1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Get JSON from URL in Objective-C

Last updated at Posted at 2015-05-25

- Synchronous

NSURL *url = [NSURL URLWithString:kJsonURL];
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                      timeoutInterval:10.0];
NSError *error = nil;
NSURLResponse *res = nil;
NSData *json = [NSURLConnection sendSynchronousRequest:req returningResponse:&res error:&error];
NSInteger statusCode = ((NSHTTPURLResponse *) res).statusCode;
// if success
if (json && statusCode == 200) {
    NSArray* data = [[NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingAllowFragments error:nil] objectForKey:@"data"];

// if failure
} else {
    
}

 

  • Asynchronous
NSURL *url = [NSURL URLWithString:kJsonURL];
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                      timeoutInterval:10.0];
[NSURLConnection sendAsynchronousRequest:req queue:[[NSOperationQueue alloc] init]
        completionHandler:^(NSURLResponse *res, NSData *json, NSError *error) {
            NSInteger statusCode = ((NSHTTPURLResponse *) res).statusCode;
            // if success
            if (json && statusCode == 200) {
                NSArray* data = [[NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingAllowFragments error:nil] objectForKey:@"data"];

            // if failure
            } else {
                
            }
        }];
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?