Skip to content

Instantly share code, notes, and snippets.

@balazsnemeth
Created March 30, 2015 21:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save balazsnemeth/cbdf3b352bb7a7df8661 to your computer and use it in GitHub Desktop.
Save balazsnemeth/cbdf3b352bb7a7df8661 to your computer and use it in GitHub Desktop.
iOS - Twitter upload image with SLRequest
/**
* Upload an image to twitter to get media_id for is
*
* @param img The image (UIImage or NSData) to be uploaded
* @param completion
*/
- (void)sendTweetWithImage:(id)img withCompletion:(void(^)(NSNumber *mediaID, NSError *error))completion {
NSURL *requestURL = [[NSURL alloc] initWithString:@"https://upload.twitter.com/1.1/media/upload.json"];
//Get image data
NSData *data = img;
if ([img isKindOfClass:[UIImage class]]) {
data = UIImagePNGRepresentation(img);
}
ACAccount *twitterAccount = [self.accounts objectAtIndex:0];
SLRequest *postRequest = [SLRequest
requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST
URL:requestURL parameters:nil];
//Setup upload TW request
[postRequest addMultipartData:data withName:@"media" type:@"image/png" filename:@"image.png"];
postRequest.account = twitterAccount;
//Post the request to get the media ID
[postRequest performRequestWithHandler:
^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if (!error && responseData) {
NSString *resp = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
DLog(@"restp : %@",resp);
if (error) {
NSLog(@"error :%@",error);
}
NSError *jsonError = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonError];
if (jsonError) {
error = jsonError;
}
if (completion) {
completion(json[@"media_id"],error);
}
}
else {
if (completion) {
completion(nil,error);
}
}
}];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment