Upload image from iOS to PHP

南楼画角 提交于 2019-11-29 12:58:15
Patrick L.

Finally I used the AFNetworking library to handle this. As I haven't found clear methods to do this on the web and on stackoverflow, here is my answer to easily post user's images from their iOS device to your server via PHP. Majority of the code comes from this stackoverflow post.

-(void)uploadImage { 
    image = [self scaleImage:image toSize:CGSizeMake(800, 800)];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.7);

    // 1. Create `AFHTTPRequestSerializer` which will create your request.
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];

    NSDictionary *parameters = @{@"your_param": @"param_value"};

    NSError *__autoreleasing* error;
    // 2. Create an `NSMutableURLRequest`.
    NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:@"http://www.yoururl.com/script.php" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData
                                    name:@"userfile"
                                fileName:@"image.jpg"
                                mimeType:@"image/jpg"];
    } error:(NSError *__autoreleasing *)error];
    // 3. Create and use `AFHTTPRequestOperationManager` to create an `AFHTTPRequestOperation` from the `NSMutableURLRequest` that we just created.
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    AFHTTPRequestOperation *operation =
    [manager HTTPRequestOperationWithRequest:request
                                     success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                         NSLog(@"Success %@", responseObject);
                                     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                         NSLog(@"Failure %@", error.description);
                                     }];

    // 4. Set the progress block of the operation.
    [operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
                                        long long totalBytesWritten,
                                        long long totalBytesExpectedToWrite) {
        //NSLog(@"Wrote %lld/%lld", totalBytesWritten, totalBytesExpectedToWrite);
        [self.progressBarView setProgress:(double)totalBytesWritten / (double)totalBytesExpectedToWrite animated:YES];
    }];

    // 5. Begin!
    operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];


    self.progressView.hidden = NO;
    [operation start];
}

I think it will help new xcoders.

Cheers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!