Nicholas Redwood Nicholas Redwood - 3 months ago 21
iOS Question

Posting image to twitter using twitterkit

I am trying to post an image and tweet using Twitters new TwitterKit with a custom UI. The only documentation they provide is how to do it with their views.

so I can figure out how to do it without an image

NSMutableDictionary *message = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[params objectForKey:@"description"],@"status",@"true",@"wrap_links", nil];

NSURLRequest* request = [twAPIClient URLRequestWithMethod:@"POST" URL:@"https://api.twitter.com/1.1/statuses/update.json" parameters:message error:nil];

[twAPIClient sendTwitterRequest:request completion:^(NSURLResponse* response, NSData* data, NSError* connectionError){



}];


But their URLRequestWithMethod method isnt mutable. how would I add an image to it. You used to do it with the SLRequest with

[postRequest addMultipartData:UIImageJPEGRepresentation(image, 0.5) withName:@"media" type:@"image/jpeg" filename:@"image.png"];

Answer

I Have figured it out.

First you need to post the image to twitter.

NSString *media = @"https://upload.twitter.com/1.1/media/upload.json";

NSData *imageData = UIImageJPEGRepresentation(image, 0.9);

NSString *imageString = [corgiData base64EncodedStringWithOptions:0];               

NSURLRequest *request = [client URLRequestWithMethod:@"POST" URL:media parameters:@{@"media":imageString} error:&requestError];

[[[Twitter sharedInstance] APIClient] sendTwitterRequest:request completion:^(NSURLResponse *urlResponse, NSData *data, NSError *connectionError) {


}];

then in the response object you use the media_id_string and add that to the parameter of the code in my question.

So

NSMutableDictionary *message = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[params objectForKey:@"description"],@"status",@"true",@"wrap_links",mediaIDString, @"media_ids", nil];

NSURLRequest* request = [twAPIClient URLRequestWithMethod:@"POST" URL:@"https://api.twitter.com/1.1/statuses/update.json" parameters:message error:nil];

[twAPIClient sendTwitterRequest:request completion:^(NSURLResponse* response, NSData* data, NSError* connectionError){

 NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&parsingError];

}];

note the media_ids object that is from the response of the first request

NSMutableDictionary *message = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[params objectForKey:@"description"],@"status",@"true",@"wrap_links",[responseDict objectForKey:@"media_id_string"], @"media_ids", nil];

So you can just put that inside the completion block and it will post the image and tweet.