0

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");
}
jeddi
  • 651
  • 1
  • 12
  • 21
  • 5
    No wonder it is true - that means the object was created and initialized successfully. I guess now you should start using it with proper calls. – BorisV May 26 '19 at 14:56
  • Why are you surprised to see `connection` is allocated? Isn't that what you wanted? This question title is confusing. – adev May 27 '19 at 00:50

1 Answers1

1

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.

GeneCode
  • 7,545
  • 8
  • 50
  • 85