LoginSignup
107
105

More than 5 years have passed since last update.

3周遅れぐらいでiOSのSocial.frameworkを使ってみる

Last updated at Posted at 2013-06-15

twitterへの投稿

Social.frameworkSLComposeViewControllerがお手軽でした。投稿クライアントはiOSとなります。

-(void)viewDidAppear:(BOOL)animated
{
    // エミュレータでも問題なく動く
    // postのクライアント表示はiOSになる。
    SLComposeViewController *twitterPostVC = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
    [twitterPostVC setInitialText:@"iOSのSocialFrameworkから投稿テスト。\nSLComposeViewController簡単。"];
    [self presentViewController:twitterPostVC animated:YES completion:nil];
}

スクリーンショット_2013_06_15_17_54.png

スクリーンショット_2013_06_15_17_55.png

Timelineの取得

OAuthのややこしいところをSLRequestが吸収してくれています。逆に戻り値はNSDataなので、それは自力でパースする必要があります(といってもNSJSONSerializationがよろしくやってくれる)。

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.accountStore = [[ACAccountStore alloc]init];
}

// ほぼコピペ
// https://dev.twitter.com/docs/ios/making-api-requests-slrequest
-(void)viewWillAppear:(BOOL)animated
{
    //  Step 0: Check that the user has local Twitter accounts
    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) {

        //  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" : @"paming",
                                          @"include_rts" : @"0",
                                          @"trim_user" : @"1",
                                          @"count" : @"10"};
                 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;
                             // サンプルではDictionaryだけど、Arrayが戻ってきてる
                             // JSONがArrayだし。
                             NSArray *timelineData =
                             [NSJSONSerialization
                              JSONObjectWithData:responseData
                              options:NSJSONReadingAllowFragments error:&jsonError];
                             NSLog(@"class=%@",[timelineData class]);
                             if (timelineData) {
//                                 NSLog(@"Timeline Response: %@\n", timelineData);
                                 for (NSDictionary *dic in timelineData) {
                                     NSLog(@"%@",[dic objectForKey:@"text"]);
                                 }
                             }
                             else {
                                 // Our JSON deserialization went awry
                                 NSLog(@"JSON Error: %@", [jsonError localizedDescription]);
                             }
                         }
                         else {
                             // The server did not respond successfully... 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]);
             }
         }];
    }
}

UserStreamを取得

SLRequestを使い、UserStreamも読み取れました。SLRequestからNSURLRequestを取得し、NSURLConnection(とNSURLConnectionDataDelegate)を使いデータを読み込み続けます。

-(void)viewDidAppear:(BOOL)animated
{

    NSURL *url = [NSURL URLWithString:@"https://userstream.twitter.com/1.1/user.json"];
    NSDictionary *params = nil;
    SLRequest *request =
    [SLRequest requestForServiceType:SLServiceTypeTwitter
                       requestMethod:SLRequestMethodGET
                                 URL:url
                          parameters:params];
    ACAccountType *twitterAccountType = [self.accountStore
                                         accountTypeWithAccountTypeIdentifier:
                                         ACAccountTypeIdentifierTwitter];
    NSArray *twitterAccounts =
    [self.accountStore accountsWithAccountType:twitterAccountType];
    ACAccount *account = [twitterAccounts lastObject];
    [request setAccount:account];

    self.connection = [NSURLConnection connectionWithRequest:request.preparedURLRequest delegate:self];

    [self.connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.connection start];


}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"%@",response);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSError *jsonError;
    id jsonObj =
    [NSJSONSerialization JSONObjectWithData:data
                                    options:NSJSONReadingAllowFragments
                                      error:&jsonError];
    NSLog(@"%@",jsonObj);
}

関連リンク

107
105
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
107
105