Skip to content

Instantly share code, notes, and snippets.

@chrisallick
Created February 4, 2013 19:25
Show Gist options
  • Save chrisallick/4708918 to your computer and use it in GitHub Desktop.
Save chrisallick/4708918 to your computer and use it in GitHub Desktop.
I was having a hard time figuring out how to upload an image to Twitter with a progress callback. Turns out I wasn't far off, just needed to convert my SLRequest to an NSURLRequest and then AFNetworking(godbless you) does the rest with progress blocks.
-(void)sendTwitter {
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:
ACAccountTypeIdentifierTwitter];
[account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
if (granted == YES) {
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0) {
twitterAccount = [arrayOfAccounts lastObject];
NSString *status = @"Secrets";
UIImageView *uploadImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 640, 480)];
UIImage *uploadImage = [image resizedImageToFitInSize:uploadImageView.bounds.size scaleIfSmaller:NO];
NSURL *requestURL = [NSURL URLWithString:@"https://upload.twitter.com/1.1/statuses/update_with_media.json"];
SLRequest *postRequest = [SLRequest
requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST
URL:requestURL parameters:nil];
[postRequest addMultipartData:UIImageJPEGRepresentation(uploadImage, 0.6) withName:@"media[]" type:@"multipart/form-data" filename:nil];
[postRequest addMultipartData:[status dataUsingEncoding:NSUTF8StringEncoding] withName:@"status" type:@"multipart/form-data" filename:nil];
[postRequest setAccount:twitterAccount];
NSURLRequest *preparedRequest = [postRequest preparedURLRequest];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:preparedRequest];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Twitter upload success");
[self completedSendingPhotos];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Twitter upload error");
}];
[operation start];
}
}
}];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment