I have a URL that when typed into a browser (EG Safari) requests a username and password, the response API comes back in the form of JSON.
Now I'm trying to connect to this API in my iOS app so I can work with the JSON data and I'm not sure if I'm going about it the correct way.
NSString *post = [NSString stringWithFormat:@"&Username=%@&Password=%@",@"username",@"password"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSString *string = [NSString stringWithFormat:@"jsonURL"];
NSURL *url = [NSURL URLWithString:string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(connection)
{
NSLog(@"connection success");
}
else
{
NSLog(@"connection could not be made");
}
The NSLog is coming back with a "connection success" response. However, I can't seem to load the JSON response into an NSDictionary or NSArray. I've used NSJSONSerialization here.
NSMutableData *urlData;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
urlData = [[NSMutableData alloc] init];
NSLog(@"DID RECEIVE RESPONSE %@", urlData);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
[urlData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"FINISHED LOADING DATA %@", connection);
NSError *jsonParsingError = nil;
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&jsonParsingError];
if (jsonParsingError) {
NSLog(@"JSON ERROR: %@", [jsonParsingError localizedDescription]);
} else {
NSLog(@"Parsed Object is %@", parsedObject);
}
}
And here is my JSON error from the NSLog: "JSON ERROR: The operation couldn't be completed. (Cocoa error 3840.)"
Where am I going wrong? Thanks in advance.
NSString *jsonstring = [NSString stringWithFormat:@"{\"userName\":\"%@\",\"password\":\"%@\",\"loginFrom\":\"2\",\"loginIp\":\"%@\"}",[username_text removequotes],[password_text removequotes],ipaddress];//The removeQuotes method is used to escape sequence the " to \" so that the json structure won't break. If the user give " in the username or password field and if we dint handle that the json structure will break and may give an expection.
NSLog(@"the json string we are sending is %@",jsonstring);
NSData *strdata = [json1 dataUsingEncoding:NSUTF8StringEncoding];
NSString *fixedURL =[NSString stringWithFormat:@"%@",loginURL];//the url is saved in loginURL variable.
NSURL *url = [NSURL URLWithString:fixedURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[request setHTTPMethod:@"POST"];
[request setHTTPBody: strdata];
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
NSLog(@"Connected to service waiting for response");
}
Example code for login using json web services
Finally resolved this. Use:
-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge previousFailureCount] == 0) {
NSLog(@"received authentication challenge");
NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"username"
password:@"password"
persistence:NSURLCredentialPersistenceForSession];
NSLog(@"credential created");
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
NSLog(@"responded to authentication challenge");
}
else {
NSLog(@"previous authentication failure");
}
}
You actually don't need to set request values (eg: [request setValue:postLength forHTTPHeaderField:@"Content-Length"];) etc etc
Connect with a:
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
and handle the JSON response data with:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
urlData = [[NSMutableData alloc] init];
NSLog(@"DID RECEIVE RESPONSE");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
NSLog(@"THE RAW DATA IS %@", data);
[urlData appendData:data];
NSString *strRes = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"LOGGING THE DATA STRING %@", strRes);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"FINISHED LOADING DATA %@", connection);
NSError *jsonParsingError = nil;
//id object = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&jsonParsingError];
NSArray *parsedObject = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&jsonParsingError];
NSLog(@"RESPONSE: %@",[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]);
if (jsonParsingError) {
NSLog(@"JSON ERROR: %@", [jsonParsingError localizedDescription]);
} else {
NSLog(@"PARSED OBJECT %@", parsedObject);
}
}
I suggest use AFNetworking whenever deal with networking.
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:username
password:password];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.