Skip to content

Instantly share code, notes, and snippets.

@DenTelezhkin
Created July 22, 2014 15:02
Show Gist options
  • Save DenTelezhkin/beab675d853fcd2fd464 to your computer and use it in GitHub Desktop.
Save DenTelezhkin/beab675d853fcd2fd464 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