How to get JSON results as particular order in ios? - ios

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

Related

Objective-C: How to send a post request with a multidimensional array of type key value

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?

GZip my AFNetworking posts to my server

My application posts large amounts of data, Orders with Order Items - sometimes 1000's, and I want to send it GZipped because my users also have crappy connections most of the time.
How can I accomplish this with AFnetworking?
I am currently using AFHTTPSessionManager to perform my posts.
You can use AFgzipRequestSerializer.
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFgzipRequestSerializer serializerWithSerializer:[AFJSONRequestSerializer serializer]];
[manager POST:#"http://example.com/"
parameters:#{#"foo": #"bar"}
success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"%#", responseObject);
}
failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"[Error] %#", error);
}];
See details here.

app crashing using afhttpsessionmanager 3.0

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

AFNetworking send image as file not as data

Hi server that I'm sending data is expecting image as file(jpg) not as NSData. This code works, but server can't recognize NSData as image. Any thoughts how to solve this?
+ (void)signupWithParameters:(NSDictionary *)parameters
andUserHaveImage:(BOOL)userHaveImage
andImage:(NSData *)image
successBlock:(void (^) (NSDictionary *response))successHandler
errorBlock:(void (^) (NSDictionary *error))errorHandler
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"multipart/form­data" forHTTPHeaderField:#"Content-Type"];
[manager POST:[NSString stringWithFormat:#"%#/api/1.0/customer/sign-up", DEFAULT_URL] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
if (userHaveImage == YES) {
//
[formData appendPartWithFileData:image name:#"img_profile" fileName:#"profileImage.jpg" mimeType:#"image/jpg"];
[formData appendPartWithFormData:image name:#"img_profile"];
}
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
successHandler(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
errorHandler(#{});
}];
}
Solved by converting image to UTF8 string and sending it in that format.

AFNetworking Response Error only for specific URL

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

Resources