2012-06-05 23 views
1

如何使用TWRequest, 我使用此代碼如何使用TWRequest

張貼到時間表更改個人資料圖片來改變輪廓圖象

- (IBAction爲)postToTwitter { ACAccountStore *帳戶= [[ACAccountStore的alloc] INIT]; ACAccountType * accountType = [account accountWithAccountTypeIdentifier: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 

      //http://api.twitter.com/1/account/update_profile_image.json 
      //https://upload.twitter.com/1/statuses/update_with_media.json 

      TWRequest *postRequest = [[TWRequest alloc] initWithURL:[NSURL URLWithString:@"https://upload.twitter.com/1/statuses/update_with_media.json"] parameters:nil requestMethod:TWRequestMethodPOST]; 

      //NSData *myData = UIImagePNGRepresentation(self.selectedImage); 
      NSData *myData = UIImageJPEGRepresentation(self.selectedImage, 0.5); 

      [postRequest addMultiPartData:myData withName:@"media" type:@"image/jpg"]; 

      [postRequest setAccount:acct]; 

      // Block handler to manage the response 
      /*  
       [postRequest addMultiPartData:[base64 dataUsingEncoding:NSUTF8StringEncoding] // base64 is an NSString of the encoded image 

       withName:@"image" 

       type:@"multipart/form-data"]; 

       // Post the request*/ 

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


    } 
    } 
}]; 

}

回答

2

我這個掙扎過,使用蘋果的WWDC11幻燈片爲指導,但似乎Twitter已經改變了API從那時起(或幻燈片有一個bug)。

解決方案很簡單:您需要使用「圖片」而不是「媒體」的多部分數據名稱。我認爲這個類型應該是「image/jpeg」,而不是「image/jpg」。

因此改變該行如下:

[postRequest addMultiPartData:myData withName:@"image" type:@"image/jpeg"];