Invalid Server Errors with NSURLSession

I have been using NSURLSession

in my application since I quit iOS 7. Recently, some users started to complain that some functions were not working, after a deep examination of their logs, I noticed that several network requests failed with the following error:

{NSLocalizedDescription = Server unavailable. Please check your network connection and try again. NSUnderlyingError = 0x174c4c300 "The operation could not be performed. (NSURLErrorDomain error -1001.)"}

As I have no idea what the problem is, I added code to resolve the hostname on unsuccessful attempts:

NSString *urlString = [url host];
const char *hostUrl = [urlString UTF8String];
struct hostent *remote_entity = gethostbyname(host);
if (!remote_entity) {
    DDLogWarn(@"DNS Lookup failed! Cant resolve Hostname: %@ for request: %@", [url host], [url description]);
    return nil;
}
else {
    // Get address info from host entry
    struct in_addr *remote_in_addr = (struct in_addr *) remote_entity->h_addr_list[0];
    char *sremote_in_addr = inet_ntoa(*remote_in_addr);
    NSString* hostIP = [NSString stringWithUTF8String:sremote_in_addr];
    DDLogWarn(@"Hostname: %@ IP: %@ (original request: %@)", [url host], hostIP, [url description]);
    return hostIP;
}

      

After deploying this change, I can see in my logs that even when the request fails (with NSURLErrorDomain error -1001), I can still resolve the hostname.

I don't understand how this can happen, I can always resolve the hostname, but the requests still don't work. Please note that I cannot reproduce this and this error only shows up from time to time, without a predictable pattern.

Any ideas on how to fix this permanently? Should I implement a packet tracking mechanism in my applications (similar to traceroute in unix)? Could this be a misconfiguration on my servers since requests to other hosts (like Amazon S3) never get interrupted? By the way, I am using Heroku.

Thanks in advance, Ze

+3


source to share


1 answer


I recommend taking a look at Apple's Networking Review , specifically Handling Network Problems gracefully .

When working with network code, you must consider the fact that sometimes things go wrong. This is especially true for mobile devices, where cellular connections can come and go. In the aforementioned section on dealing with network issues, Apple offers guidelines for automatically re-requesting and detecting network changes using the API SCNetworkReachability

. I recommend using this strategy in networking code to give your users a better experience.



In your particular case, an error -1001 appears indicating a network timeout . The host search succeeds, but for some reason the network request did not reach the server. In this case, repetition will make sense.

0


source







All Articles