Im trying to get response from using GeoNames API. and here my Code
NSMutableDictionary * parameters = [[NSMutableDictionary alloc]initWithDictionary:params];
NSURL *baseURL = [NSURL URLWithString:#"http://api.geonames.org/findNearbyPostalCodesJSON"];
AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"" parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
[delegate didReceiveNearByLocationResponse:responseObject];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"%#",error);
}];
Im getting following error.
Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: forbidden (403)" UserInfo={NSUnderlyingError=0x7ff013d840f0 {Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo={com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7ff013d07440> { URL: http://api.geonames.org/findNearbyPostalCodesJSON/ }
i tried with hurl.it to check whether response coming or not. and its coming fine.
Surprise is im using same above code for various other requests with only changing URL and those are working fine.
UPDATED
And previously it worked for the following code. and i did some code quality adjustment and transferred the code to above. then got the problem
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"lat": lat,
#"lng": lon,
#"username" : #"testing"
};
[manager POST:#"http://api.geonames.org/findNearbyPostalCodesJSON" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
}
When I just enter the URL http://api.geonames.org/findNearbyPostalCodesJSON into a browser, I get the following JSON:
{"status":{"message":"Please add a username to each call in order for geonames to be able to identify the calling application and count the credits usage.","value":10}}
So I suspect that, at the very least, you need to change your 'POST' to a 'GET':
[manager GET:#"" parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
[delegate didReceiveNearByLocationResponse:responseObject];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"%#",error);
}];
Beyond that, based on the returned content, it looks like you'll need some additional application-level logic to provide user identification/authentication in order to get the actual data you're interested in, but the above change should at least trigger an invocation of the success block.
I found the solution. i even upgraded the AFNetworking to 3.0 from 2.X
and Code Changed like below. Special Changes GET
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager GET:#"http://api.geonames.org/findNearbyPostalCodesJSON" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"success!");
[delegate didReceiveNearByLocationResponse:responseObject];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error: %#", error);
}];
"Request failed: unacceptable content-type: text/html"
because the AFNetworking only support #"application/json", #"text/json", #"text/javascript"
you should add a #"text/html" type
[manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
NSMutableDictionary * parameters = [[NSMutableDictionary alloc]initWithDictionary:params];
NSURL *baseURL = [NSURL URLWithString:#"http://api.geonames.org/findNearbyPostalCodesJSON"];
AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
//insert this code
[manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager POST:#"" parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
[delegate didReceiveNearByLocationResponse:responseObject];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"%#",error);
}];
Related
I use the following code to make a GET request including a header Authorization but does not seem to work...the get request does not include the authorization token. Any ideas?
// 1 - define resource URL
NSURL *URL = [NSURL URLWithString:#"https://myurl"];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
[requestSerializer setValue:[NSString stringWithFormat:#"Bearer %#",Token] forHTTPHeaderField:#"Authorization"];
manager.requestSerializer = requestSerializer;
//3 - set a body
NSDictionary *body =#{#"email":#"a#gmail.com"};
//4 - create request
[manager GET:URL.absoluteString
parameters:body
progress:nil
//5 - response handling
success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
NSLog(#"Reply POST JSON: %#", responseObject);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error on machine token: %#", error);
}
];
From application, written in Objective (we use AFNetworking), I need to send a POST request, in the body of which - a multidimensional array of the type "key": "value"
We send request this way:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#“application/json” forHTTPHeaderField:#“Accept”];
[manager.requestSerializer setValue:#“multipart/form-data” forHTTPHeaderField:#“Content-Type”];
[manager POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
for (UIImage* image in photoArray) {
NSData *dataImage = UIImageJPEGRepresentation(image,1);
[formData appendPartWithFileData:dataImage name:randomString fileName:[NSString stringWithFormat:#“%#.jpeg”,randomString] mimeType:#“image/jpeg”];
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#“!!!!! %#“, responseObject);
if (success) {
[KVNProgress dismiss];
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#“%#“, error.localizedFailureReason);
[KVNProgress showError];
}];
And this way we form NSDictionary:
NSString*name = model.name;
NSString*lat = model.lat;
NSString*lon = model.lon;
NSDictionary* dic = [NSDictionary
dictionaryWithObjectsAndKeys:name,#"name",lat,#"lat",lon,#"lon", nil];
[addressArray addObject:dic];
Here's what we get on Objective
Here is what request the server receives
And here's what should come
How to build an object on Objective so that data [address] came to the HTTP server as indicated in the 3 picture?
i tried like this in webservices.m
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer=[AFHTTPRequestSerializer serializer];
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes =[NSSet setWithObject:#"text/html"];
[manager POST:meetingupdateurlparams parameters:meetingdictparams progress:nil
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable
responseObject)
{
NSLog(#"Complete");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull
error)
{
NSLog(#"Fail %#",error);
}];
i call this service in Viewcontroller.m
NSString *updateMeetingurl=#" url ";
NSDictionary *dictparms=#{ params };
[Servicecall meetingupdate:updateMeetingurl meetingupdatedict:dictparms];
[Servicecall setDelegate:self];
but i am getting error like this
-[AFHTTPSessionManager :parameters:progress:success:failure:] unrecognized selector sent to instance 0x792cfcb0'
*** First throw call stack:
so any one can help in this issuance...thanks in advance..
UPDATE:
I now see where you're doing wrong.
POST:meetingupdateurlparams this part.
Shouldn't you use
POST:meetingupdateurl instead?
I'm not sure which version of AFNetworking you're using.
But it seems like the method signature you're using does not exist.
Try POST:parameters:success:failure: instead of POST:parameters:progress:success:failure.
See the documentation.
I got same error.
It's a issue with Xcode,you should clean build folder(or delete your DerivedData folder,Xcode -> Preferences -> Location -> Locations -> Derived Data).Because Xcode didn't fully clean the older AFNetworking.
Try this USing Afnetworking 3
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"URL"parameters:#{#"paramter":#""} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//if you want to pass image file
if (image) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.8) name:imagename fileName:#"Image.jpg" mimeType:#"image/jpeg"];
}
}error:nil];
AFURLSessionManager *managers = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
managers.responseSerializer = [AFJSONResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask;
uploadTask = [managers
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
} else {
// here your response
}
}];
[uploadTask resume];
While accessing the Json result from API with AFNetworking Library, We will get results as in different order compare to POSTMAN results
For Example:
Postman result
1
2
3
4
5
AFNetworking response
2 3 1 5 4
Why it differs from POSTMAN? Any idea? Please give some suggestion to fix this issue. Thanks in advance.
My code sample below
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:url parameters:parameters constructingBodyWithBlock:^(id _Nonnull formData) {
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * Nonnull task, id Nullable responseObject) {
[MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow.rootViewController.view animated:YES];
NSLog(#"APi Success : %#",responseObject);
} failure:^(NSURLSessionDataTask _Nullable task, NSError _Nonnull error) {
NSLog(#" APi Failed : %#",[error description]);
}];
There are other questions with similar titles but none of them helped me. I've to send a PUT request to server in order to change the status of appointment so I've made this method -(void)appointmentStatusChangedTo:(NSString *)statusID atAppointmentID:(NSString *)appointmentID In which I'm setting the URL and Parameters as
NSString *string = [NSString stringWithFormat:#"%#/API/Appointments/3",BaseURLString];
NSDictionary *para = #{
#"AppointmentStatusId":statusID,
#"ID":appointmentID
};
Then I've made URL request as
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:#"PUT" URLString:string parameters:para error:nil];
After that I'm setting the header for an authorization token as
NSString *token = [NSString stringWithFormat:#"Bearer %#",[[NSUserDefaults standardUserDefaults] objectForKey:#"userToken"]];
[req setValue:token forHTTPHeaderField:#"Authorization"];
So finally I'm calling it as
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error){
if (!error) {
if (response) {
NSLog(#"Respose Object: %#",responseObject);
[self.patientsAppointmentsTableView reloadData];
}
}
else {
// NSLog(#"Error: %#, %#, %#", error, response, responseObject);
NSLog(#"Error: %#", error.localizedDescription);
}
}] resume];
Now it is successfully sending the data to the server but as a response I'm getting
Error: The data couldn’t be read because it isn’t in the correct
format.
I am not sure what the response might look like at the moment as I'm not in contact with backend guy. But as far as I remember it was just a simple 1. SO kindly tell me how to handle any type of response using AFNetworking 3.0 or any change in my code.
try to use below code:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setStringEncoding:NSUTF8StringEncoding];
manager.requestSerializer=serializer;
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
Try following code using Afnetworking 3.0
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:url parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"%#",responseObject);
self.responseHandlers(YES,responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
self.responseHandlers(NO,nil);
}];