Created
June 18, 2015 08:07
-
-
Save hsavit1/95a35bd52c317e75f84d to your computer and use it in GitHub Desktop.
Fetch JSON from URL with RAC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (RACSignal *)fetchJSONFromURL:(NSURL *)url { | |
NSParameterAssert(url); | |
return [[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) { | |
NSURLSession * session = [NSURLSession sharedSession]; | |
NSURLSessionDataTask * dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) { | |
if (data) { | |
NSError * jsonError = nil; | |
id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError]; | |
if (json) { | |
[subscriber sendNext:json]; | |
} | |
else { | |
[subscriber sendError:jsonError]; | |
} | |
} | |
else { | |
[subscriber sendError:error]; | |
} | |
[subscriber sendCompleted]; | |
}]; | |
[dataTask resume]; | |
return [RACDisposable disposableWithBlock:^{ | |
[dataTask cancel]; | |
}]; | |
}] doError:^(NSError * error) { | |
NSLog(@"%@", error); | |
}]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment