1

So i have this method in my app that returns BOOL if and update is available for my apps content

- (BOOL)isUpdateAvailable{
    NSData *dataResponse=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"url that returns json object"] ];
    if(dataResponse!=nil){
        NSError *error;
        dicUpdates = [NSJSONSerialization JSONObjectWithData:dataResponse options:NSJSONReadingMutableContainers error:&error];
    }
    if(dicUpdates.count > 0) isUpdateAvailable = YES;
    else isUpdateAvailable = NO;
    return isUpdateAvailable;
}

I need a synchronous request for this, cause the next view controller will be dependent on the server response. However sometimes it takes a long time for the server to respond or the internet is really slow, i need to set a time out to prevent the app from 'being frozen'.

I previously used NSUrlconnection to accomplish this task, but it has been deprecated.

Also, I tried using NSURLSession, (been using it also to download updates in the background thread), but i just can figure out if it can be used for a synchronous request.

Any idea how to deal with this? i just need a synchronous method that returns a BOOL. Best regards.

ram obrero
  • 197
  • 10

1 Answers1

-1

We have to use NSURLRequest in NSURLSession to set timeout interval. Check below code:

- (BOOL)isUpdateAvailable{  
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"url that returns json object"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:4]//timeout
        completionHandler:^(NSData *dataResponse,
                            NSURLResponse *response,
                            NSError *error) {
            // handle response
            if(dataResponse!=nil){
                NSError *error;
                dicUpdates = [NSJSONSerialization JSONObjectWithData:dataResponse options:NSJSONReadingMutableContainers error:&error];
            }
            if(dicUpdates.count > 0) isUpdateAvailable = YES;
            else isUpdateAvailable = NO;
            return isUpdateAvailable;


        }] resume];
}
SIRAJ V K
  • 45
  • 5
  • I'm having error since return `return isUpdateAvailable;` is inside the completion handler, ive moved it outside the session task. Ill try the code right away, thanks! – ram obrero Sep 30 '15 at 04:52
  • this doesnt work, since the method returns the isUpdateAvailable var, without even waiting for the requestwithURL method, – ram obrero Sep 30 '15 at 06:15