Search code examples
iphoneiosobjective-cnsdata

NSData appendData: UIImageJPEGRepresentation() returns nil


This has had me scratching for quite some time.

I am preparing a UIImage to post as part of a HTTP request. I am doing this with the following code:

[postData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
                        [postData appendData:[[NSString stringWithFormat:@"Content-Disposition: attachment; name=\"q%@\"; filename=\".jpg\"\r\n" , key] dataUsingEncoding:NSUTF8StringEncoding]];
                        [postData appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
                        [postData appendData:[NSData dataWithData:UIImageJPEGRepresentation(image, 1.0)]];
                        [postData appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

The problem I am having is that postData is null after running these lines.

Using NSLog I found out that [postData appendData:[NSData dataWithData:UIImageJPEGRepresentation(image, 1.0)]]; is the line which is causing this to happen. I then went on to see if the image was a the problem. UIImageJPEGRepresentation(image, 1.0) outputs a mass of data to the console and adding image to a UIImageView shows the .jpg I was expecting.

I am absolutely bamboozled. Please help >.< S

EDIT

After a bit of a debacle below I have realised that it is definitely posting the image .

NSLog(@"postData = %@",[postData length]);

shows 280861 (bytes?) but a PHP file with <?php print_r($_FILES); ?> returns Array {}.


Solution

  • Resolved with:

    [postData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\";\r\nfilename=\"%@.jpeg\"\r\nContent-Type: image/jpeg\r\n\r\n", key,key] dataUsingEncoding:NSUTF8StringEncoding]];
    [postData appendData:[NSData dataWithData:imageData]];
    [postData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    

    The first newline after my already included data seems to have resolved this