AFNetworking 2.0 JSON Parse [closed] - ios

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Here is my code.
(void)performHttpRequestWithURL :(NSString *)urlString :(NSMutableArray *)resultArray completion:(void (^)(NSArray *results, NSError *error))completion
{
NSURL *myUrl = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:myUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"请求完成");
NSArray *arr;
arr = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingAllowFragments error:NULL];
[resultArray addObjectsFromArray:arr];
if (completion) {
completion(resultArray, nil);
}
}failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(#"请求失败: %#", error);
if (completion) {
completion(nil, error);
}
}];
[operation start];
}
I can only use apple json parse, I don't know how to use AFNetworking json parse itself.
I didn't find AFJsonrequestOperaton in AFNetworking 2.0.ask for help, thank you.

For AFNetworking 2.0 below sample code works:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"UserId": #"24",#"Name":#"Robin"};
NSLog(#"%#",parameters);
parameters = nil; // set to nil for the example to work else you can pass data as usual
// if you want to sent parameters you can use above code
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:#"http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
}failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];

No need to do it manually, just set the response serializer to JSON like this:
....
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
and now inside your block, responseObject should be the deserialised object (NSDictionary or NSArray depending on your root JSON object from the response)
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Hooray, we got %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(#"Oops, something went wrong: %#", [error localizedDescription]);
}];
[operation start];

Related

AFNetworking 2.0

I'm a newbie in iOS development and I'm trying to figure out how to send GET request with AFNetworking.
I used the example provided in Tutorial on Using AFNetworking 2.0 and placed it in main expecting a error:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://samwize.com/api/poos/"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
...and I've got nothing, so I tried to point to the webservice that returns a valid JSON and also got nothing. Why none of blocks (success or failure) are executed?
Your code does not execute blocks (success or failure) beacause somthing went wrong.
but if you use try catch block then it will go into catch block try once.
code:
try {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://samwize.com/api/poos/"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}#catch (NSException *exception) {
**// you will get error here**
}
Use following function and just send your URL in Argument
- (void)callWebservice : (NSString *)strURL{
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL urlWithEncoding:strURL]];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient setDefaultHeader:#"Accept" value:#"application/json"];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"GET" path:#"" parameters:nil];
[request setTimeoutInterval:180];
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:#"text/html"]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"Success");
} failure:^ (NSURLRequest *request, NSURLResponse *response, NSError *error, id json){
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"Failure");
}];
[GlobalManager setOperationInstance:operation];
[operation start];
}
It was strange, I just created another project (iOS instead of OSX) and called the same code from the IBAction and it worked easily. In Podfile I specified a new version of AFNetworking (2.5 instead of 2.4). I don't know if this is relevant.
Thank you everyone for trying to help me.
Try following code to do that.
#try {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:stringURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject){
NSLog(#"JSON: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
#catch (NSException *exception) {
NSLog(#"Exception - %#", [exception debugDescription]);
}
#finally {
}
And make sure you have a valid JSON.

responseObject is not JSON but NSInLineData for AFHTTPRequestOperationManager

