SocialFrameworkを使ってTwitterに画像をPOSTするにはどうすればいいのだろうか?
POST statuses/updateを読むと、Uploading Media: Multiple Photosに記載されている
https://upload.twitter.com/1.1/media/upload.jsonにPOSTしろと書かれているので、まずは、下のような形でACAccountを取得する
ACAccount *aCAccount; ACAccountStore *aCAccountStore = [[ACAccountStore alloc] init]; ACAccountType *aCAccountType = [aCAccountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter]; [aCAccountStore requestAccessToAccountsWithType:aCAccountType options:nil completion:^(BOOL granted,NSError *error){ //許可がおりた時 if (granted) { dispatch_async(dispatch_get_main_queue(), ^{ NSArray *acAcounts = [aCAccountStore accountsWithAccountType:aCAccountType]; NSUInteger count = [acAcounts count]; //今回は、1個のアカウントの場合を考える aCAccount = (ACAccount *)[acAcounts objectAtIndex:0]; }); } }];次に下のように組んでPOSTを行った。
//POSTするimage UIImage *image; SLRequest *sLRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:@"https://upload.twitter.com/1.1/media/upload.json"] parameters:nil]; [sLRequest addMultipartData:UIImageJPEGRepresentation(image,1.0) withName:@"media" type:@"image/jpeg" filename:@"image.jpg"]; sLRequest.account = aCAccount; [sLRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error){ if (!error) { NSDictionary *dictJSON = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil]; NSString *mediaIdString = (NSString *)[dictJSON objectForKey:@"media_id_string"]; dispatch_async(dispatch_get_main_queue(), ^{ SLRequest *sLRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/update.json"] parameters:@{@"media_ids":mediaIdString,@"status":@"test"}]; sLRequest.account = aCAccount; [sLRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error){ if (!error) { NSDictionary *dictJSON = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil]; if (![dictJSON objectForKey:@"errors"]) { dispatch_async(dispatch_get_main_queue(), ^{ }); } } }]; }); } }];https://upload.twitter.com/1.1/media/upload.jsonで投げた結果、media_id_stringをもらうことができるので、これをパラメータに使って送信することで画像付きツイートを実行することができた。
ぐぐってみたところ、statuses/update_with_media でアップロードしている例がありましたが、すでに、deprecatedされているので、できれば上の方法でいきたいですね。
0 コメント:
コメントを投稿