Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AlamofireSoftwareFoundation/bb16a491b2709a8476e2 to your computer and use it in GitHub Desktop.
Save AlamofireSoftwareFoundation/bb16a491b2709a8476e2 to your computer and use it in GitHub Desktop.
// AFNetworking
[[AFHTTPSessionManager manager] GET:@"http://httpbin.org/ip" parameters:nil success:^(NSURLSessionDataTask *task, id JSON) {
NSLog(@"IP Address: %@", JSON[@"origin"]);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"Error: %@", error);
}];
// NSURLSession
NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/ip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
} else if (data && [data length] > 0) {
NSError *JSONError = nil;
id JSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&JSONError];
if (JSONError) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"IP Address: %@", JSON[@"origin"]);
}
}
}];
// NSURLSession + HTTP Validation + Background JSON Processing
NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/ip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
} else if (data && [data length] > 0) {
if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) {
if ([(NSHTTPURLResponse *)response statusCode] != 200) {
return;
}
NSString *contentType = [(NSHTTPURLResponse *)response allHeaderFields][@"Content-Type"];
if (contentType && ![contentType hasSuffix:@"/json"]) {
return;
}
}
NSError *JSONError = nil;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
id JSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&JSONError];
if (JSONError) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"IP Address: %@", JSON[@"origin"]);
}
});
}
}];
@mfaani
Copy link

mfaani commented Jun 9, 2016

In the sample code is, the AFNetworking also dealing with HTTP Validation + Background JSON Processing as well? Or is it that the sample code doesn't cover that part?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment