Objective-C sync HTTP GET JSON with timeout
Objective-C
#import <Foundation/Foundation.h>
static id FetchJSON(NSURL *url, NSTimeInterval timeout, NSError **error) {
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:timeout];
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
__block NSData *body = nil;
__block NSError *failure = nil;
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *resp, NSError *err) {
body = data;
failure = err;
dispatch_semaphore_signal(sem);
}];
[task resume];
if (dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeout * NSEC_PER_SEC))) != 0) {
[task cancel];
if (error) *error = [NSError errorWithDomain:@"HTTPError" code:1 userInfo:@{NSLocalizedDescriptionKey: @"request timed out"}];
return nil;
}
if (failure) { if (error) *error = failure; return nil; }
return [NSJSONSerialization JSONObjectWithData:body options:0 error:error];
}