Monday, 28 April 2014

Retrieving user timelines of Twitter account with SLRequest (API requests with SLRequest) (API Version 1.1)

Overview

SLRequest is a class in the Social.framework for iOS that encapsulates HTTP requests to Twitter’s REST API. This class supersedes 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.




//.h file

#import <UIKit/UIKit.h>

#import <Accounts/Accounts.h>
#import <Social/Social.h>
//#import "SCSimpleSLRequestDemo.h"

@interface HomeViewController : UIViewController
{
    
}


@property (nonatomic) ACAccountStore *accountStore;

@end








//.m file

#import "HomeViewController.h"

@interface HomeViewController ()

@end

@implementation HomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    _accountStore = [[ACAccountStore alloc] init];
    
    
    
    [self fetchTimelineForUser:@"UserName"];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




- (BOOL)userHasAccessToTwitter
{
    return [SLComposeViewController
            isAvailableForServiceType:SLServiceTypeTwitter];
}

- (void)fetchTimelineForUser:(NSString *)username
{
    //  Step 0: Check that the user has local Twitter accounts
    if ([self userHasAccessToTwitter])
    {
        
        //  Step 1:  Obtain access to the user's Twitter accounts
        ACAccountType *twitterAccountType =
        [self.accountStore accountTypeWithAccountTypeIdentifier:
         ACAccountTypeIdentifierTwitter];
        
        [self.accountStore
         requestAccessToAccountsWithType:twitterAccountType
         options:NULL
         completion:^(BOOL granted, NSError *error) {
             if (granted) {
                 //  Step 2:  Create a request
                 NSArray *twitterAccounts =
                 [self.accountStore accountsWithAccountType:twitterAccountType];
                 NSURL *url = [NSURL URLWithString:@"https://api.twitter.com"
                               @"/1.1/statuses/user_timeline.json"];
                 NSDictionary *params = @{@"screen_name" : username,
                                          @"include_rts" : @"0",
                                          @"trim_user" : @"1",
                                          @"count" : @"5"};
                 SLRequest *request =
                 [SLRequest requestForServiceType:SLServiceTypeTwitter
                                    requestMethod:SLRequestMethodGET
                                              URL:url
                                       parameters:params];
                 
                 //  Attach an account to the request
                 [request setAccount:[twitterAccounts lastObject]];
                 
                 //  Step 3:  Execute the request
                 [request performRequestWithHandler:
                  ^(NSData *responseData,
                    NSHTTPURLResponse *urlResponse,
                    NSError *error) {
                      
                      if (responseData) {
                          if (urlResponse.statusCode >= 200 &&
                              urlResponse.statusCode < 300) {
                              
                              NSError *jsonError;
                              NSDictionary *timelineData =
                              [NSJSONSerialization
                               JSONObjectWithData:responseData
                               options:NSJSONReadingAllowFragments error:&jsonError];
                              if (timelineData) {
                                  NSLog(@"Timeline Response: %@\n", timelineData);
                              }
                              else {
                                  // Our JSON deserialization went awry
                                  NSLog(@"JSON Error: %@", [jsonError localizedDescription]);
                              }
                          }
                          else {
                              // The server did not respond ... were we rate-limited?
                              NSLog(@"The response status code is %d",
                                    urlResponse.statusCode);
                          }
                      }
                  }];
             }
             else {
                 // Access was not granted, or an error occurred
                 NSLog(@"%@", [error localizedDescription]);
             }
         }];
    }
}


@end




Recommended Reading
The following articles on Apple's Developer Site will help you as you work with SLRequest :






No comments:

Post a Comment