Properly formatting parameters for POST message in AFNetworking? - objective-c

So I'm trying to use AFNetworking to essentially pull down the same information that I get with the following cURL request in Terminal:
curl --data 'method=my-service.search&document_type=x&keywords=y' http://mywebsite.com/services/json/my-service.search
If I type that into Terminal, I get JSON back. Now I want to essentially do the same thing (download the JSON) so I can parse it in Xcode.
I've tried asking this question in different terms here, but I think I'm narrowing in on why I am getting issues — I'm not properly formatting the parameters.
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:#"document_type", #"keywords", nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
So, how do I perform this task with the right formatting to return proper results? Do I set the urlString to http://mywebsite.com/services/json/my-service.search, should 'method=my-service.search' enter parameters in any form? How do I define the two parameters that I have listed (e.g. set document_type to podcast)?
Sorry for the flurry of questions. I'm just frustrating that this web service works so well in Terminal but I can't apply it to Xcode with the knowledge that I currently have.
Thanks!

I think you have created wrong parameters dictionary, the fowolling code
NSDictionary *parameters = #{"document_type":value, #"keywords":value};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:urlString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
//SUCCESS BLOCK
} failure:^(NSURLSessionDataTask *task, NSError *error) {
//FAILURE BLOCK
}];

Related

Post method using Afnetworking in Objective-C

How to write the code to sending POST method for the below JSON format using Afnetworking.
{
Media
{
Photo : image.jpg,
UserId : 2
},
Personal
{
Name : aaa,
Age : 30
},
Education
{
College : xxx,
Course : yyy
},
}
Obviously that's not quite the actual format, but we can guess what you might have meant. Clearly, if those numeric values (the user id and age) are expected as strings, then quote then, but hopefully it illustrates what the Objective-C representation of that dictionary might look like:
NSDictionary *parameters = #{#"Media": #{#"Photo": #"image.jpg", #"UserId": #2}, #"Personal": #{#"Name": #"aaa", #"Age": #30}, #"Education": #{#"College": #"xxx", #"Course": #"yyy" }};
Then you can post it as JSON like so:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:#"https://yoururl.com" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"responseObject = %#", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error %#", error);
}];
And if your server doesn't support HTTPS, but only HTTP, then you might have to alter your Info.plist's "App Transport Security Settings" to "Allow Arbitrary Loads".
Firstly make a dictionary of params you want to send
NSDictionary *params = #{
#"contact_no":#"9898989898",
#"password":#"••••••••••"
};
Then write the following code
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
operationManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript", #"text/html", nil];
[operationManager POST:urlString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
NSLog(#"%#",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error){
if (failure)
NSLog(#"%#",error.localizedDescription);
}];
You can neglect the line in which i am setting the acceptableContentTypes.
Hope this will help.

Afnetworking wrong block is returned

I am using afnetworking and AFHTTPRequestOperationManager,
I have a singleton class, which contains all my api call. However, when I have concurrent api call, wrong data is being returned. API call A is returning API call B response?
CHAFHTTPRequestOperationManager is a subclass of AFHTTPRequestOperationManager
Anyone experience the same problem, what do I need to do to solve this:
NSString *path = [NSString stringWithFormat:#"users/%#/profile_photo", userName];
CHAFHTTPRequestOperationManager *manager = [CHAFHTTPRequestOperationManager sharedManagerObj];
[manager GET:path
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}
];
}

Convert CURL Request to AFNetworking Request

I would like to use the following curl request in AFNetworking 2.0. Any ideas how I would go about this?
curl --request POST -d "login=remitest&password=password&api_version=3" https://8tracks.com/sessions.json
Try this:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
#"remitest", #"login",
#"password", #"password",
#3, #"api_version",
nil];
[manager POST:#"https://8tracks.com/sessions.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
// do your stuff
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// fail cases
}];
Hope it helps

Khan Academy Topic Tree Not Working -Objective C and AFNetworking 2.0

I am attempting to call the khan academy api inside my iOS app. I am using the AFNetworking class to make the api call. Here is my code:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager GET:#"http://www.khanacademy.org//api/v1/topictree" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
[activityIndicator stopAnimating];
NSLog(#"no error");
for (NSString *key in [responseObject allKeys]) {
NSLog(#"%#", [responseObject objectForKey:key]);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error");
[activityIndicator stopAnimating];
NSLog(#"Error Khan: %#", [error localizedDescription]);
}];
When I visited http://www.khanacademy.org//api/v1/topictree it was a very long list. I have a hunch it may be the JSON parsing because I am only getting one NSDictionary. As you can see in the code above I used Fast Enumeration to view the values and the keys.
If that is the correct parse. I have no idea which keys to use to get a list of all the topics. Then when a user clicks on the topic I want to show a list of the video then I need to access the video download url specific to mp4. I could do it in the playlist list method however it has been deprecated.
The goal of this is to be able to view a list if topics followed by the topics videos followed by the video description then its downloadable url in mp4 format.
I have also been getting the error Error Khan:
The operation couldn’t be completed. (Cocoa error 3840.)
But some of the time it works.
All help is appreciated.
Thanks in advance,
Joel
that error code means JSON text did not start with array or object and option to allow fragments not set.
because response json from server is not a valid json for retireve array or object. Try using
NSJSONReadingAllowFragments
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingAllowFragments error:&error];
NSLog(#"response: %# error: %#", json, error);

Using AFHTTPRequestOperationManager at a later time

I'm using AFNetworking for my app.
I want to create a queue mechanism with different priority for each HTTP request.
For that - I need to be able to create an HTTP Request using AFNetowrking but use it later.
The example for creating an HTTP request is:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
This code will send the request immediately.
How can I just create the request (method, parameters, url), but use it at a later time?
Check operationQueue of AFHTTPRequestOperationManager. If you suspend it before adding request, it will not run until you resume operation queue. For example:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.operationQueue setSuspended:YES];
Turns out you need to create an AFHTTPRequestOperation instead of a manager.
Full article here:
http://samwize.com/2012/10/25/simple-get-post-afnetworking/