I'm trying to connect my application to the backend using NSURLConnection.
When I use postman everything works really fine and I get the expected result.
But when I try that in my code I get a totally different result, which is a JSON object from the server but with an error message.
Please check the following pictures and the code I use for more details.
Any idea will be really appreciated .
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *urlStr=[NSString stringWithFormat:#"URL"];
NSURL* _url=[NSURL URLWithString:urlStr];
[request setURL:_url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"Bearer ---" forHTTPHeaderField:#"Authorization"];
NSArray *keys= [[NSArray alloc] initWithObjects:#"email",#"firebase_token",#"password",#"username",#"phone",#"uploaded_file", nil];
NSArray *values = [[NSArray alloc] initWithObjects:email,#"token",password,userName,phone,#"#/C:/Users/admin/Downloads/chili house.png", nil];
NSDictionary *params = [[NSDictionary alloc] initWithObjects:values forKeys:keys];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:NSJSONWritingPrettyPrinted
error:&error];
[request setHTTPBody:jsonData];
NSString *jsonString;
if ( jsonData) {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
[request setHTTPBody:jsonData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
if ([challenge previousFailureCount] == 0) {
NSURLCredential *newCredential;
newCredential = [NSURLCredential credentialWithUser:#"User"
password:#"Password"
persistence:NSURLCredentialPersistenceNone];
[[challenge sender] useCredential:newCredential
forAuthenticationChallenge:challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data{
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Connection failed: %#", [error description]);
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return YES;
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.responseData setLength:0];
}
- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[[BusyAgent defaultAgent] makeBusy:NO];
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
if (responseString == (id)[NSNull null] || responseString.length == 0 ){
NSLog(#"responseString= %#",responseString);
}else{
NSLog(#"responseString = %#",responseString);
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:responseString delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alert show];
}
self.responseData = nil;
}
Related
Hi I am facing problem in conversion of NSData to NSDictionary using NSJSONSerialization?
I got data using my code but unable to convert it into json.
Here is my code...
ViewController.h File
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<NSURLConnectionDelegate>
{
NSString *massage;
NSURL *url;
NSMutableURLRequest *request;
NSURLConnection *connection;
NSMutableData *httpbody;
NSMutableData *webData;
NSData *responceData;
NSDictionary *responceJson;
}
and ViewController.m File
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *mobile = #"123456789";
NSString *password = #"Welcome123";
NSString *deviceId = #"123sdfg15641ert321ret";
url = [NSURL URLWithString:#"http://203.109.87.34:8585/d-cab/web/app_dev.php/api/v1"];
massage = [NSString stringWithFormat:#"{\"action\":\"login\",\"data\":{\"contact\":\"%#\",\"password\":\"%#\",\"deviceId\":\"%#\"}}",mobile,password,deviceId];
//NSLog(#"Body = %#", massage);
httpbody = [ NSMutableData dataWithBytes: [ massage UTF8String ] length: [ massage length ] ];
request = [NSMutableURLRequest requestWithURL: url];
[request setHTTPMethod: #"POST"];
[request setHTTPBody: httpbody];
[request setTimeoutInterval:10.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
//[connection start];
if (connection) {
webData = [[NSMutableData alloc]init];
}
}
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[webData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
//NSLog(#"WebData = %#",webData);
//NSLog(#"=================================");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError* error = nil;
responceJson = [NSJSONSerialization JSONObjectWithData:webData options:kNilOptions error:&error];
NSLog(#"ResponceJSON = %#",responceJson);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// Show error message
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error In connection" message:#"We are facing some problem in connection. Please Check your Internet Connection." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Please Check my code and tell me where and what change I have to make?
Hey Thanks to all who gave attention to my question.... But I found the problem in my question.
I am trying to send the parameter into string format instead of dictionary format and not specifying header to request. Here is my updated code...
NSDictionary *paramData = [[NSDictionary alloc]initWithObjectsAndKeys:mobile,#"contact",password,#"password",deviceId,#"deviceId", nil];
//NSLog(#"paramData = %#",paramData);
jsonParam = [[NSDictionary alloc]initWithObjectsAndKeys:#"login",#"action",paramData,#"data", nil];
//NSLog(#"jsonParam = %#",jsonParam);
httpbody = [NSJSONSerialization dataWithJSONObject:jsonParam options:0 error:nil];
request = [NSMutableURLRequest requestWithURL: url];
request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [httpbody length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: httpbody];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
webData = [[NSMutableData alloc]init];
}
It worked for me....
Try using the following code :
responceJson = [NSJSONSerialization JSONObjectWithData:webData
options:NSJSONReadingMutableContainers
error:&error];
Well the problem here is not in conversion problem is in this funtion
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
//[webData setLength:0];
webdData = [[NSMutableData alloc] init];
}
It will help.Thanks
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if( theConnection )
{
mdata = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
mdata.length=0;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mdata appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Data store in dictionary when connection proceed in background
dict=[NSJSONSerialization JSONObjectWithData:mdata options:kNilOptions error:nil];
NSLog(#"%#",dict);
}
This is working gooood...
Try to check, what your connection is load. Converting NSData to NSString. In didFinishLoading typing this:
NSString *tempString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSLog(#"loaded data: %#",tempString);
I uses nsurlconnection delegates to post request I just created one class to test my login post request one I login it gives me correct profile and again I run and login with another credentials it is giving me previous profile I done understand what is the problem I am posting to ROR server
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError * error;
jsonDictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:0 error:&error];
NSLog(#"%#",jsonDictionary);
theConnection = nil;
receivedData = nil;
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
theConnection = nil;
receivedData = nil;
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (IBAction)sigininAction:(id)sender {
if (theConnection) {
[theConnection cancel];
receivedData.data = nil;
jsonDictionary = nil;
theConnection = nil;
}
NSString *bodyData = [NSString stringWithFormat:#"user[email]=%#&user[password]=%#",[_email text],[_password text]];
NSData *postData = [bodyData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://URL/login"]];
[postRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[postRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[postRequest setHTTPMethod:#"POST"];
[postRequest setHTTPBody:postData];
theConnection=[[NSURLConnection alloc] initWithRequest:postRequest delegate:self];
if (theConnection) {
[theConnection start];
receivedData = [[NSMutableData alloc]init];
}
}
I am sending a request to server using NSURLConnection, it worked for 2 times , since third time it is not working, delegates are not being called. What i found during debugging is connectionShouldUseCredentialStorage method is called for initial times, third time it was not called and rest of methods are also not called.
Here is my code:
NSString *requestString = [NSString stringWithFormat:#"%#", [serviceParameters JSONFragment], nil];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: strUrl]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setHTTPBody:requestData];
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.data = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)aData
{
[self.data appendData:aData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
SBJSON *jsonParser = [[SBJSON new] autorelease];
NSString *jsonString = [[[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding] autorelease];
NSError *outError = nil;
id result = [jsonParser objectWithString:jsonString error:&outError];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
if( [[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust] )
{
return YES;
}
return NO;
}
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
{
return YES;
}
in .h
NSMutableData * data;
NSURLConnection *connection;
Also add Add
in .m
-(void) startConnection
{
NSString *requestString = [NSString stringWithFormat:#"http://md5.jsontest.com/?text=Pushkraj"];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
data = [NSMutableData dataWithCapacity:0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setHTTPBody:requestData];
connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)aData
{
[data appendData:aData];
NSDictionary * dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSLog(#"dataDict : %#",dataDict);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"connectionDidFinishLoading");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Error : %#",error);
}
Call [self startConnection]; wherever you want means on viewDidLoad or on UIButton Click
You forgot to start connection. You are not saving the reference to NSURLConnection for starting the connection. So replace last line
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
with this
NSURLConnection *cn =[NSURLConnection connectionWithRequest:urlRequest delegate:self];
[cn start];
Hope it helps.
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 (e.g.: [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];
I am using JSON to get data from web service.The problem is When i call web service and due to slow response my app become unresponsive for few seconds and some times crash.
I search a lot and found that by making Asynchronous call instead of Synchronous call can solve problem. But how to use asynchronous call that i don't know.
My code is like..
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [[NSMutableData data] retain];
NSString *service = #"/Get_NearbyLocation_list";
double d1=[[[NSUserDefaults standardUserDefaults]valueForKey:#"LATITUDE"] doubleValue];
NSLog(#"%f",d1);
double d2=[[[NSUserDefaults standardUserDefaults]valueForKey:#"LONGITUDE"] doubleValue];
NSLog(#"%f",d2);
NSString *requestString = [NSString stringWithFormat:#"{\"current_Lat\":\"%f\",\"current_Long\":\"%f\"}",d1,d2];
NSLog(#"request string:%#",requestString);
// NSString *requestString = [NSString stringWithFormat:#"{\"GetAllEventsDetails\":\"%#\"}",service];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *fileLoc = [[NSBundle mainBundle] pathForResource:#"URLName" ofType:#"plist"];
NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
NSString *urlLoc = [fileContents objectForKey:#"URL"];
urlLoc = [urlLoc stringByAppendingString:service];
NSLog(#"URL : %#",urlLoc);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
// self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
NSError *respError = nil;
NSData *returnData= [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
if (respError)
{
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"Internet connection is not Available!" message:#"Check your network connectivity" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alt performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:YES];
[alt release];
[customSpinner hide:YES];
[customSpinner show:NO];
}
else
{
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#" %#",responseString);
NSDictionary *results = [[responseString JSONValue] retain];
NSLog(#" %#",results);
thanks in advance..
NSData *returnData= [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
this line makes the call a synchronous one.
Use this
-(void)downloadWithNsurlconnection
{
//MAke your request here and to call it async use the code below
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[receivedData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse: (NSCachedURLResponse *)cachedResponse {
return nil;
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Succeeded! Received %d bytes of data",[receivedData length]);
//Here in recieved data is the output data call the parsing from here and go on
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
this is how u can send asynchronous url request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil)
//date received
else if ([data length] == 0 && error == nil)
//date empty
else if (error != nil && error.code == ERROR_CODE_TIMEOUT)
//request timeout
else if (error != nil)
//error
}];