Skip to content

Instantly share code, notes, and snippets.

@funami
Created April 17, 2012 15:50
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save funami/2407027 to your computer and use it in GitHub Desktop.
Save funami/2407027 to your computer and use it in GitHub Desktop.
Upload file to S3 with AFNetworking
#import "AFNetworking.h"
- (IBAction)uploadTest:(id)sender {
NSURL *url = [NSURL URLWithString:@"https://xxx.s3-ap-northeast-1.amazonaws.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"194-note-2.png"]);
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
@"xxxxx/videos/XXXXW",@"key",
@"XXXXXXXX",@"AWSAccessKeyId",
@"XXXXXXXXXXXXXXXXXXXXXXXXXXXXX",@"policy",
@"XXXXXXXXXXXXXXXXXXXXXXXXX",@"signature",
nil];
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/" parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:@"file" fileName:@"194-note-2.png" mimeType:@"image/png"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
NSLog(@"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *theOperation, id responseObject) {
NSLog(@"Success:%@,%@",operation.response.allHeaderFields, operation.responseString);
} failure:^(AFHTTPRequestOperation *theOperation, NSError *error) {
NSLog(@"Error:%@ ,%@,%@",error,operation.response.allHeaderFields,operation.responseString);
}];
[operation start];
}
@fmundaca
Copy link

in the setCompletionBlockWithSuccess and the failure is a better option use the object "theOperation" instead of operation. It may causes of leaks.

Nice code btw

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment