在IOS5中使用TWrequest向Twitter发送带有文字的图片。

8

根据 Apple 的示例,我可以使用 TWRequest 轻松发送推文,如下所示:

 ACAccountStore *account = [[ACAccountStore alloc] init];
 ACAccountType *accountType = [accountaccountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

// Request access from the user to access their Twitter account
[account requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) 
 {
     // Did user allow us access?
     if (granted == YES)
     {
         // Populate array with all available Twitter accounts
         NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];

         // Sanity check
         if ([arrayOfAccounts count] > 0) 
         {
             // Keep it simple, use the first account available
             ACAccount *acct = [arrayOfAccounts objectAtIndex:0];

             // Build a twitter request
           TWRequest *postRequest = [[TWRequest alloc] initWithURL:
                                  [NSURL URLWithString:@"http://api.twitter.com/1/statuses/update.json"] 
                                                          parameters:[NSDictionary dictionaryWithObject:@"tweet goes here" 
                                                                                                 forKey:@"status"] requestMethod:TWRequestMethodPOST];             

             // Post the request
             [postRequest setAccount:acct];

            // Block handler to manage the response
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) 
              {
                  NSLog(@"Twitter response, HTTP response: %i", [urlResponse statusCode]);
              }];

但我想知道是否有可能以某种方式使用http://api.twitter.com/1/statuses/update_with_media.json来发送带有图像的推文,而不是通过Twitpic或其他服务。还是有其他方法可以在推文中发送图像?

谢谢


最终的代码是什么样子? - Ali
1个回答

14

这是可能的。 您需要使用addMultiPartData:withName:type:方法为您的推文添加属性。 状态文本在您将其添加为多部分数据之前不会显示。

TWRequest *postRequest = [[TWRequest alloc] initWithURL:[NSURL URLWithString:@"https://upload.twitter.com/1/statuses/update_with_media.json"] parameters:nil requestMethod:TWRequestMethodPOST];
NSData *myData = UIImagePNGRepresentation(img);
[postRequest addMultiPartData:myData withName:@"media" type:@"image/png"];
myData = [[NSString stringWithFormat:@"Any status text"] dataUsingEncoding:NSUTF8StringEncoding];
[postRequest addMultiPartData:myData withName:@"status" type:@"text/plain"];

@Andrey,我只想发送文本,那么TWRequest的URL应该是什么? - Hitarth
@Coder 你不需要使用 update_with_media 方法。Apple 的示例程序使用了如下代码:TWRequest *postRequest = [[TWRequest alloc] initWithURL:[NSURL URLWithString:@"http://api.twitter.com/1/statuses/update.json"] parameters:[NSDictionary dictionaryWithObject:@"Hello. This is a tweet." forKey:@"status"] requestMethod:TWRequestMethodPOST]; - Andrey Kuznetsov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接