Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronwardle/49ad2ecb7227936d1bb2c49b798d0dc6 to your computer and use it in GitHub Desktop.
Save aaronwardle/49ad2ecb7227936d1bb2c49b798d0dc6 to your computer and use it in GitHub Desktop.
Multipart-form PUT request for image upload. NSURLSession, iOS 7
+(void)uploadUserPhoto:(UIImage *)image
success:(void (^)(void))success
failure:(FailureBlock)failure
{
GTSessionManager * manager = [GTSessionManager manager];
NSString* tmpFilename = [NSString stringWithFormat:@"%f", [NSDate timeIntervalSinceReferenceDate]];
NSURL* tmpFileUrl = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:tmpFilename]];
NSString * query = [NSString stringWithFormat:@"%@user?auth_token=%@",[manager.baseURL absoluteString],[[UserManager shared] authToken]];
// Create a multipart form request.
NSMutableURLRequest *multipartRequest = [[manager requestSerializer] multipartFormRequestWithMethod:@"PUT"
URLString:query
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileData:UIImagePNGRepresentation(image)
name:@"photo"
fileName:@"photo.png"
mimeType:@"image/png"];
} error:nil];
[[manager requestSerializer] requestWithMultipartFormRequest:multipartRequest
writingStreamContentsToFile:tmpFileUrl
completionHandler:^(NSError *error) {
NSURLSessionUploadTask * task = [manager uploadTaskWithRequest:multipartRequest
fromFile:tmpFileUrl
progress:nil
completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
[[NSFileManager defaultManager] removeItemAtURL:tmpFileUrl error:nil];
if (error) {
if (failure)
{
failure(error);
}
} else {
if (success)
{
success();
}
}
}];
[task resume];
}];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment