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

twitterへの投稿
----
[Social.framework](http://developer.apple.com/library/ios/#documentation/Social/Reference/Social_Framework/_index.html%23//apple_ref/doc/uid/TP40012233)の[SLComposeViewController](http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Reference/SLComposeViewController_Class/Reference/Reference.html%23//apple_ref/doc/uid/TP40012205)がお手軽でした。投稿クライアントはiOSとなります。

```objc:
-(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](https://qiita-image-store.s3.amazonaws.com/0/7946/25dcf02c-ead1-5767-05a6-5ab351e6faef.png "スクリーンショット_2013_06_15_17_54.png")

![スクリーンショット_2013_06_15_17_55.png](https://qiita-image-store.s3.amazonaws.com/0/7946/8ba3790c-ee8c-20f9-e65f-f264537c5c79.png "スクリーンショット_2013_06_15_17_55.png")


Timelineの取得
-----
OAuthのややこしいところを[SLRequest](http://developer.apple.com/library/ios/#documentation/Social/Reference/SLRequest_Class/Reference/Reference.html%23//apple_ref/doc/uid/TP40012234)が吸収してくれています。逆に戻り値はNSDataなので、それは自力でパースする必要があります（といっても[NSJSONSerialization](http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html)がよろしくやってくれる)。

```objc:
- (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](http://developer.apple.com/library/ios/#documentation/Social/Reference/SLRequest_Class/Reference/Reference.html%23//apple_ref/doc/uid/TP40012234)を使い、UserStreamも読み取れました。SLRequestからNSURLRequestを取得し、NSURLConnection(とNSURLConnectionDataDelegate)を使いデータを読み込み続けます。

```objc:
-(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);
}

```

関連リンク
----
* [Social Framework](http://developer.apple.com/library/ios/#documentation/Social/Reference/Social_Framework/_index.html%23//apple_ref/doc/uid/TP40012233)
 * [SLComposeViewController](http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Reference/SLComposeViewController_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40012205) 投稿用の画面
 * [SLRequest](http://developer.apple.com/library/ios/#documentation/Social/Reference/SLRequest_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40012234) SNSへのリクエスト部分。認証周りを主に処理。実際の通信や応答のパースはしない

* [Accounts Framework](http://developer.apple.com/library/ios/#documentation/Accounts/Reference/AccountsFrameworkRef/_index.html%23//apple_ref/doc/uid/TP40011024)
 * OSに組み込まれてるアカウントへのアクセス

* Foundation
  * [NSURLRequest](http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/Reference/Reference.html#//apple_ref/doc/c_ref/NSURLRequest)
  * [NSURLConnection](http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html#//apple_ref/occ/cl/NSURLConnection)
  * [NSURLConnectionDelegate](http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSURLConnectionDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intf/NSURLConnectionDelegate)
  * [NSURLConnectionDataDelegate](https://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSURLConnectionDataDelegate_protocol/Reference/Reference.html) http://d.hatena.ne.jp/watanata2000/20111123/1322013738

* twitter
 * https://dev.twitter.com/docs/ios ←iOSのFrameworkを使った解説 
 * https://dev.twitter.com/docs/ios/migrating-tokens-core-accounts
 * https://dev.twitter.com/docs/ios/making-api-requests-slrequest
* UserStream関連 
 * https://dev.twitter.com/docs/streaming-apis/streams/user 
 * https://dev.twitter.com/docs/api/1.1/get/user


* 一連を通したスライド
 * http://www.slideshare.net/i2key/iostwitterframework