App get crashing If I use the AFHTTPSessionManager setTaskDidCompleteBlock - afnetworking

Instance method '-GET:parameters:progress:success:failure:' not found (return type defaults to 'id')
I am trying to migrate the AFHTTPRequestOperation to AFHTTPSessionManager app gets crashed and shows the below error.
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:origin]];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager GET:origin parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
// Got crashed in this line and shows a warning as Instance method '-GET:parameters:progress:success:failure:' not found (return type defaults to 'id')
Also if I use the [self setTaskDidCompleteBlock:^(NSURLSession *session, NSURLSessionTask *task, NSError *error) app gets crashed. Kindly let me know what needs to be done here.
I am using the AFNetworking version4.

Related

how can i pass dictionary in json post request using afnetworking 3.0

i am trying to pass dictionary as parameter in afnetworking 3.0
NSDictionary *dictionary=[[NSDictionary alloc]initWithObjectsAndKeys:#"meetingTyp",_MeetingTypeId,#"meetinTitle",Meetingtitletxtfld.text,#"meetDescription",Meetingdistxtfld.text,#"startTym",_Starttimestr,#"hours",Meetinglengthtxtfld.text,#"meetOwnId",Useridstr,#"projectId",_ProjId,#"meetDate",[[meetDate componentsSeparatedByString: #" "]objectAtIndex:0],#"meetingId",_MeetingId,#"ConferRoomId",_ConfOwnerId,nil];
and implementing post request using afnetworking 3.0 like,
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"text/html",#"text/plain",#"application/rss+xml", nil];
[manager POST:meetingupdateurlparams parameters:meetingdictparams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
NSLog(#"response object is %#",responseObject);
[delegate meetingupdate:responseObject];
}
failure:^(NSURLSessionTask *operation ,NSError *error)
{
NSLog(#"welcome %#",error);
}];
but app crashing ,due to
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[AFHTTPSessionManager :parameters:progress:success:failure:]:
anyone can help in this issuance..Thanks in advance :)

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;

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);
}];

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.

AFNetworking 2.0 Send Post Request with URL Parameters

How do I send a POST request with AFNetworking 2.0 with all the parameters in the URL like such:
http://www.myserver.com?api_key=something&lat=2.4&radius=100
Right now I have:
NSString* query = #"http://example.com?name=param&date=param";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{};
[manager POST:query parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
But it's not working, I get this error back:
Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: bad request (400)
The previous best answer was to get the backend to change and accepts parameters in the body. Thats the preferred method but sometimes some of us are stuck using backends that can't change so I offer this solution....
In the class AFURLRequestSerialization there is a property called HTTPMethodsEncodingParametersInURI and that is an NSSet that contains the http methods that are allowed to use params in the uri GET, HEAD, and DELETE by default.
You could override that and include POST as well.
in AFURLRequestSerialization.m lines 462 has an if statement that checks self.HTTPMethodsEncodingParametersInURI property contains POST. if it doesn't (as it doesn't by default), it will put the parameters in the body.
You can comment out that id statement for a quick test.
To get it to work I recommend overwriting the HTTPMethodsEncodingParametersInURI property.
when setting up your AFHTTPSessionManager it should look like this...
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:self.httpBaseUrl]];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:#[#"POST", #"GET", #"HEAD", whatever other http methods you need here....]];
this should allow for sending a parameters in the uri of a POST. worked for me, hope it helps someone else
#import "AFNetworking.h"
...
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"param1": value1,
#"param2": value};
manager.responseSerializer = [AFJSONResponseSerializer serializer]; // if response JSON format
[manager POST:#"http://domain.com/backend.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", responseObject);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", error);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}];
try this
I've had the same problem with you.
Other people's answers seem to be accurate.
The cause of the error is:
when you init NSUrl with parameters such as http:www.baidu.com/api?id=1&name=我,it needs you to encode your urlString with utf-8
such as :
//解决奇葩需求:请求方式为post时,url带?id=1之类。主要原因是url带中文的时候url初始化失败
URLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
Hope to help you!
can you try this.
NSString* apiURL = #"http://example.com"
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:apiURL]];
manager.responseSerializer = [AFJSONResponseSerializer serilizer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
NSDictionary *parameters = #{#"name":#"John",#"date":"27/12/2013"};
AFHTTPRequestOperation *apiRequest = [manager POST:#"" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog#"response ---%#,responseObject";
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[apiRequest start];
I was able to do this by creating the string like this:
NSString *relativeURL =[NSString
stringWithFormat:#"/reward/commit?deviceUUID=%#&rewardID=%#",[[Client
sharedInstance] deviceUUID],self.rewardID];
and then passing it as the query. I had to set the requestSerializer and responseSerializer as follows:
client.requestSerializer = [AFJSONRequestSerializer serializer];
client.responseSerializer = [AFHTTPResponseSerializer serializer];
Worked for me once I left the manager.requestSerializer property alone and let it be the default (AFHTTPRequestSerializer).
The service i was POSTing to, was seemingly expecting UTF8 encoded body parameters.

Resources