Check if NSURLConnection is connected in iphone?

-(void)loadRequest:(NSString *)jsonString{ receivedData = [[NSMutableData alloc]init]; urlString = [[NSString alloc]initWithString:[NSString stringWithFormat:kURL]]; urlRequest=[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; requestInformation =[[NSMutableURLRequest alloc]initWithURL:urlRequest cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60]; [requestInformation setValue:khttpValue forHTTPHeaderField:kContentType]; [requestInformation setValue:@"value1" forHTTPHeaderField:@"key1"]; [requestInformation setHTTPMethod:kPost]; jsonData= [[NSString stringWithFormat:@"json=%@",jsonString] dataUsingEncoding:NSUTF8StringEncoding]; [requestInformation setHTTPBody:jsonData]; connection = [[NSURLConnection alloc] initWithRequest:requestInformation delegate:self]; [connection start]; if(connection){ NSLog(@"Connection succesfull"); } else{ NSLog(@"There is a error in connection"); [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(onFailedToUpload) userInfo:nil repeats:NO]; } } 

how to check if the else part is complete. I give an invalid url, the didfailwitherror method is called, but the else part is not executed.

+4
source share
1 answer

As far as I know, the connection object is always created. Even your URL is incorrect. Any errors come to the didFailWithError delegate didFailWithError . You probably need to check the error and continue it accordingly. Ex. In case this is a timeout, you can try again in the didFailWithError didFailWithError . For other types of errors, they are handled differently.

If you want to handle broken or bad URLs before submitting them to NSURLConnection , you need to do it yourself.

Here are the delegates that you, when using NSURLConnection -

 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog("@Resp received"); return; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSLog("@Data received"); return } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog("@ERROR: Achtung !: %@",[error localizedDescription]); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH , 0),, ^{ NSLog(@"FinishedLoading: In bg thread, do something with data here"); dispatch_async( dispatch_get_main_queue(), ^{ NSLog(@"FinishedLoading: In Main thread, access the UI here"); }); }); } 
+3
source

Source: https://habr.com/ru/post/1433298/


All Articles