Following code is to submit images through an operationQueue. The requests are all fired one by one correctly, the server response contains the image file name which client needs to get hold of. The problem is that the reponseObject for the success/failure block is not expected parsed JSON but type of NSInLineData shown in debugger. Now I suspect the code to construct the operation from the NSMutableURLRequest caused the issue. Please help.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSMutableURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:#"POST"
URLString:podURLString parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSError *error;
BOOL success =[formData appendPartWithFileURL:imgURL name:#"images" fileName:img.path
mimeType:#"image/jpg" error:nil];
if (!success)
NSLog(#"appendPartWithFileURL error: %#", error);} error:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Image Success: %#", [responseObject description]);
NSString *imagePath = [response objectForKey:#"imageFileName"];
[self.delegate networkManager:self didSubmitDeliveryImageForImageID:imagePath];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Image Error: %#", error);
NSLog(#"image error: %#", [operation.responseObject description]);
NSString *imageFilePath = [operation.responseObject objectForKey:#"imageFileName"];
[self.delegate networkManager:self didFailSubmitDeliveryImageForImageID:imageFilePath];
}];
[manager.operationQueue addOperation:operation];
When you get the response as NSInLineData. It's good to go now. You can write below single line of code to get NSDictionary if it supports json format.
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObjec options:0 error:nil];
Just add this line of code before your AFHTTPRequestOperation block
**operation.responseSerializer = [AFJSONResponseSerializer serializer];**

AFNetworking 2 POST with Authentication challenge

Im using AFNetworking 2, with AFHTTPRequestOperation I can use for my Get
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"GET"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.securityPolicy = securityPolicy;
[operation setWillSendRequestForAuthenticationChallengeBlock:
^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge) {
//the certificate
}
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
DLog(#"operation :: %#", responseObject);
NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
DLog(#"operation :: %#", result);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DLog(#"operation error :: %#", error);
}];
[operation start];
But now i need to use POST, with parameters,
I have problems finding how to set parameters on
AFHTTPRequestOperation
or finding how to set challenge block for
AFHTTPRequestOperationManager
how to have a POST with parameters and challenge block?
cheers
I am working now on the POST request. So far I've came up with the following code while trying to send an NSDictionary with POST method:
NSDictionary*packet = [NSDictionary dictionaryWithObjectsAndKeys: ......
[manager POST:path
parameters:packet
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
if ([responseObject isKindOfClass:[NSDictionary class]])
[self parseReceivedDataPacket:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Actually it works for me, apart from getting an "unacceptable content-type: text/html" when sending this data. But it gets received.
Hope this was useful.

Afnetworking 2 with parameters

i am really new to IOS developments..i just want to get some JSON response from my web service. when i searched about it i found AFnetworking is good for that. so i downloaded it and did a sample application. but i need to pass some parameters to the service . my service takes two parameters [username and password]. my url like this
http://myweb.mobile.com/WebServices/AppointmentService.asmx/GetValidUser
can anyone please give me some code sample how to pass my parameters to this service to get json response ?
i have tried this code.. but it wont take parameters.. some people telling about AFHTTPClient.. but im using AFN 2.0.. there is no class call AFHTTPCLient here .. i'm so conduced here....please help me
NSURL *url = [NSURL URLWithString:#"https://maps.googleapis.com/maps/api/place/textsearch/json?query=restuarants+in+sydney&sensor=false&key=AIzaSyDn9a-EvJ875yMxZeINmUP7CwbO9YT1w2s"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// 3
self.googlePlaces = [responseObject objectForKey:#"results"];
[self.tableView reloadData];
// NSLog(#"JSON RESULT %#", responseObject);
self.weather = (NSDictionary *)responseObject;
self.title = #"JSON Retrieved";
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
EDIT :
i have sloved my problem using below code segments...
NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:#"47", #"caregiverPersonId", nil];
AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager setSecurityPolicy:policy];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
[operationManager POST:#"your full url goes here"
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", [responseObject description]);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error description]);
}
];
Try this
-(void)login
{
NSMutableDictionary *dict=[[NSMutableDictionary alloc]initWithCapacity:3];
[dict setObject:_usernameTextField.text forKey:#"userName"];
[dict setObject:_passwordTextField.text forKey:#"password"];
AFHTTPClient *client=[[AFHTTPClient alloc]initWithBaseURL:[NSURL URLWithString:#""]];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefaultHeader:#"Accept" value:#"application/json"];
client.parameterEncoding = AFJSONParameterEncoding;
[client postPath:#"GetValidUser" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *op=(NSDictionary *)responseObject;
NSLog(#"%#",op);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:MESSAGE_EN message:#"Unable to login. Please try again." delegate:self cancelButtonTitle:OK_EN otherButtonTitles:nil, nil];
[alert show];
NSLog(#"error.localizedDescription %#",error.localizedDescription);
}];
}
Note : Please do fill the fields with proper values and try.
dict is the Input postdata
I got this one from somewhere in SO question. See this:
- (IBAction)loginButtonPressed {
NSURL *baseURL = [NSURL URLWithString:#"http://myweb.mobile.com/WebServices/AppointmentService.asmx"];
//build normal NSMutableURLRequest objects
//make sure to setHTTPMethod to "POST".
//from https://github.com/AFNetworking/AFNetworking
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[httpClient defaultValueForHeader:#"Accept"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
[usernameTextField text], kUsernameField,
[passwordTextField text], kPasswordField,
nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"http://myweb.mobile.com/WebServices/AppointmentService.asmx/GetValidUser" parameters:params];
//Add your request object to an AFHTTPRequestOperation
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc]
initWithRequest:request] autorelease];
//"Why don't I get JSON / XML / Property List in my HTTP client callbacks?"
//see: https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ
//mattt's suggestion http://stackoverflow.com/a/9931815/1004227 -
//-still didn't prevent me from receiving plist data
//[httpClient registerHTTPOperationClass:
// [AFPropertyListParameterEncoding class]];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation *operation,
id responseObject) {
NSString *response = [operation responseString];
NSLog(#"response: [%#]",response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", [operation error]);
}];
//call start on your request operation
[operation start];
[httpClient release];
}
Hope this helps .. :)
EDIT
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:URLString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:[email dataUsingEncoding:NSUTF8StringEncoding]
name:#"email"];
[formData appendPartWithFormData:[pass dataUsingEncoding:NSUTF8StringEncoding]
name:#"password"];
// etc.
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Use below code
NSDictionary *paramDictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"first_Object",#"first_Key",#"second_Object",#"second_Key" nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"YOUR_URL_STRING" parameters:paramDictionary success:^(AFHTTPRequestOperation *operation, id responseObject) {Success responce} failure:^(AFHTTPRequestOperation *operation, NSError *error) {failure responce}];
if you want you can set
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.securityPolicy.allowInvalidCertificates = YES;

AFNetworking 2.0 - mutable json

My code currently looks like this
NSURL *URL = [NSURL URLWithString:URLForSend];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"%#", responseObject);
[BoxJsonDataHelper gotNewJson:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Request Failure Because %#",[error userInfo]);
}];
[operation start];
But when trying to edit dictionaries in object received, I get an error about using methods that belongs to a mutable dictionary rather than a dictionary.
How do I make AFNetworking use nested mutable objects instead?
You tell the AFJSONResponseSerializer that it needs to return mutable containers:
operation.responseSerializer =
[AFJSONResponseSerializer serializerWithReadingOptions: NSJSONReadingMutableContainers]
It is all very well documented: http://cocoadocs.org/docsets/AFNetworking/2.0.0/

Resources