iOS engineer who likes clean, simple designs and sans-serif.


Underneath AFNetworking – How to Work With API’s From Scratch

Here’s a cheatsheet of how to make an API request in iOS7+:

  1. Obviously, you need to pick an API, sign up for a developer account and add your application.
  2. Look over the docs and gain an understanding of what is available in the API and what it wants you to provide. Play around with the data by doing sample requests using the API tools, a web browser or tools like Postman REST client.


  3. After you understand what you need to provide, construct an NSURL using constants and NSString (of course).
     NSString *apiSlug = @"search";
     NSString *urlPath = [NSString stringWithFormat:@"%@/%@?%@&key=%@intitle=%@",STACKOVERFLOW_BASE_URL,apiSlug,STACKOVERFLOW_STANDARD_PARAMS,STACKOVERFLOW_KEY,searchString];
     NSURL *url = [NSURL URLWithString:urlPath];
  4. Construct an NSURLSessionDataTask using NSURLSession and NSURLRequest. For non-GET requests, don’t forget to use NSMutableURLRequest with HTTPMethod, HTTPBody and NSUTF8StringEncoding.
     NSURL *getAccessTokenURL = [NSURL URLWithString:@""];
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:getAccessTokenURL];
     request.HTTPMethod = @"POST";

     NSString *params = [NSString stringWithFormat:@"client_id=%@&client_secret=%@&code=%@",YOUR_CLIENT_ID,YOUR_CLIENT_SECRET,YOUR_CODE];
     request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding];

     NSURLSession *session = [NSURLSession sharedSession];

     NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  5. Inside the completion block, capture and handle the response data using NSJSONSerialization, NSArray, NSDictionary, NSString, regex, etc. to get the data you want. Access and store the data by choosing your poison: models, Core Data, NSUserDefaults, singleton datastore, property, etc. Here’s an example using NSDictionary and NSJSONSerialization:
     NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
     NSArray *questionDictionaries = responseDictionary[@"items"];
     NSMutableArray *questionsArray = [[NSMutableArray alloc]init];

     for (NSDictionary *question in questionDictionaries) {
       FISQuestion *newQuestion = [FISQuestion questionWithAnswerCount:question[@"answer_count"]
        [questionsArray addObject:newQuestion];

    Example with regex and NSString:

     NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
     NSString *pattern = @"\\Aaccess_token=(.+)&scope";
     NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
     NSArray *matches = [regex matchesInString:responseString options:0 range:NSMakeRange(0, [responseString length])];
     NSTextCheckingResult *match = matches[0];

     NSString *access_token = [responseString substringWithRange:[match rangeAtIndex:1]];

     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
     [defaults setObject:access_token forKey:@"githubAccessToken"];
     [defaults synchronize];
  6. Last, but not least, don’t forget to “resume” your NSURLSessionDataTask!
     [task resume];

Leave a Comment