Skip to content

Instantly share code, notes, and snippets.

@hsavit1
Created June 18, 2015 08:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hsavit1/95a35bd52c317e75f84d to your computer and use it in GitHub Desktop.
Save hsavit1/95a35bd52c317e75f84d to your computer and use it in GitHub Desktop.
Fetch JSON from URL with RAC
- (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