I'm trying to post an image to a webservice by means of an HTTP POST request.
The API doc says that image parameter should be the "binary file data for the image you would like analyzed - PNG, GIF, JPG only."
This is the code I'm trying to use:
UIImage *image = [UIImage imageNamed:@"air.jpg"];
NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
NSURLResponse *response;
NSError *error = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://pictaculous.com/api/1.0/"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:imgData];
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if(error!=nil) {
NSLog(@"web service error:%@",error);
}
else {
if(receivedData !=nil) {
NSError *Jerror = nil;
NSDictionary* json =[NSJSONSerialization
JSONObjectWithData:receivedData
options:kNilOptions
error:&Jerror];
if(Jerror!=nil) {
NSLog(@"json error:%@",Jerror);
}
}
}
The problem is that in the JSON response I always receive the error "You must provide an image" as if the format of the received image was not correct.
Isn't "UIImageJPEGRepresentation" the correct way to get binary data from an image ?
Is there any other way I can get the binary file data from my JPEG image ?
Thanks, Corrado
If you want to simplify your code, you can use a simple NSURLConnection wrapper such as STHTTPRequest.
STHTTPRequest *r = [STHTTPRequest requestWithURLString:@"http://pictaculous.com/api/1.0/"];
NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"jpg"];
NSData *data = [NSData dataWithContentsOfFile:path];
[r addDataToUpload:data parameterName:@"image"];
r.completionBlock = ^(NSDictionary *headers, NSString *body) {
NSLog(@"-- %@", body);
};
r.errorBlock = ^(NSError *error) {
NSLog(@"-- error: %@", error);
};
[r startAsynchronous];