API requests with SLRequest

Updated on Tue, 2013-10-08 17:00

Overview

SLRequest is a class in the Social.framework for iOS that encapsulates HTTP requests to Twitter’s REST API. This class supercedes the Twitter.framework's TWRequest from iOS5.

How do I perform requests with SLRequest ?

Executing a request to Twitter's REST API is a 3 step process:

  1. First, you create a new request using +[SLRequest requestForServiceType:requestMethod:URL:parameters:] , with the service type set to SLServiceTypeTwitter and the subsequent parameters set to the required values.
  2. Next, you assign an ACAccount instance to the request via the -[SLRequest setAccount:] method.
  3. Finally, to perform the request, you call -[SLRequest performRequestWithHandler:].

Note

Beginning with API v1.1, all requests to the REST API must be authenticated. Failure to attach an account instance to a request will result in an error.

Example: Retrieving user timelines

In this example, we will first query the accounts that the user has stored on the device, then for the first account returned we retrieve the user's home timeline using GET statuses/user_timeline, which requires authentication. We will pass four parameters to the endpoint, screen_name, count, include_rts, and trim_user.

  1. // SCSimpleSLRequestDemo.m
  2. #import <Accounts/Accounts.h>
  3. #import <Social/Social.h>
  4. #import "SCSimpleSLRequestDemo.h"
  5.  
  6. @interface SCSimpleSLRequestDemo()
  7.  
  8. @property (nonatomic) ACAccountStore *accountStore;
  9.  
  10. @end
  11.  
  12. @implementation SCSimpleSLRequestDem
  13.  
  14. - (id)init
  15. {
  16.   self = [super init];
  17.   if (self) {
  18.     _accountStore = [[ACAccountStore alloc] init];
  19.   }
  20.   return self;
  21. }
  22.  
  23. - (BOOL)userHasAccessToTwitter
  24. {
  25.   return [SLComposeViewController
  26.           isAvailableForServiceType:SLServiceTypeTwitter];
  27. }
  28.  
  29. - (void)fetchTimelineForUser:(NSString *)username
  30. {
  31.   //  Step 0: Check that the user has local Twitter accounts
  32.   if ([self userHasAccessToTwitter]) {
  33.  
  34.     //  Step 1:  Obtain access to the user's Twitter accounts
  35.     ACAccountType *twitterAccountType =
  36.       [self.accountStore accountTypeWithAccountTypeIdentifier:
  37.         ACAccountTypeIdentifierTwitter];
  38.  
  39.     [self.accountStore
  40.      requestAccessToAccountsWithType:twitterAccountType
  41.      options:NULL
  42.      completion:^(BOOL granted, NSError *error) {
  43.        if (granted) {
  44.          //  Step 2:  Create a request
  45.          NSArray *twitterAccounts =
  46.          [self.accountStore accountsWithAccountType:twitterAccountType];
  47.          NSURL *url = [NSURL URLWithString:@"https://api.twitter.com"
  48.                        @"/1.1/statuses/user_timeline.json"];
  49.          NSDictionary *params = @{@"screen_name" : username,
  50.                                   @"include_rts" : @"0",
  51.                                   @"trim_user" : @"1",
  52.                                   @"count" : @"1"};
  53.          SLRequest *request =
  54.          [SLRequest requestForServiceType:SLServiceTypeTwitter
  55.                             requestMethod:SLRequestMethodGET
  56.                                       URL:url
  57.                                parameters:params];
  58.  
  59.          //  Attach an account to the request
  60.          [request setAccount:[twitterAccounts lastObject]];
  61.  
  62.          //  Step 3:  Execute the request
  63.          [request performRequestWithHandler:
  64.           ^(NSData *responseData,
  65.             NSHTTPURLResponse *urlResponse,
  66.             NSError *error) {
  67.  
  68.            if (responseData) {
  69.              if (urlResponse.statusCode >= 200 &&
  70.                  urlResponse.statusCode < 300) {
  71.  
  72.                NSError *jsonError;
  73.                NSDictionary *timelineData =
  74.                [NSJSONSerialization
  75.                 JSONObjectWithData:responseData
  76.                 options:NSJSONReadingAllowFragments error:&jsonError];
  77.                 if (timelineData) {
  78.                  NSLog(@"Timeline Response: %@\n", timelineData);
  79.                }
  80.                else {
  81.                  // Our JSON deserialization went awry
  82.                  NSLog(@"JSON Error: %@", [jsonError localizedDescription]);
  83.                }
  84.              }
  85.              else {
  86.                // The server did not respond ... were we rate-limited?
  87.                NSLog(@"The response status code is %d",
  88.                 urlResponse.statusCode);
  89.              }
  90.            }
  91.          }];
  92.        }
  93.        else {
  94.          // Access was not granted, or an error occurred
  95.          NSLog(@"%@", [error localizedDescription]);
  96.        }
  97.      }];
  98.   }
  99. }
  100. @end