Thursday, May 31, 2012

Posting to twitter with TWRequest

It took me a while but I finally found a solution to posting a status with TWRequest. I had to use the addMultiPartData: method and separately add the status and image. Hope this helps anybody who has the same problem I had.


        if ([TWTweetComposeViewController canSendTweet])
    {
        // Create account store, followed by a twitter account identifier
        // At this point, twitter is the only account type available
        ACAccountStore *account = [[ACAccountStore alloc] init];
        ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier: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];
                     
                     NSString *status = [[NSString alloc] initWithString:captionField.text];
                     
                     // Build a twitter request
                     TWRequest *postRequest = [[TWRequest alloc] initWithURL:[NSURL URLWithString:@"https://upload.twitter.com/1/statuses/update_with_media.json"] 
                                                                  parameters:nil requestMethod:TWRequestMethodPOST];
                     
                    
                     [postRequest addMultiPartData:[captionField.text dataUsingEncoding:NSUTF8StringEncoding] withName:@"status" type:@"multipart/form-data"];
                    
                     // "http://api.twitter.com/1/statuses/update.json"
                    
                     
                     [postRequest addMultiPartData:UIImageJPEGRepresentation(image, 0.9) withName:@"media" type:@"multipart/png"];
                     // 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]);
                      }];
                     [postRequest release];
                     [status release];
                 }
             }
         }];
        [account release];
        
    }

2 comments :