iosobjective-cnsurlconnectionnsurlconnectiondelegate

objective-c wait until NSURLConnection connection did finish loading


I have a method which starts an NSURLConnetion to read an IP-Address an return the IP after the connection did finish loading:

- (NSString *)getHansIP
{
   self.returnData = [[NSMutableData alloc] init];
   NSMutableURLRequest *getIpRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://example.com"]];
   [getIpRequest setHTTPMethod:@"GET"];
   NSURLConnection *ipconn = [NSURLConnection connectionWithRequest:getIpRequest delegate:self];
   [ipconn start];
   return self.ipString;
}

The problem is that objective-c tries to return the IP-Address (ipString) when the connection did not finished loading yet. I know there is a simple way to fix it but with this way the NSURLConnectionDelegate methods do not getting executed and I need thedidReceiveAuthenticationChallenge Method an the canAuthenticateAgainstProtectionSpace method. P.S. hope you understand my bad school english :P


Solution

  • You can't return the IP direct from the method, not without blocking the thread anyway, and you can't really do that and handle auth issues.

    You need to create an object to manage this which is the delegate for the connection, maintains the connection as an instance variable while it's processing and has a delegate or a completion callback block to pass the IP back with once it's done.

    You need to embrace the fact that the connection is asynchronous and not want to return the IP from the method directly.