Search code examples
iosobjective-cwifiafnetworking

AFNetworking can sometimes not connect using some WiFi networks


We have an iOS app which makes a number of API calls to a remote server. We first check whether we have an internet connection, and then make all the API calls. We are using the AFNetworking 1.0 library for this.

NSMutableURLRequest *request = [[self.class sharedNetworkHelper].httpClient
                                requestWithMethod:HTTP_VERB_POST
                                path:path
                                parameters:parameters
                                parameterEncoding:AFJSONParameterEncoding];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, NSHTTPURLResponse *responseObject) {
    // Success response here
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // Failure response here
}];
[operation start];

Sometimes, a connection cannot be made with the server. It will try for ~30 seconds, and then fails. We have noticed that on some WiFi networks, this never happens, but on other WiFi networks, this happens ~10% of the time. When you try it again, it often works.

My questions are:

  1. Are there specific wireless network settings that could improve this unreliable connection?
  2. Is it a good idea to try a few times in the app to see if one of the requests will be successful?
  3. Can we change the timeout value in the app, such that the app doesn't wait until the request is processed after let's say 5 seconds?

Solution

  • The last one is pretty straightforward. Use:

    [request setTimeoutInterval:5];
    

    the second question depends on what are you doing with the request in your app. Sometimes it may be appropriate to try and call api 2 or 3 times before going to the error path of your code.