I've built an API client for communicating with my web-server and all HTTP requests in my app are done using this class: (subclass of AFHTTPRequestOperationManager)
+ (SNPAPIClient *)sharedClient {
static SNPAPIClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURL *baseURL = [NSURL URLWithString:BASE_URL];
_sharedClient = [[SNPAPIClient alloc] initWithBaseURL:baseURL];
_sharedClient.responseSerializer = [AFJSONResponseSerializer serializer];
_sharedClient.requestSerializer = [AFJSONRequestSerializer serializer];
});
return _sharedClient;
}
The class has 3 methods for POST, GET & POST-MULTIPART. While POST & GET methods work perfectly, I'm having issues with POST-MULTIPART.
-(void)httpPOSTMultiPartRequestWithPath:(NSString*)path Parameters:(NSDictionary*)parameters BodyBlock:(id)bodyBlock Completion:(APICompletionBlock)apiComp{
comp = apiComp;
[self POST:path
parameters:parameters
constructingBodyWithBlock:bodyBlock
success:^(NSURLSessionDataTask *task, id responseObject) {
comp(responseObject,nil);
}
failure:^(NSURLSessionDataTask *task, NSError *error) {
comp(nil,error);
}];
}
Specifically, I'm trying to send a simple JSON to the server followed by an image. I've tried doing something like this:
From my controller i'm calling:
NSDictionary *POSTpic = [NSDictionary dictionaryWithObjectsAndKeys:@"109",@"userId",@"P",@"contentType", nil];
NSURL *pictuePath = [NSURL fileURLWithPath:@"cat.JPG"];
[[SNPAPIClient sharedClient]httpPOSTMultiPartRequestWithPath:@"PATH_GOES_HERE"
Parameters:POSTpic
BodyBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:pictuePath name:@"profile" error:nil];
}
Completion:^(id serverResponse, NSError *error){
if (serverResponse){
NSLog(@"success");
}else{
NSLog(@"error: %@",error);
}
}];
Sending this request I get the following error in debugger:
internal server error (500)" UserInfo=0xb681650 {NSErrorFailingURLKey=http://"my_path", AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0xb347d40> { URL: http://"my_path" } { status code: 500, headers {
"Content-Length" = 142;
"Content-Type" = "text/plain";
Date = "Wed, 06 Nov 2013 19:26:05 GMT";
"Proxy-Connection" = "Keep-alive";
Server = "nginx admin";
} }, NSLocalizedDescription=Request failed: internal server error (500)}
For some reason, even though I send an NSDictionary and my request serilaizer is set to AFJSONRequestSerializer, the JSON object is not created. Again, this only happens with POST MULTIPART, other requests done with the same client and settings, are processed correctly.
Thanks!