使用AFNetworking上传图像选择器

Sorry for my ignorance. I can't quite get a hang of it all yet.

So currently I have the code:

NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"image.png"]);

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
                                    initWithURL:[NSURL
                                                 URLWithString:@"http://xyz.co.uk/zyx/imageupload.php"]];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"image/png"
   forHTTPHeaderField:@"Content-type"];
    [request setValue:[NSString stringWithFormat:@"%lu",
                       (unsigned long)[imageData length]]
   forHTTPHeaderField:@"Content-length"];
     [request setHTTPBody:[self imageDataToSend]];

    [[NSURLConnection alloc] initWithRequest:request delegate:self];

imageupload.php:

<?php
$handle = fopen("image.png", "wb"); // write binary

fwrite($handle, $HTTP_RAW_POST_DATA);

fclose($handle);

print "Received image file.";
?>

Which uploads a photo to my website... Perfect... NO!

I have noticed some problems.

  1. There is no loading gif at the top of the iphone indicating any kind of activity.
  2. There is no way to create a delegate sector so that I can indicate if there has been an error or success.

I then looked towards this. Which was all well and good until I realised that it infact was rubbish and I have received a million errors on trying to upload it. Also everyone told me that I am going in the wrong direction "ASIHTTPRequest is old. You should use AFNetworking".

And I am now trying to work with AFNetworking but it is proving to be extremely difficult! I can't see how it is similar to ASIHTTPRequest at all.


Can anybody help me do the equivelant kind of thing with AFNetwork. Or a whole knew way of uploading image data to my php file.


Errors from Jai Govindani:

enter image description here

Here's an example of photo upload using AFNetworking - ZodioAPIClient is my AFHTTPClient subclass. You'll want to subclass AFHTTPClient (and usually create a singleton to do stuff like below). The filenames are of course your choice, all that really matters is appending the NSData. Note that this is for AFNetworking < 2.0. 2.0's structure is different but if you can understand below, you can migrate it to 2.0 pretty easily.

The steps are (this applies to all AFNetworking operations, with some special steps for the photo data):

  1. Create an NSMutableURLRequest and append the NSData
  2. Create an AFJSONRequestOperation using the NSMutableURLRequest and specify your success/failure blocks
  3. optional - specify an upload progress block with a callback to whoever/whatever you want to use to handle upload progress
  4. Enqueue the operation (if you don't do this nothing will happen, the operation won't get started)

NSData *photo = UIImagePNGRepresentation([UIImage imageNamed:@"image.png"]);

NSMutableURLRequest *addPhotoRequest = [[YourAFHTTPClientSubclass sharedClient] multipartFormRequestWithMethod:@"POST" path:addPhotoPath parameters:parameters constructingBodyWithBlock:^(id <AFMultipartFormData> formData)
                           {
                               [formData appendPartWithFileData:photo name:@"photo" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
                           }];

AFJSONRequestOperation *addPhotoRequestOperation = [AFJSONRequestOperation JSONRequestOperationWithRequest:addPhotoRequest
                                                                                                success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)

                                                 {
                                                     DDLogVerbose(@"in add photo success block");
                                                 }
                                                  failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
                                                 {
                                                     DDLogVerbose(@"request that errored: %@", request);
                                                     DDLogVerbose(@"Request failed with error: %@, %@", error, error.userInfo);
                                                     DDLogVerbose(@"the response I got was: %@", JSON);
                                                 }];

[addPhotoRequestOperation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite)
 {
     DDLogVerbose(@"Total progress: %f", (totalBytesWritten * 1.0f)/(totalBytesExpectedToWrite * 1.0f));
 }];

[[YourAFHTTPClientSubclass sharedClient] enqueueHTTPRequestOperation:addPhotoRequestOperation];