0

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

Midhun MP
  • 103,496
  • 31
  • 153
  • 200

1 Answers1

0

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.

Wain
  • 118,658
  • 15
  • 128
  • 151
  • ok. Is there any way to make a synchronous request with handling auth challenges? – user3708025 Apr 01 '15 at 19:52
  • Only if you can specify the auth in the URL or headers. You can't have synchronous with a delegate... – Wain Apr 01 '15 at 19:56
  • 1
    http://stackoverflow.com/q/4613067/3411191 explains your question quite well @user3708025 – Zane Helton Apr 01 '15 at 19:59
  • And do you know if it's possible with an third party framework / library for example AFNetworking? – user3708025 Apr 01 '15 at 20:00
  • To do synchronously - no. AFN is built on top of `NSURLConnection` (or `NSURLSession`) so it has similar limitations – Wain Apr 01 '15 at 20:01
  • Do not use synchronous network calls. They are bad news. Learn to use delegates or the block-based completion method in NSURLConnection. – Duncan C Apr 01 '15 at 21:06