NSURLConnection always TRUE

51 views Asked by At

I am checking for server connection with the code below, however 'connection' is always TRUE..

I know that 'initWithRequest:delegate:' is deprecated: and it is recommended to use NSURLSession instead, however I'd prefer continuing using it for simplicity as NSURLSession seems much more complex to implement.

Any advice to make it work?

NSURL *url = nil;
NSMutableURLRequest *request = nil;

NSString *getURL = [NSString stringWithFormat:@"%@?TEST=%@",URL, str];

url = [NSURL URLWithString: getURL];
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[request addValue: @"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

if(connection) //Always true!!!
{
    mutableData = [NSMutableData new];
    NSLog(@"SERVER CONNECTION OK");
}
else
{
    NSLog(@"NO SERVER CONNECTION");
}
1

There are 1 answers

0
GeneCode On

connection is an NSURLConnection object that you created. If it gets created, it will return true.

Problem is you did not handle the response data which can be utilized using these delegates functions:

-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace;
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
-(void)connectionDidFinishLoading:(NSURLConnection *)connection;

You should put a log in didFailWithError to check whether your connection is successful or not.

I am quite sure you have not tried NSURLSession, but you should because NSURLSession can be written as blocks which makes it easier to write code (no delegates). In truth NSURLSession is a lot simpler and easier to implement than NSURLConnection.