- Create a New project.
- Create the Screen(View).
- Declare and Connect the properties and functions to the UI elements.
- Set actions for Background Click and text field Return events.
- Post data to URL and parse the JSON response.
4. Set Actions for Background Click and text field Return events.
We need to batch the events such as the background clicks(user taps in the empty area of the view) and when the return key in pressed in the textfields.
What i am doing here is:
- Create the action backgroundClick().
- Change the class of the view from UIView to UIControl
- Attach the action to the Touchup Inside event of the UIControl.
- Attach the action to the Did End On Exit event of both the text field.
Next: Post data to URL and parse the JSON response.
Got it by your older post.
Thaks
Hello Sir,
I have ran code and its given me following error pelase let me know what i have to do for it,
Error: Error Domain=NSURLErrorDomain Code=-1005 “The network connection was lost.” UserInfo=0x8da2030.
Thanks,
Use error_log(), instead of echo for all other outputs.
hi Dipin, my logintodb.php is below:
$host = “localhost”;
$user = “root”;
$pass = “root”;
$db=”iwll”;
$r = mysql_connect($host, $user, $pass);
if (!$r) {
echo “Could not connect to server\n”;
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo “Connection established\n”;
}
echo mysql_get_server_info() . “\n”;
$r2 = mysql_select_db($db);
if (!$r2) {
echo “Cannot select database\n”;
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo “database selected\n”;
}
$us=$_POST[‘username’];
$pw=$_POST[‘password’];
$result=mysql_query(“select username,pass from login where username=’$us’ and pass=’$pw'”);
$row=mysql_fetch_array($result);
if($row[“username”]==$us && $row[“pass”]==$pw)
{
echo ‘{“success”:1}’;
}
else
{
echo ‘{“success”:0,”error_message”:”Username and/or password is invalid.”}’;
}
Hi,
Are you ‘echo’ing anything before the ‘{“success”:1}’ ??
if i changed like that my output is:
2014-11-05 16:24:06.764 logintodb[90940:90b] Response ==> Connection established
5.5.38
database selected
{“success”:1}
2014-11-05 16:24:06.764 logintodb[90940:90b] Success: 0
and i got pop-up as Login failed
why i got initially success:1 and then success:0
pls explain me?
Change
echo ‘”success”:1’;
to
echo ‘{“success”:1}’;
nice tutorial.i have written my php code as:
if($row[“username”]==$u && $row[“pass”]==$pw)
{
echo ‘”success”:1’;
}
else
{
echo ‘{“success”:0,”error_message”:”Username and/or password is invalid.”}’;
}
but i got in console pane as:2014-11-04 12:06:14.701 logintodb[5003:90b] Response ==> Connection established
5.5.38
database selected
“success”:1
2014-11-04 12:06:14.701 logintodb[5003:90b] Success: 0
i dont know what it means?pls help me?
try 127.0.0.1:8888 instead of dipinkrishna.com
Excellent tutorial! I have tried with this code.i am using MAMP server.so i don’t know what i have to put here:
NSURL *url=[NSURL URLWithString:@”https://dipinkrishna.com/jsonlogin.php”];
could u pls help me?
If you are starting a new project, use storyboard.
xcode 6.0.1
Hey,
Which version of xcode are you using?
What do you mean by setting tab bar controller as the root view controller. Does it mean selecting this as a initial view controller? Are they same concept? How do you set a view controller as a root view controller? Could you provide sample code, please?
If you are not getting a response then it might be because your php file is throwing an error.
My latest tutorial (using swift) has DB connectivity.
Download the php source code from https://dipinkrishna.com/blog/2014/07/login-signup-screen-tutorial-xcode-6-swift-ios-8-json/
hi dipin,
thanx for your wonderful tutorial.It works for me.
but there is one problem, when i tried to change my php file code to get username and password from mysql database i got an error saying signin failed. will u pls send me a php code where mysql database connectivity is done and in that case if there is any change i would like to do in my objective C code to get response from edited php file becoz right now i am getting a response(NULL) and success:0.
thanks in advance.
THx in advance.
Its because, the server is not returning a valid json.
When i run this code, show username password is invalid.And show json data is null.why?
Hey,
If you are saving the login info and status in user defaults, then clear them and send the user to the login page.
If your website/server uses cookies, you may even clear that too.
Example:
Hello bro,
Thank you for this tutorial, i have a follow up question.. how will i end logging out the application? thank u so much
Please check your php/webserver log.
Hello,
thank you for this informative tutorial , I had one problem after adding the json code, when I ran the code and i was reading the console message, i noticed it was always taking username value as null , so I deleted the field and added it again and then it displayed the username correctly in the console, but when i did that the server in which i’m uploading the php code at got a 500 error, I deleted that php code and added it again and still facing the same error code.
can you help?
thank you!
Brilliant, works great. Thanks!
This should do:
Basically what I am trying to achieve is when your login script gives a success and I send it into a webview, I am trying to get the same information (username and password from the text inputs) into the webview also. Is their any way to do this?
Did you try POST?
ahhh I need to stop using php tags 🙂
print_r($_POST);
try using the ‘POST’ version.
Yes that is what im trying to do. Ime using this but doesn’t seem to be passing any data through
UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
//Change Frame
webView.frame = CGRectMake(webView.frame.origin.x, webView.frame.origin.y + 20, webView.frame.size.width, webView.frame.size.height);
//Create a URL object.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@”http://www.mysite.co.uk/testpost.php?username=%@&password=%@”, [_txtUsername text],[_txtPassword text]]];
//URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webView loadRequest:requestObj];
//show the webview
[self.view addSubview:webView];
The contents of the testpost.php is
If you are planning to ‘POST’ the data to the web view, see the below example:
Use [txtUsername text] and [txtPassword text]
eg:
Thanks that works like a charm, just one more.
Is their any way to pass the post data used to verify the username and pass into the web view?
This is a quick fix:
Scratch that last question I manage to figure it out, I used the second method you gave me. just one more question, my app is sitting over the navigation bar, is there any way I can set the size of the uiwebview or just get it to nudge down a little so its not under the clock? Thanks for all your help!
Hi,
If you want to go to another view/screen then use:
Or if you just want to show a uiwebview then use:
You can add as many params as you want to this line:
See: http://stackoverflow.com/questions/8798725/get-device-token-for-push-notification on how to get the device id.
Also how do I get the code to point to a UIWebView I have created if the login is a success?
Great tutorial, How would I add a device id into this submission so I can store it for the purpose of push notifications?
Thank you sir, for this tutorial
this tutorial is provide good platform for bigeners.
thanks allot…..
There is no response.
If it shows ‘It Works’ for the url you mentioned, then its some apache issue.
in adittion I am receiving this messages in console
2014-01-14 17:11:46.829 LoginJSon[1067:a0b] Response ==>
2014-01-14 17:11:46.830 LoginJSon[1067:a0b] (null)
2014-01-14 17:11:46.830 LoginJSon[1067:a0b] 0
Hi guys well structure tutotial. I am having a problem. When I put the original url NSURL *url=[NSURL URLWithString:@”https://dipinkrishna.com/jsonlogin.php”];
the programs work perfectly. But when I put there my local addres it does not work I am putting http://localhost/jose/jsonlogin.php“. has anyone had the same proble any suggestions?. I tried restarting apache but it still not working. When i write in my browser localhost it shows “it works”.
thanks
You can find the code in the post itself.
Sir, Its really help for me. Is the perfect tutorial for beginers. I need to know the code of the login page.
The tutorial will be using
Xcode5 + iOS7 + storyboard + json
hi, i will prepare the tutorial this week.
Hi,
i will prepare the tutorial this week.
can u send me the same tutorial which is developed in xcode 5??It’ll be very helpful to me. Thanks in advance…
Hi Dipin,
Any idea when an Xcode 5/IOS 7 version will be available?
Thanks
Jon
Its there at the end of the article.
https://dipinkrishna.com/blog/2012/03/iphoneios-programming-login-screen-post-data-url-parses-json-response/5
how can i get source code for this project please tell me…
Use:
instead of the alertView when the login is success.
Hi, I’ve successfully launched your program, great work thanks.
I would just like to know if how can I go to the next page after login in
if(success == 1)
{
NSLog(@”Login SUCCESS”);
[self alertStatus:@”Logged in Successfully.” :@”Login Success!”];
//enter code to next page here. (what code do I enter here)
} else {
thanks and regards
The server should send a json response for it to work.
Sorry about it
Im logged in
but I’m getting output in html format..
what should i do??
i mean, you are getting success=0 because you are sending { ‘success’ : 0 } from the server.
i didn’t get you??
Seems to be a server side problem.
you should be sending { ‘success’ : 1 } if login was success.
hi dipin , i really appreciate your work
i have changed the parameters n also I’m providing right credentials but still it gives error “Login failed”.
the response code is 200 and success=0
what should be the problem?
Plz guide me I’m new to iphone development
thanks in advance.. 🙂
ok that error got cleared but now I get response code 415
my code looks like this:NSString *post =[[NSString alloc] initWithFormat:@”{\”username\”:\”%@\”,\”password\”:\”%@\”}”,[self.txtUserName text],[self.txtPaswd text]];
NSURL *url=[NSURL URLWithString:@”http://112.23.82.110:9080/SSR/webapi/pager1/login”];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@”%d”, [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@”POST”];
[request setValue:postLength forHTTPHeaderField:@”Content-Length”];
[request setValue:@”application/json” forHTTPHeaderField:@”Accept”];
[request setValue:@”application/x-www-form-urlencoded” forHTTPHeaderField:@”Content-Type”];
[request setHTTPBody:postData];
Can you copy/paste your block of code?
yes, my backend application has published the restfult web service which I consume to interact with that app.
Are you trying to send a json string to your api?
Thanks for this great tutorial.
I ma new to iOS/JSON programming and need help here. I send my data to the restful servce url in this format {“username:”myuser”,”password”:”mypassword”} but I get an error -JSONRepresentation failed, not a valid type for JSON,
Please help
Cool thanks!
Ok. I will roll one out as soon as possible.
Are there any plans to update this to iOS 7? JSON parsing is now a part of the framework no need for 3rd party libraries.
great tut. Apple says that they will reject this setAllowsAnyHTTPSCertificate:forHost because it’s using a non-public API/s in the app. Would you know how to resolve this?
thanks
thanks, nice tutorial
Hey,
I think, after successful login, you are showing an alertview and then moving to another viewcontroller.
It would be better if you move the code for “Moving to second screen” to the click event of uialertview’s ok button.
Lets assume that the current code is:
Lets add a tag to the alertview, and then move the code to alertview’s ‘clickedButtonAtIndex’ event.
And add this:
scratch that. It doesn’t work. I think it has something to do with pressing ok on the alertview while already in another view. Any ideas? lol
found the solution! . For some reason, I had an extra nil in the alertview after you successfully log in . Works after I removed it!
hey man, awesome tutorial!
I am trying it again now that I upgraded to xcode 5.0 and ios 7. and it seems to throw an exception and crash the program. Do you have any clue what it could be?
Hi,
If you are not using https, then you can remove that line.
or add these lines to the top of the controller.
Hello Sir,
I have facing the problem with this line plz help me regarding ths . ths show a error
how cn i resolve ths.
plz send me mail regarding solution.
// [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
Ok. thank u for the reply
I haven’t changed the password.
Make sure your are making a POST request. Try logging the username and password.
Hi, first I would to thanked u for this great tutorial. I’ve been following it step by step and I succeeded. However, just now I try to log in using the username “dipinkrishna” and password “password” but there is an error popup msg saying that the username/password is invalid. I’ve checked in the codes there’re no such message will be appear if the login failed. I wonder is the username and password have been change or something? many thanks in advance
Please see my reply to previous comment. Thanks.
Hello Sir,
Thanks for this tutorial.I am very new in IOS and Objective C.
I have one query that,I have created application with multiple screen,1st one is login screen,my query is that if successfully login is done then it transfer to new screen otherwise not.What to do plz help me as soon as possible.
Thanks in advance
Use:
instead of the alertView when the login is success.
Hi Dipin,
Thanks for tutorial,I am very new in IOS.I have a query that i want if login is succesfully done then it will transfer to the new view control otherwise keep it in Login Screen.can you help me…
Can you post that portion of your code?
GNU gdb 6.3.50-20050815 (Apple version gdb-1708) (Mon Aug 8 20:32:45 UTC 2011)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type “show copying” to see the conditions.
There is absolutely no warranty for GDB. Type “show warranty” for details.
This GDB was configured as “x86_64-apple-darwin”.sharedlibrary apply-load-rules all
Attaching to process 1065.
2013-08-09 13:21:07.595 jsonLogin[1065:f803] PostData: user_name=Sunil%20Parmar&password=sunil123
2013-08-09 13:21:07.603 jsonLogin[1065:f803] urldata is: (null)
2013-08-09 13:21:07.604 jsonLogin[1065:f803] Response code: 0
2013-08-09 13:21:07.605 jsonLogin[1065:f803] Error: Error Domain=NSURLErrorDomain Code=-1000 “bad URL” UserInfo=0xb59dd00 {NSUnderlyingError=0xb59d9b0 “bad URL”, NSLocalizedDescription=bad URL}
(gdb)
still this problm is coming… i try alot.. but not working… still give connection fail.. login fail
Hey,
Its better to use “presentViewController” for the login screen.
In your Appdelegate please set the tab bar controller as the root view controller.
Then, use the following line in the viewDidLoad method of the main view of the tab controller.
You can use
in the loginScreen view controller to return to the tab bar controller.
Thanks.
You are having some issue with the url. Maybe it contains spaces. Plz check it.
Also, try changing this line:
to:
GNU gdb 6.3.50-20050815 (Apple version gdb-1708) (Mon Aug 8 20:32:45 UTC 2011)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type “show copying” to see the conditions.
There is absolutely no warranty for GDB. Type “show warranty” for details.
This GDB was configured as “x86_64-apple-darwin”.sharedlibrary apply-load-rules all
Attaching to process 1474.
2013-08-08 16:19:48.046 jsonLogin[1474:f803] PostData: username=Sunil Parmar&password=sunil123
2013-08-08 16:19:48.079 jsonLogin[1474:f803] Response code: 0
2013-08-08 16:19:48.081 jsonLogin[1474:f803] Error: Error Domain=NSURLErrorDomain Code=-1000 “bad URL” UserInfo=0x6eb06f0 {NSUnderlyingError=0x6eb03a0 “bad URL”, NSLocalizedDescription=bad URL}
i write as per yr code … but stilll …. login fail is display….
Hey Dipin, great walkthrough! Informative and concise, just the way I like it. I was wondering if you could help me with something … I want this login view controller to be the initial view , however I must have my tab controller as the root view. How would I making the login screen initial and then pushing it into the tab bar controller. Please bear in mind, I am extremely new to objective C and iOS programming. Brand new computer science graduate , so I atleast know the basics 😛
Hi Akash,
What are you trying to achieve? I went through your code. You doesn’t seem to do anything with the response.
Hey Dipin,
I need to create login for private site. I could successfully implement your code but in my case, it is not JSON.
Here’s the gist for my code. I get “login successful message but nothing else is happening.”
https://gist.github.com/akashtrivedi/e1df0b88a9c61ffbf158
I’d appreciate if you could help. thanks
Hi,
When you get a success, replace the alert with the following code.
This creates and loads a UIWebView with html.
The html content has the JS code to post data to an url.
Please adjust the url and the name fields.
Thanks!
Works great thanks! if the login is successful how can I make it redirect to a URL with the posted variables? for example http://www.domain.com/index.php?username=POSTED-USERNAME&password=POSTED-PASSWORD
Dipin, like everyone else said, this tutorial is the best I’ve seen out there. I’m trying to tailor what you’ve posted to a URL in an iOS login page. The URL is https://quantdesk.lucenaresearch.com/#login. I changed the login field and added the required line for an https url.
My result is that I get
2013-07-08 15:17:29.762 LoginJson[51681:c07] PostData: [email protected]&password=xxxxxxxxx
2013-07-08 15:17:30.068 LoginJson[51681:c07] Response code: 405
(lldb)
It seems like the method is not accepted. Do you have any idea how to resolve this issue?
In the developer console when I login with my credentials on the actual web browser, the response is as follows
Request URL:https://quantdesk.lucenaresearch.com/lr/api/token
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:56
Content-Type:application/json
Cookie:__utma=216204950.464340013.1373310569.1373310569.1373310569.1; __utmb=216204950.1.9.1373311137524; __utmc=216204950; __utmz=216204950.1373310569.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
Host:quantdesk.lucenaresearch.com
Origin:https://quantdesk.lucenaresearch.com
Referer:https://quantdesk.lucenaresearch.com/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
{user:xxxxxxx, pass:xxxxxxxxx}
pass: xxxxxxxxx
user: xxxxxxxxx
Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Keep-Alive,Authorization,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:https://quantdesk.lucenaresearch.com
Connection:keep-alive
Content-Encoding:gzip
Content-Type:application/json;charset=UTF-8
Date:Mon, 08 Jul 2013 19:18:57 GMT
Server:nginx
Transfer-Encoding:chunked
Vary:Accept-Encoding
thnx…
Cool.
Thanks you very much. It’s run succesfull.
This is the url I used json, it returns data.
http://87.106.216.32/mfdbservice/json.aspx?name=mf_avl_login&%%40UserName=qazvin133&%%40Password=qazvin133
You could use a xml parser instead of the Json library.
Are you sure that the server is returning any data?
heyyy..
i m getting response data in xml…
how can i display it in my app?
please reply me asap…
I run program and it have response result:
2013-07-02 16:52:17.708 avl[5734:12e03] PostData: UserName=qazvin133&Password=qazvin133
2013-07-02 16:52:22.825 avl[5734:12e03] Response code: 200
2013-07-02 16:52:22.826 avl[5734:12e03] Response ==>
2013-07-02 16:52:23.322 avl[5734:12e03] (null)
2013-07-02 16:52:23.322 avl[5734:12e03] 0
Sorry, i wasn’t available last day.
Nevermind again, I figured it out!
NSString *retUser =(NSString *)[jsonData objectForKey:@”user”];
Thank you!
Oh, I actually figured that part out by adding all json “m” to the Build Phases, Compile Sources.
I do have another question for you however. The way you wrote your php you return a 0 or 1. In mine, I actually look to return a String. how would I rewrite this part of the objC code to return a string versus the int?
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSLog(@”%@”,jsonData);
NSInteger success = [(NSNumber *) [jsonData objectForKey:@”success”] integerValue];
NSLog(@”%d”,success);
Yep, you were right it fixed that error. But now I get a new one:
Undefined symbols for architecture i386:
“_OBJC_CLASS_$_SBJsonParser”, referenced from:
objc-class-ref in Login.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Any thoughts on why I would see this? Thank you so much.
YOu might be using a wrong Json Library.
Great tutorial, everything works except I receive an error on this line:
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData:nil];
The error: no visible @interface for SBJsonParser declares the selecter ‘objectWithString:error’
I’m in to modify the JSON framework, change imports, or tweak code? Thank you.
Hi,
The Json parsing section in my code, looks for a format
{“success”:1, error_message: “message”}
Your’s might be something different. Please check and change the code accordingly.
grt tutorial…
my problem is i m getting this error:
Response code: 200
Object reference not set to an instance of an object.
You could use a navigation controller to move to the next screen.
Replace the code for “success” alert with it.
first of all, this is a great tutorial. my problem is how can i set when login successfully the program will jump to next view and only when the login failed the alter will comes out..
thanks Dipin
This was a very difficult debug on my side. I didn’t think about mod_rewrite which is because my website converts any urls without www to have www. When it does this, the POST data is lost. So adding www fixed it for me. I imagine redirecting urls and other things would give a similar issue.
I din’t get u. Can you be more specific?
how i get the actual location of user..not of the device which are fixed in xcode debug arrow..please reply me asp.
Nice tutorial
great tutorial ||
Your web url doesn’t return a json response, it returns just “1”.
– (IBAction)Signin:(id)sender {
@try {
if([[username text] isEqualToString:@””] || [[password text] isEqualToString:@””] ) {
[self alertStatus:@”Please enter both Username and Password” :@”Login Failed!”];
} else {
NSString *post =[[NSString alloc] initWithFormat:@”userName=%@&password=%@”,[username text],[password text]];
NSLog(@”PostData: %@”,post);
NSURL *url=[NSURL URLWithString:@”http://cgi.soic.indiana.edu/~team34/login.php”];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@”%d”, [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@”POST”];
[request setValue:postLength forHTTPHeaderField:@”Content-Length”];
[request setValue:@”application/json” forHTTPHeaderField:@”Accept”];
[request setValue:@”application/x-www-form-urlencoded” forHTTPHeaderField:@”Content-Type”];
[request setHTTPBody:postData];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@”Response code: %d”, [response statusCode]);
if ([response statusCode] >=200 && [response statusCode] %@”, responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSLog(@”%@”,jsonData);
NSInteger success = [(NSNumber *) [jsonData objectForKey:@”success”] integerValue];
NSLog(@”%d”,success);
if(success == 1)
{
NSLog(@”Login SUCCESS”);
[self alertStatus:@”Logged in Successfully.” :@”Login Success!”];
} else {
NSString *error_msg = (NSString *) [jsonData objectForKey:@”error_message”];
[self alertStatus:error_msg :@”Login Failed!”];
}
} else {
if (error) NSLog(@”Error: %@”, error);
[self alertStatus:@”Connection Failed” :@”Login Failed!”];
}
}
}
@catch (NSException * e) {
NSLog(@”Exception: %@”, e);
[self alertStatus:@”Login Failed.” :@”Login Failed!”];
}
}
– (IBAction)backgroundClick:(id)sender {
[password resignFirstResponder];
[username resignFirstResponder];
}
Can you post the code block here?
I am having issues with trying to connect the login to my mysql server. I keep getting this in the output in Xcode : 2013-04-23 20:25:46.990 FriendsOnTap[68927:f803] PostData: userName=k&password=k
2013-04-23 20:25:47.149 FriendsOnTap[68927:f803] Response code: 200
2013-04-23 20:25:47.150 FriendsOnTap[68927:f803] Response ==> 1
2013-04-23 20:25:47.150 FriendsOnTap[68927:f803] (null)
2013-04-23 20:25:47.150 FriendsOnTap[68927:f803] 0
Then it says login failed and it pushes to the next to view anyways.
This is great !!
Appreciate your effort . I could run the application and test the code . Thank you Dipin .
Yep. its better to add a navigation controller to navigate through the views.
it worked for me when i changed header.But please let me know if I cab add more views to this project and how to do that?I dont have a Navigation Control.Do I need to add that?
Your server side doesn’t matter as long as the app gets a proper json response from it.
Please post your json string here. I will give you the code to parse it.
Hi,
Please let me know how to make this work fo my login app which has a rails back ground.This doesnt work for me.In android app I am creating a json Object named user and username and password are inside user.
Great! 🙂
i found it on following this tutorial also 🙂
hey! thank you for this great tutorial 🙂
plz if you have a similar tutorial for a registration form ( when i click on submit button , data must be stored in database) can you give me code i write in .m file
thank you
@try {
if([[emailTextfield text] isEqualToString:@””] || [[passwordTextfield text] isEqualToString:@””] ) {
[self alertStatus:@”Please enter both Username and Password” :@”Login Failed!”];
} else {
NSString *loginTag = @”login”;
NSString *post =[[NSString alloc] initWithFormat:@”tag=%@&email=%@&password=%@”,loginTag,[emailTextfield text],[passwordTextfield text]];
NSLog(@”PostData: %@”,post);
NSURL *url=[NSURL URLWithString:@”http://www.businessreputationalert.com/android_apps/”];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@”%d”, [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@”POST”];
[request setValue:postLength forHTTPHeaderField:@”Content-Length”];
[request setValue:@”application/json” forHTTPHeaderField:@”Accept”];
[request setValue:@”application/x-www-form-urlencoded” forHTTPHeaderField:@”Content-Type”];
[request setHTTPBody:postData];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@”Response code: %d”, [response statusCode]);
if ([response statusCode] >=200 && [response statusCode] %@”, responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSLog(@”=============>>>>%@”,jsonData);
NSInteger success = [(NSNumber *) [jsonData objectForKey:@”success”] integerValue];
NSLog(@”%d”,success);
if(success == 1)
{
NSLog(@”Login SUCCESS”);
[self alertStatus:@”Logged in Successfully.” :@”Login Success!”];
} else {
NSString *error_msg = (NSString *) [jsonData objectForKey:@”error_message”];
[self alertStatus:error_msg :@”Login Failed!”];
}
} else {
if (error) NSLog(@”Error: %@”, error);
[self alertStatus:@”Connection Failed” :@”Login Failed!”];
}
}
}
@catch (NSException * e) {
NSLog(@”Exception: %@”, e);
[self alertStatus:@”Login Failed.” :@”Login Failed!”];
}
i have changed the code like this.
but the problem is in parsing the data. NSLog(@”=============>>>>%@”,jsonData); this line return me a null value. can you tell me how to fixed that?
Hey,
Please do the necessary changes in the code to parse your json response.
This is a great tutorial for all the beginners like me but only problem is i am using a different url. and although i am giving a correct username and password it is showing me a msg field “login failed”.
debugger says me..
Response ==> {“tag”:”login”,”success”:1,”error”:0,”uid”:”76″,”user”:{“email”:”[email protected]”},”profile”:[{“profile_id”:”84″,”profile_name”:”Toyota Of Manhattan”},{“profile_id”:”82″,”profile_name”:”Mercedes-Benz of Nanuet”}…………..
……410670288&v=wall”,”date”:”13\/10\/12″,”profile_id”:”79″}]}
2013-03-21 16:58:07.663 Buisness Reputation[1984:c07] =============>>>>(null)
2013-03-21 16:58:07.663 Buisness Reputation[1984:c07] 0
Great Tutorial…
Thank you very much..!
Hey, i have send you a mail. Please reply to that.
– (IBAction)LOGIN:(id)sender {
@try {
if([[_Name text] isEqualToString:@””] || [[_Passwort text] isEqualToString:@””] ) {
} else {
NSString *post =[[NSString alloc] initWithFormat:@”email=%@&password=%@”,[_Name text],[_Passwort text]];
NSLog(@”PostData: %@”,post);
NSURL *url=[NSURL URLWithString:@”http://www.myURL.php”];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@”%d”, [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@”POST”];
[request setValue:postLength forHTTPHeaderField:@”Content-Length”];
[request setValue:@”application/json” forHTTPHeaderField:@”Accept”];
[request setValue:@”application/x-www-form-urlencoded” forHTTPHeaderField:@”Content-Type”];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@”Response code: %d”, [response statusCode]);
if ([response statusCode] >=200 && [response statusCode] %@”, responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSLog(@”%@”,jsonData);
NSInteger success = [(NSNumber *) [jsonData objectForKey:@”success”] integerValue];
NSLog(@”%d”,success);
if(success == 1)
{
NSLog(@”Login SUCCESS”);
UIAlertView *PopUp = [[UIAlertView alloc]
initWithTitle:@”Logged in (y)”
message:@”Welcome”
delegate:nil
cancelButtonTitle:@”Ok”
otherButtonTitles:nil];
[PopUp show];
} else {
NSString *error_msg = (NSString *) [jsonData objectForKey:@”error_message”];
}
} else {
if (error) NSLog(@”Error: %@”, error);
}
}
}
@catch (NSException * e) {
NSLog(@”Exception: %@”, e);
}
}
@end
Please post your code.
Ok i checked my URL and it was wrong -.-
But there’s now another mistake:
2013-03-13 15:01:51.689 Test[2434:c07] PostData: [email protected]&password=test
2013-03-13 15:01:51.828 Test[2434:c07] Response code: 200
2013-03-13 15:01:51.828 Test[2434:c07] Response ==>
2013-03-13 15:01:51.828 Test[2434:c07] (null)
2013-03-13 15:01:51.829 Test[2434:c07] 0
404 is page not found error.
Double check your url.
In the JSON Code was a little mistake and now come this fail:
2013-03-13 14:32:49.014 Test[1720:c07] PostData: [email protected]&password=test
2013-03-13 14:32:49.335 Test[1720:c07] Response code: 404
(lldb)
Can you post the block of code from ‘Posting’ to ‘Parsing Jason’ ?
Okay, thanks for your answer.Now the mistakes are away.
But in Xcode at “All Output” comes the following failure:
2013-03-13 14:13:50.923 Test[99093:c07] PostData: [email protected]&password=test
2013-03-13 14:13:51.388 Test[99093:c07] Response code: 200
2013-03-13 14:13:51.389 Test[99093:c07] Response ==> Fehler
2013-03-13 14:13:51.389 Test[99093:c07] (null)
2013-03-13 14:13:51.389 Test[99093:c07] 0
do you have an idea, why it’s so?
If you are removing the alertview then remove all the references to that too.
Hi, thanks for this great tutorial.
When I delete the code: – (void) alertStatus:(NSString *)msg :(NSString *)title
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@”..”
message:@”no”
delegate:self
cancelButtonTitle:@”Ok”
otherButtonTitles:nil, nil];
[alertView show];
}
When I delete this, I get the fail “No visible @interface for ‘ViewController’ declares the selector ‘alertStatus::’
I hope you can help me.
When I didn’t delete the code, in te simulator came always only the AlertView.
Hi Dipin, It is almost completed. just password validation is remained.
hii….nice tutorial… well i want to check login credential for facebook or twitter kind of site. I want to implement login page which ask login through facebook. How to use the above code for this requirement. Thanks in advance.
Hi Sudheer,
I haven’t got a reply from you. Hope, your issue has been revolved.
No, I’m stuck.
Hi mark,
For the username/password input fields we need to assign an object to hold/access it.
For the button, we need to assign an action which will be called when its clicked.
Please watch the video. Thanks.
Hi,
When you say, 2. Right click on the text fields and bind the properties for it.
3. Right click on the login button and bind a action to it.
What do you exactly mean? Can you elaborate it in detail plz.
Hi Ori Dahan, Did you solved the issue.Here is urgent requirement to solve the issue.
No. Don’t put it into an array.
Make it:
{“message”:”Welcome To JSON”,”success”:1}
and you could use the old code itself.
NSInteger success = [(NSNumber *) [jsonData objectForKey:@”success”] integerValue];
Yes, what changes you want me to do in the webservice?
Do you want me to change the JSON to
[login={“message”:”Welcome To JSON”,”success”:1}]
But then how will the JSON processing work.
Pingback: The beginning of my first iPhone project | Michael DiNicola Blog
Do you have control of the webservice?
Hi Dipin,
I tried to replace the line, but it gives foll error
No visible @interface for ‘NSDictionary’ declares the selector ‘objectAtIndex’
The response looks like a json array.
Try :
Hi Dipin,
Thanks a lot for this tutorial.
When I run the app, on this line
NSInteger success = [(NSNumber *) [jsonData objectForKey:@”success”] integerValue];
I get the foll error
JSON response from webservice:
[{“message”:”Welcome To JSON”,”success”:1}]
Console:
2013-02-23 09:30:55.946 Json[2836:c07] -[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x76b6790
2013-02-23 09:30:55.946 Json[2836:c07] Exception: -[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x76b6790
Please Help Me..
No, I did not find the solution yet.
The login I try to implement had no JSON response because the encoding was wrong.
After I changed the encoding I am getting a response but can’t login.
Probably becuase the login I’m trying to implement is HTTP login, I’m currently trying to find another way to login (using NSURLConnection).
Hope I will be able to do it
Hi Ori Dahan, Exactly I am facing the same issue, trying to login to a website in ios app but no json response. I saw your ques in stack overflow. Did you overcome this issue, if so can you please send me the view controller.m file. Awaiting for your reply.
If the url is the only value you are returning, then it will be present in ‘responseData”.
Check out the logs.
Hi Dipin, Good Tutorial. It helped me a lot. I have one issue remained ,expecting your help in this issue. My url which I used is in the codeline
NSURL *url=[NSURL URLWithString:@”https://dipinkrishna.com/jsonlogin.php”];
is returning one URL. And I need to access the URL after the login with the secure code which is in that url. I think you got what I am willing to get from you.
If you are asking about web sessions, then, yes it will persists. The cookies are saved.
For the redirection: Do you have a navigation controller? If yes, then just push the new view into it.
can you tell also about the sessions and redirection like i want to redirect to the new view when login sucess fully
Yes, it should work as long as you are running it in the simulator.
what if i want to change the link of login file from the live server to my localhost link ? is that work ? bcox i tried and it dont work
Sorry it need to be ‘alertView.tag’
Hi Dipin, I got error when I used the same code published by you. and the error is in the line
in DKViewController.m file, alertStatus method
–> if (tag) alert.tag = tag;
(Semantic issue: use of undeclared Identifier: ‘alert’) .
can You please check it out and help me in this regard.
Lets add a tag to the alertView.
Change the alertStatus method to:
And now pass in the tag to alertStatus.
[self alertStatus:@”Logged in Successfully.” :@”Login Success!” :101];
[self alertStatus:error_msg :@”Login Failed!” :0];
And now update the alertView’s clickedButtonAtIndex method.
{
{
}
}
There might be typos and bugs.
Hope this helps.
Hi Dipin Krishna, At first I am very thankful to you by responding with the code what I required. Thank you very much. After logged in successfully application is opening my URL. now one more issue is raised and the issue is here goes,
when I give the wrong login credentials then invalid username/password pop up is displaying. up to that fine but when I click on ‘ok’ on the pop up again the application is redirecting to given URL. Our requirement is if we have wrong login credentials we can’t open the url to access. may I get the code how to resolve this issue
Hi Sudheer,
Add UIAlertViewDelegate to the interface of your view controller.
In my example, change the @interface line in the file DKViewController.h to:
Then add the following code to the “.m” file.
{
{
}
}
This opens the url in safari.
I haven’t tested this, there might be typos and bug.
But, you could get an idea on what to do.
Thanks for contacting.
Hi Dipin Krishna, Today you saved my day. This tutorial helped me a lot. I had one doubt I need help 4m you in this regard. After access from the web service i.e logged in successfully pop up I would want to redirect into an external url(my application). may I know the procedure..
awaiting for reply, thanks in advance
Thanks.
Please check your logs, try to debug.
You can easily find out the issue.
Hello,
Excellent tutorial. Thanks so much.
One thing though,
I can’t seem too get it to login successfully.
I’ve followed your tutorial to the exact, but it’s just saying
“Username and/or Password is invalid”
Any suggestions? Thanks.
Good Job Brother!
I’m new in iOS development. Still dissecting each line of the loginClicked function though. Its very helpful to understand the logic and processes within it.
Thanks a lot!
I have send you a mail. Reply to that.
Sure, where to?
Can you send me your login url and your viewController.m file?
Still not working, what else should I change except from the url?
How can I know which parameters to change?
If you are accessing https urls,
Please add the below code to DKViewController.m, just below the import statements.
@interface NSURLRequest (DummyInterface)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;
@end
Which parameters do you refer to?
Does it matter if it’s an https website?
Thanks, again.
Its simple, just replace the url with your login url.
Do adjust the parameters also.
Hello,
Thanks for a great tutorial!
I would like to use the above code in a specific website, how can I adjust the above code to work with it?
I tried replacing the url in the following line with no luck:
NSURL *url=[NSURL URLWithString:@”https://dipinkrishna.com/jsonlogin.php”];
Can you help me adjust it properly?
Thanks!
🙂
Hey , Got it !!!
Yes .
Hi Bharath,
Are you using a “Navigation Controller”?
Hey , how do i navigate to the home screen if the login is successful ?
Hi..I am new to iphone apps… this tutorial is very good. I need to redirect to a home page if the user name and password entered is correct. can u please suggest me code.
Hi,
You could use NSUserdefaults.
Setting Value:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setInteger:1 forKey:@”isLoggedIn”];
Retrieving Value:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSInteger isLoggedIn = [prefs integerForKey:@”isLoggedIn”];
Hello, great tutorial… How can I save the user credidentials in my app so the user doesn’t have to log in each time the app loads? If there is no user logged in, then I want the app to show the login page. If there is already a user logged in or upon successful login, I want to go to default app view. I then want to show a log out button that clears the user credidentials and goes back to login page… How can I do this? Thanks.
Hi Dipin,
I have UIImageView and an image has been added to it. This image view has been added to a view (which has a different background image).
I need to rub/scratch the image so that it will be made transparent (like an eraser effect). I am using the below code to do it and the code works fine.
– (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
lastTouch = [touch locationInView:bk]; // http://stackoverflow.com/questions/12329766/transparency-on-uiimageview-should-show-image
NSLog(@”last touch is %@”, NSStringFromCGPoint(lastTouch));
}
– (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
currentTouch = [touch locationInView:bk]; // bk is UIImageView
NSLog(@”last touch is %@”, NSStringFromCGPoint(currentTouch));
CGFloat brushSize = 35;
CGColorRef strokeColor = [UIColor whiteColor].CGColor; // it’s like CGSize CGPoint structure..
UIGraphicsBeginImageContext(bk.frame.size); // need to put scratch view??
CGContextRef context = UIGraphicsGetCurrentContext();
[bk.image drawInRect:CGRectMake(0, 0, bk.frame.size.width, bk.frame.size.height)];
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, brushSize);
CGContextSetStrokeColorWithColor(context, strokeColor);
CGContextSetBlendMode(context, kCGBlendModeClear);
CGContextBeginPath(context);
CGContextMoveToPoint(context, lastTouch.x, lastTouch.y);
CGContextAddLineToPoint(context, currentTouch.x, currentTouch.y);
CGContextStrokePath(context);
bk.image = UIGraphicsGetImageFromCurrentImageContext(); // here the image will be becoming transparent
UIGraphicsEndImageContext();
lastTouch = [touch locationInView:bk];
}
How I do check if the image is completely transparent and the background image is fully visible? How can I keep track of this complete transparency of the first image?
Please guide me.
Cheers,
Bharani 🙂
No need brother….i have cured it
excellent tutorial….really really hats off to u for ur selfless work
keep going 🙂 🙂 🙂
Hey i am getting an error on this line
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
the error says : no visible @interface for SBJsonParser declares the selecter ‘objectWithString:error’
Please Help ME
Hey i have created a project “registration”,with name,email amd password…that will post to a url using Post menthod,
How can i create a login page for that dat,
(i will mail you the project,registraion..please give me ur mail id)
Please help…..
NSJSONSerialization came with ios5. I haven’t used it till now.
I don’t think that it would be anything different.
I will prefer to use native library if and only if the class methods are easier and faster than the 3rd party libraries.
Have you done this (or something similar) with the JSON library that comes with the iOS?
Would it be very different?
I just want to check whether user name and password is valid. Like we have tutorials for Facebook right? http://www.raywenderlich.com/1488/how-to-use-facebooks-new-graph-api-from-your-iphone-app…
Hi,
Do you want to just authenticate using gmail username/password? (i.e check whether username/password exists.)
Or
Do you want to allow your application to access contents of a google account?
Sorry to disturb again. Could you please share some tutorials / examples for integrating gmail login in iphone app? It’s bit urgent.. Can u help it out?
No. I think.
Hi, Do we have an option of adding placeholder to UITextView using Interface Builder (like we’ll do it for UITextField)? If yes, please share it..
Thanks,
Bharani..
Thank you very much for the guidance..!! I’ll start looking on it..
Hi,
I will be pretty difficult to do it without an api.
What we can do is.
1. Login into way2sms using the username and password by posting it to the login url.
2. Now, the toughest part.
a. Find out the url to which we can post the message, so that it will process the request.
b. Find out the parameters that you will need to pass in.
c. Post it.
3. Process the HTML returned.
🙂
Hi…!! I’m planning to develop an iPhone app which should be integrated with Way2Sms (http://site2.way2sms.com/content/prehome.jsp?) /160By2 ( free messaging services to India). I couldn’t find any APIs related to it. Could you please guide me on this or provide any sample code? Thank you very much…!! Bharani….: )
Good to know… 🙂
Hi.. The above problem is solved.. I just reinstalled the webserver and everything is working fine now.. Thanks….
Hi.. I have followed your tutorial.. Everything worked well.. But I think I am having issues related to my webserver.. If I give http://localhost or http://127.0.0.1 or http://myComputerIpAddress in my browser, I am getting “It works”. But when I give http://127.0.0.1/anyFileName.php or http://myComputerIpAddress.php, I am getting “Not found.The requested URL /myFile.php was not found on this server.” But it works for http://localhost/myFile.php.
Please help.
Thanks for your time.
Julian,
Sorry. If you are not using https, just remove the below line from DKViewController.m
Or if you are accessing https urls,
Please add the below code to DKViewController.m, just below the import statements.
🙂
Hi there,
First, thanks for posting all these tutorials.
I”m getting “No known class method for selector ‘[NSURLRequest setAllowsAnyHTTPSCertificate:forHost.’
Any idea how I can fix this?
Thanks!
One of the best tutorials….!!!!:) Nice one….
It doesn’t maintain the sessions. You should store the session after the login gets successful. And the next time the app starts, look for a valid session. If present, skip the login screen or do a auto login.
Thanks.
Best explained login tutorial around, I have found so many sample projects but are not this well explained, great great job.
One final question/request, does this maintains the session or what could I do in order for it to always open the app “as logged-in” instead of logging in on app start.
Regards.
Excellent tutorial. Best tutorial on this topic. Many Thanks.
Done.
Yep, the final part(5) will be posted today.
Hi,
thanks very much for the great tutorial.
Are you considering to post the final part (5) sometime soon?
Thanks,
Tuna