まいまいワークス

主にiPhoneアプリの開発で考えた事、調べた事、感じた事などを記していきます。

Twitter/Facebookのアカウントで認証して、アプリからタイムライン/フィードに投稿する[#6]〜Twitterのタイムライン投稿〜

メッセージのみを投稿

//以下の項目をインポートしておく
#import <Parse/Parse.h>
#import <FacebookSDK/FacebookSDK.h>
#import <AFNetworking/AFNetworking.h>



//twitter 文章のみ投稿
-(void)tweet:(NSString *)message {
    
    //URLとパラメータを生成
    NSString* url = @"https://api.twitter.com/1.1/statuses/update.json";
    NSMutableDictionary* param = @{@"status":message}.mutableCopy;

    //リクエストにメソッド(POST)、URL、パラメータを設定
    NSMutableURLRequest *tweetRequest = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST"
                                                                           URLString:url
                                                                          parameters:param
                                                                               error:nil];

    //認証
    [[PFTwitterUtils twitter] signRequest:tweetRequest];
    
    //operationの定義
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:tweetRequest];
    
    //実行
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
        
        NSLog(@"success!");
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        
        NSLog(@"fail!");
        NSLog(@"operation=%@",operation);
        NSLog(@"error=%@",error);

    }];
    
    [[NSOperationQueue mainQueue] addOperation:operation];
}

メッセージのみの投稿はこんな感じです。
簡単ですね。

画像とメッセージを投稿

//以下の項目をインポートしておく
#import <Parse/Parse.h>
#import <FacebookSDK/FacebookSDK.h>
#import <AFNetworking/AFNetworking.h>



//twitter 画像添付バージョン
-(void)tweetWithImage:(NSString *)message image:(UIImage *)image{
    
    //受け取ったUIImageをNSData形式に変換
    NSData* data = UIImageJPEGRepresentation(image, 1.0);
    
    // AFHTTPRequestOperationManagerの定義
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //URLとパラメータを生成
    NSString* url = @"https://api.twitter.com/1.1/statuses/update_with_media.json";
    NSMutableDictionary* param = @{@"status":message}.mutableCopy;
    
    //リクエストにメソッド(POST)、URL、パラメータ、添付画像を設定
    NSMutableURLRequest *tweetRequest = [manager.requestSerializer multipartFormRequestWithMethod:@"POST"
                                                                                      URLString:url
                                                                                     parameters:param
                                         
                                                           constructingBodyWithBlock:^(id<AFMultipartFormData> formData){

                                                               [formData appendPartWithFormData:data name:@"media[]"];
                                                               
                                                           }
                                                                                          error:NULL];
    
    
    //認証!
    [[PFTwitterUtils twitter] signRequest:tweetRequest];
    
    //送信!
    AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:tweetRequest success:^(AFHTTPRequestOperation* operation, id responseObject){
        
        NSLog(@"success!");
        
    }failure:^(AFHTTPRequestOperation* operation, NSError* error){
        
        NSLog(@"operation=%@",operation);
        NSLog(@"eror=%@",error);
        
    }];
    
    
    // データを送信する度に実行される処理を設定する
    //プログレスバーなど
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long totalBytesWritten, long totalBytesExpectedToWrite) {
        // アップロード中の進捗状況をコンソールに表示する
        NSLog(@"bytesWritten: %@, totalBytesWritten: %@, totalBytesExpectedToWrite: %@, progress: %@",
              @(bytesWritten),
              @(totalBytesWritten),
              @(totalBytesExpectedToWrite),
              @((float)totalBytesWritten / totalBytesExpectedToWrite));
    }];
    
    [manager.operationQueue addOperation:operation];
}

画像添付の場合も基本的なパターンは同じです。
リクエストの設定で画像を設定しているところと、画像送信で少し待たされることを想定して進捗を取得できるようにしています。
あと、ビルドの環境によってはlongがlong longになるかもしれません。

TwitterAPIに関しては本家のドキュメントを参考にするか、 最終的には本家にリンクされているのですが、こちらのサイトがよくまとまっていてわかりやすかったです。


  1. イントロダクション
  2. Twitterのアプリ登録
  3. Facebookのアプリ登録
  4. Parseの登録と設定
  5. Twitterアカウントでの認証
  6. Twitterのタイムライン投稿
  7. Facebookアカウントでの認証
  8. Facebookのフィード投稿