NSURLSession fails when we try to assign an IP instead of localhost or home

I have a server working locally (my IP address is 192.168.0.98) and experimented with some network code to access it. This was originally done through AFNetworking, but I did it using NSURLSession as follows:

 NSURLSession *session = [NSURLSession sharedSession]; NSURL *url = [NSURL URLWithString:@"http://192.168.0.98:8080/api"]; NSURLSessionDataTask *task = [session dataTaskWithURL: url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSLog(@"Error: %@", error); NSLog(@"Body: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); }]; [task resume]; 

Then I run it with these three URLs:

  • http://localhost:8080/api β†’ works.
  • http://127.0.0.1:8080/api β†’ works.
  • http://192.168.0.98:8080/api β†’ with an error:

     Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory" UserInfo={ NSErrorFailingURLStringKey=http://192.168.0.98:8080/api, NSErrorFailingURLKey=http://192.168.0.98:8080api, _kCFStreamErrorCodeKey=2, _kCFStreamErrorDomainKey=1 } 

Where 192.168.0.98 is the IP assigned to this machine. If I run these URLs from PAW or browser, it works fine. But from unit test, it fails.

From my project perspective, I can just use localhost . So this is not an interruption of the transaction. But I'm curious why it doesn't work.

Does anyone know what the problem is?

+6
source share
1 answer

tl; dr: use your Bonjour local domain name instead of your IP address.

I myself ran into this problem. I create the API locally and do not want to deploy it to an external server, but I need to call the API both from the simulator and from the devices. At first I tried using localhost, but of course this does not work for devices, since localhost will be the device itself, not my Mac. The IP address worked on devices, but did not work in the simulator. Then I remembered that I can use the .local domain name for my Mac for a different network addressing, and it certainly works. I can use http://mymac.local/ as the base URL for my API requests on both the simulator and my test devices.

I'm not sure why using the actual IP address does not work, but it may give you an opportunity that will work for your needs.

+5
source

All Articles