AFHTTPRequestOperationManager for POST image not working into Xcode 6 - afnetworking

I am developing an application which required to upload image on server.For upload image I use following code.
AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
manager1.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager1.requestSerializer setValue:#"Content-Type" forHTTPHeaderField:#"text/html"];
manager1.responseSerializer = [AFJSONResponseSerializer serializer];
manager1.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
AFHTTPRequestOperation *op= [manager1 POST:urlString parameters:Nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"photo" fileName:[NSString stringWithFormat:#"%#.jpeg",timeStamp] mimeType:#"image/jpeg"];
}success:^(AFHTTPRequestOperation *operation, id responseObject) { }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[self dismissLoading];}];[op start];
My problem is that when I run same code from Xcode 5 into iPad 2 iOS 8.1, then It will work fine. But when I run same code from Xcode 6.1 into same iPad 2 iOS 8.1, It get request time out.
Please help..!

Few days ago i also had the same problem with AFHTTPRequestOperationManager. I was not able to upload image on server with xcode 6. But when i resolve the warnings (https://github.com/AFNetworking/AFNetworking/commit/0ae246896e2327a31d26dcb998375af8fe9209a2 ) then its working fine. Hope this will help you and others :)

Related

AFNetwoking POST call returns 500 internal server error but server got request parameter

I'm trying to upload my payment success message to my server. Below are my code
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
[manager.requestSerializer setValue:[NSString stringWithFormat:#"Bearer %#",myTokenString] forHTTPHeaderField: #"Authorization"];
AFHTTPRequestOperation *operation = [manager POST:#"MYAPI" parameters:paramsDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#",error.localizedDescription);
}];
[operation start];
But I'm getting error code 500 (internal server error). But my server has all the information and API call is success. Can anyone please help me understand why it's entering the error block?
In new AFNetworking version, you don't need a initialize for AFHTTPRequestOperation class to handle request so you just adjust your code as following:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:[NSString stringWithFormat:#"Bearer %#",myTokenString] forHTTPHeaderField: #"Authorization"];
[manager POST:#"MYAPI" parameters:paramsDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#",error.localizedDescription);
}];
By default requestSerializer is set to an instance of AFHTTPRequestSerializer, which means that Content-Type of your request will be application/x-www-form-urlencoded.
But if your server requires application/json content type for that api, then you must set to an instance of AFJSONResponseSerializer
E.G.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
Encode your url.
NSString *unescaped = #"http://www";
NSString *escapedString = [unescaped stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
Try with formData
[manager POST:#"API" parameters:paramsDict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
it's AFNetworking 3.0 Method, but you can used same (formData) in AFNetworking 2.x
I had been encountering the same issue with AFNetworking POST as well as sometimes on GET calls but... Sometimes i would get a 500 internal server error although the server received request parameters!! Finally after some research with my web services backend developers, i came to know that its caused due to a DLL misconfiguration on the server side, particularly the System.reflection DLL file. Deleting the file from the server side (if it exists) removes the issue, otherwise copy pasting it back from the Bin (if it doesn't exist already) removes the issue. This is pretty baffling but apparently it fixes it!!
AND YES. IT HAS NOTHING TO DO WITH AFNETWORKING!
The answer assumes Microsoft azure server
Try to see what the detail accept/content type is for android. Do you know if they are using retrofit? Most likely it will have to do with your request or response serializer not matching what server is expecting.
Add the below coding to AFURLResponseSerialization.m file and remove the existing code.
#implementation AFJSONResponseSerializer
self.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"application/xml",#"text/html", nil];
return self;

Send Asset Video to web service - iOS

I am trying to send video in assets library to web service with parameter video but how is it possible to do ?
I got the NSURL as the following : assets-library://asset/asset.MOV?id=What-ever-0000-000&ext=MOV
I am using AFNetworking to send the post request and here is my code :
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager setSecurityPolicy:[AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]];
[manager.requestSerializer setValue:#"no-cache" forHTTPHeaderField:#"Catch-Control"];
NSDictionary *parameters = #{#"video": myurl};
[manager POST:#"this is my service link" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Do I need to convert the NSURL to another representation so I can submit it? I have no idea?
You can post video to server like this.
AFHTTPRequestOperation *op = [theManager POST:urlString
parameters:theParameters
constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileURL:postedVideoURL name:#"media" fileName:#"FinalMovie.mp4" mimeType:#"mp4" error:nil];
[formData appendPartWithFileData:imgData name:#"video_thumb" fileName:#"png" mimeType:#"image/jpeg"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{}];
[op start];
Create theManager object like this.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
Hope this helps.

I cant get rid of Request failed: bad request (400)

NSDictionary *parameters = #{
#"project_name": #"hasanProj",
#"project_desc" : #"testing...",
#"project_date" : #"2015-2-22"
};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithBaseURL:[NSURL URLWithString:#"http://serverIP"]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:[HRUser sharedUser].userApiKey forHTTPHeaderField:#"Authorization"];
[manager POST:#"/rest/v1/project" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"%#",responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"error: %#",error.localizedDescription);
}];
This code is returning Request failed: bad request (400).
I checked parameter, url they are all correct. I called it from chrome extension postman and getting correct result.
And other requests are working perfectly, even get is working fine.
But why I am getting Request failed: bad request (400) on this?
I was also facing the same error and this worked for me..
manager.responseSerializer.acceptableStatusCodes = [NSIndexSet indexSetWithIndex:400];
or
You can directly parse the response object.
i think there will be problem with the request. your putting wrong type or wrong data.
acceptableContentTypes for request also matters.
second thing the parameters that your sending data to it. check tags correct are not
ask WEB service developer exact need of API.
Code:
NSDictionary *parameters = #{
#"project_name": #"hasanProj",
#"project_desc" : #"testing...",
#"project_date" : #"2015-2-22"
};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]init];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:[HRUser sharedUser].userApiKey forHTTPHeaderField:#"Authorization"];
[manager.requestSerializer.acceptableContentTypes setByAddingObject:#"application/json"];
[manager.responseSerializer.acceptableContentTypes setByAddingObject:#"application/json"];
[manager POST:#"http://serverIP/rest/v1/project" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject)
{
NSLog(#"%#",responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"error: %#",error.localizedDescription);
}];

How to send OAuth2 Access token from IOS 7 to google blobstore using AFNNetworking API

From iPhone i am trying to send oAuth Access token as http header to upload image to google blobstore service .I got the blob upload url fine but when I try to upload image I am getting NullPointer exception in upload handler servlet, saying user is null .I am using AFNNetwokring API . I pasted Exception and IOS code below .Please help.Thanks in advance.
NullPointer exception java.lang.NullPointerException
at com.allyouralbums.servlets.AppContext.getCurrentUser(AppContext.java:91)
at com.allyouralbums.servlets.UploadHandlerServlet.doPost(UploadHandlerServlet.java:45)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
- (void)postImage :(UIImage *) image
toUploadURI:(NSString*) blobServiceURL
withAuthentication:(GTMOAuth2Authentication*) auth{
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:[NSString stringWithFormat:#"Bearer %#", [auth accessToken]] forHTTPHeaderField:#"Authorization"];
[manager POST: blobServiceURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"FromIos" fileName:#"FromIos" mimeType:#"image/jpg;"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}

AFNetworking ASPXAUTH Cookies AFHTTPRequestOperationManager

I am trying to work with a .NET server that is returning a ASPXAUTH cookie when logging in. I am definitely getting the cookie back when I watch my network traffic with Charles, but when I inspect [NSHTTPCookieStorage sharedHTTPCookieStorage] I am not finding it contains anything. Listed is my code below. Any help would greatly be appreciated!
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc]
initWithBaseURL:[NSURL URLWithString:#"http://someurl.com/api/"]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary *parameters = #{#"UserName":#"SomeUserName", #"Password":#"SomePassword"};
[manager POST:#"User/Login" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
I found the solution as... taking the cookie and setting the http header value like so...
[manager.requestSerializer setValue:[NSString stringWithFormat:#".ASPXAUTH=%#", cookie[#"Value"]] forHTTPHeaderField:#"Cookie"];
.NET expects the cookie returned in the above format. Hope this helps anyone.

Resources