I am getting the above warning in this code on line number 6 and the userInfo also becoming nil in the block.Please suggest something to remove this warning and userInfo issue.
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"some url"]];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient setDefaultHeader:#"Accept" value:#"application/json"];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:path parameters:parameters];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSDictionary* JSON)
{
[self.delegate didReceivedResponse:JSON withUserInfo:operation.userInfo];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response,
NSError *error, id JSON)
{
NSLog(#"Network : %#",error);
[self.delegate didFailWithError:error withUserInfo:operation.userInfo];
}];
operation.userInfo = userInfo;
[operation start];
Just use userInfo variable when you create operation, instead of calling operation.userInfo - which is not existing in a moment you are creating it.
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"some url"]];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient setDefaultHeader:#"Accept" value:#"application/json"];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:path parameters:parameters];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSDictionary* JSON)
{
[self.delegate didReceivedResponse:JSON withUserInfo:userInfo];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response,
NSError *error, id JSON)
{
NSLog(#"Network : %#",error);
[self.delegate didFailWithError:error withUserInfo:userInfo];
}];
operation.userInfo = userInfo;
[operation start];
Another option is to set block later:
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"some url"]];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient setDefaultHeader:#"Accept" value:#"application/json"];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:path parameters:parameters];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:nil failure:nil];
operation.userInfo = userInfo;
[operation setCompletionBlockWithSuccess:^(NSURLRequest *request, NSHTTPURLResponse *response, NSDictionary* JSON)
{
[self.delegate didReceivedResponse:JSON withUserInfo:userInfo];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response,
NSError *error, id JSON)
{
NSLog(#"Network : %#",error);
[self.delegate didFailWithError:error withUserInfo:userInfo];
}];
[operation start];
Related
I am trying to make a POST request using AFNetworking. I went through SO and found that I need to include httpClient.parameterEncoding = AFJSONParameterEncoding
It still doesn't work even after making that change. Anything else I am missing ? Here is the code
NSDictionary *subDictionaryUsers = [[NSDictionary alloc]initWithObjectsAndKeys:myObject.name,#"name", myObject.topic_description,#"description", nil];
NSString *_restPath = [NSString stringWithFormat:#"spaces.json/auth_token=%#",myObject.auth_token];
NSDictionary *params = [[NSDictionary alloc]initWithObjectsAndKeys:subDictionaryUsers,#"space",nil];
myAppAFNClient *httpClient = [myAppAFNClient sharedClient];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:_restPath parameters:params];
httpClient.parameterEncoding = AFJSONParameterEncoding;
[httpClient getJsonResponse:request notificationString:#"add.hydramixer.topics"];
myAppAFNClient.m
-(void)getJsonResponse:(NSURLRequest *)_request notificationString:(NSString *)notifString{
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:_request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
if([notifString length] != 0){
// handling success
}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){
// handling errors
}];
[operation start];
}
I'm getting this response in error.userInfo while making a POST request from AFNetworking.
Can anyone tell either I'm missing anything obvious or something need to fix at my server end?
Request Failed with Error: Error Domain=AFNetworkingErrorDomain
Code=-1016 "Expected content type {(
"text/json",
"application/json",
"text/javascript" )}, got text/html" UserInfo=0x6d7a730 {NSLocalizedRecoverySuggestion=index test,
AFNetworkingOperationFailingURLResponseErrorKey=, NSErrorFailingURLKey=http://54.245.14.201/,
NSLocalizedDescription=Expected content type {(
"text/json",
"application/json",
"text/javascript" )}, got text/html, AFNetworkingOperationFailingURLRequestErrorKey=http://54.245.14.201/>}, {
AFNetworkingOperationFailingURLRequestErrorKey = "http://54.245.14.201/>";
AFNetworkingOperationFailingURLResponseErrorKey = "";
NSErrorFailingURLKey = "http://54.245.14.201/";
NSLocalizedDescription = "Expected content type {(\n \"text/json\",\n \"application/json\",\n
\"text/javascript\"\n)}, got text/html";
NSLocalizedRecoverySuggestion = "index test"; }
And I'm using this code;
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient setDefaultHeader:#"Accept" value:#"application/json"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
#"Ans", #"name",
#"29", #"age",
nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:#"/" parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"Success");
NSLog(#"%#",JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
NSLog(#"Failure");
}];
[operation start];
[operation waitUntilFinished];
By default, AFJSONRequestOperation accepts only "text/json", "application/json" or "text/javascript" content-types from server, but you are getting "text/html".
Fixing on server would be better, but you can also add "text/html" content type as acceptable in your app:
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:#"text/html"]];
It worked for me, hope this helps!
Did you send this POST request by AFHTTPClient? If so, you need to set operation class for it:
AFHTTPClient * client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://localhost:8080"]];
// ...
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefaultHeader:#"Accept" value:#"application/json"];
// ...
// EDIT: Use AFHTTPClient's POST method
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
#"Ans", #"name",
#"29", #"age", nil];
// POST, and for GET request, you need to use |-getPath:parameters:success:failure:|
[client postPath:#"/"
parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"RESPONSE: %#", responseObject);
// ...
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (error)
NSLog(#"%#", [error localizedDescription]);
// ...
}
Set your values in this code and check if it works for you
AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:[NSURL URLWithString:kBASEURL]];
NSString *_path = [NSString stringWithFormat:#"groups/"];
_path = [_path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%s %#",__PRETTY_FUNCTION__,_path);
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:_path
parameters:postParams];
[httpClient release];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
if ([JSON isKindOfClass:[NSArray class]] || [JSON isKindOfClass:[NSDictionary class]]) {
completed(JSON);
}
else {
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#" response %# \n error %# \n JSON %#",response,error,JSON);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
errored(error);
}];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
I want to "POST" a JSON value to server and response a json databack.
The URL: http://solok.com:8080/soloo/phone/execute?content={"method":"tet_123","version","1"}, can get the right value(JSON) in browser.
ASIHTTPRequest way:
NSDictionary *postDic = [NSDictionary dictionaryWithObjectsAndKeys:#"tet_123",#"method",#"1",#"version",nil];
NSString *postString;
//Then convert the "postDic" to NSString, the value is:{"method":"tet_123","version","1"} assign to postString;
psotString = ...;
ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
[req setRequestMethod:#"POST"];
[req setPostValue:posStr forKey:#"content"];
[req startAsynchronous];
[req setDelegate:self];
[req setCompletionBlock:^{
NSData *d = [req responseData];
NSLog(#"respond is %#".d);
}
It works smoothly! But AFNetworkding is not, here is the code;
NSURL *url = [NSURL URLWithString:#"http://localhost:8080"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:#"tet_123",#"method",#"1",#"version",nil];
NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:dic,#"content", nil];
[httpClient postPath:#"/soloo/phone/execute" parameters:dic1 success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *d = (NSDictionary *)responseObject;
NSLog(#"success is %#",d);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"fail");
}];
The output is: success is <>.
or i use another way of AFNetworking:
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"path:#"/soloo/phone/execute" parameters:dic1];
AFJSONRequestOperation *ope = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"response %d",response.statusCode);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"fail%d JSON %#",response.statusCode,JSON);
}];
The respond code is 200, which means connection is correct, but still no the correct result.
Not sure why. Any help, thank in advance!
The reason is is the backend is a "GET" method, but i did "POST", meanwhile, i forgot: [Operation start] method.
Dumb question. I'm just pasting the example AFNetworking code in:
NSURL *url = [NSURL URLWithString:#"https://gowalla.com/users/mattt.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"Name: %# %#", [JSON valueForKeyPath:#"first_name"], [JSON valueForKeyPath:#"last_name"]);
} failure:nil];
[operation start];
But, nothing happens. If I output operation to NSLog it looks like the request was cancelled:
<AFJSONRequestOperation: 0x81655f0, state: isExecuting, cancelled: NO request: <NSURLRequest https://gowalla.com/users/mattt.json>, response: (null)>
What am I doing wrong?
Your best bet would be to add a failure block and then inspect the variables provided in that
NSURL *url = [NSURL URLWithString:#"https://gowalla.com/users/mattt.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"Name: %# %#", [JSON valueForKeyPath:#"first_name"], [JSON valueForKeyPath:#"last_name"]);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"%#", [error localizedDescription]);
}];
[operation start];
I'm using NSMutableURLRequest before using AFJSONOperationRequest and I have a problems getting the data in my Rails app.
If I use :
NSMutableURLRequest *request = [[HTTPClient sharedClient] multipartFormRequestWithMethod:#"POST" path:path parameters:dict constructingBodyWithBlock: ^(id <AFMultipartFormData>formData)
{
}];
Then :
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
else {
}
}
I get my data correctly formatted in the Rails logs:
Parameters: {"contact"=>{"country_id"=>"45", "lastname"=>"Tutu"}}
But I don't need AFMultipartFormData to send a file... (no file to send)
So, instead, I use:
NSMutableURLRequest *request = [[HTTPClient sharedClient] multipartFormRequestWithMethod:#"POST" path:path parameters:dict];
with my AFJSONRequestOperation too. But, my parameters are now not set correctly in my rails app:
Parameters: {contact[country_id] => "45", contact[lastname] => "Tutu"}
instead of
Parameters: {"contact"=>{"country_id"=>"45", "lastname"=>"Tutu"}}
I don't understand why. It looks like the body of the request is not set correctly when I don't use the block: "constructingBodyWithBlock".
Don't use multipartFormRequestWithMethod.
Just use the postPath method like this
[[YourHTTPClient sharedClient] postPath:path
parameters:dict
success:^(AFHTTPRequestOperation *operation, NSString* path){
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
Edit:
If you need an operation use AFJSONRequestOperation directly
+ (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure;
NSURL *url = [NSURL URLWithString:#"http://yoursite.com/path"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
}];