AFNetworking 2.0 - ios

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.

Related

iOS: AFHTTPSession manager response data

in my app I'm using the new AFN 3.0 and I have
AFHTTPSessionManager *manager
instead of
AFHTTPRequestOperation *operation
my problem is that before I was able to get some data from RequestOperation as:
NSURL *url = operation.request.URL;
//or
NSNumber statusCode = operation.response.statusCode;
//or
NSData *responseData = operation.responseData;
and how can I get this elements with AFHTTPSessionManager?
thanks
in v2 you were getting AFHTTPRequestOperation for the request
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);
}];
But in the v3 you will get NSURLSessionTask
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:#"http://example.com/resources.json" parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
So based on that you can get the details the from the NSURLSessionTask like the currentRequest , response etc
For more changes and details, you can refer to the migration guide of AFNetworking
AFNetworking Migration Guide
For NSURLSessionTask Reference : NSURLSessionTask

How to make an HTTP request with AFNetorking and NSURLRequest?

I am trying to use AFHTTPRequestOperationManager to make an HTTP request. I need to use AFHTTPRequestOperationManager because I want to be able to cancel all operations if necessary. I can't get this working for some reason. The completion blocks aren't called. Am I missing something?
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://twitter.com/%#", username]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:#"MyUserAgent (iPhone; iOS 7.0.2; gzip)" forHTTPHeaderField:#"User-Agent"];
[request setHTTPMethod:#"GET"];
[self.manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *html = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
if ([html containsString:#"var h = decodeURI(l.hash.substr(1)).toLowerCase();"]) {
completion(YES, nil);
} else {
completion(NO, nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
completion(NO, error);
}];
This is working code, you need to use GET or POST method there.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"email":emailfield.text};
[manager GET:#"http://example.com/api" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
While everyone else is right -- you should be using the modern AFNetworking constructs instead of the legacy features -- there is a quick way to get done what you're looking to get done.
By the looks of it, the method - (??? *) HTTPRequestOperationWithRequest:success:failure likely returns an AFHTTPRequestOperation. If I'm correct, you just need to actually start the operation. See below for your code, corrected.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://twitter.com/%#", username]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:#"MyUserAgent (iPhone; iOS 7.0.2; gzip)" forHTTPHeaderField:#"User-Agent"];
[request setHTTPMethod:#"GET"];
AFHTTPRequestOperation *op = [self.manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *html = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
if ([html containsString:#"var h = decodeURI(l.hash.substr(1)).toLowerCase();"]) {
completion(YES, nil);
} else {
completion(NO, nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
completion(NO, error);
}];
[op start];
HTTPRequestOperationWithRequest method returns AFHTTPRequestOperation. You have to add it to some operation queue to start it. For example
AFHTTPRequestOperation *operation = [self.manager HTTPRequestOperationWithRequest:request .........
[[NSOperationQueue currentQueue] addOperation:operation];
You can use AFHTTPSessionManager which is a little better than AFHTTPRequestOperationManager and cancel requests using method cancel of NSURLSessionDataTask. You can find some code examples here - AFNetworking 2.0 cancel specific task
Check this will work
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", nil];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];

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.

How can I log AFHTTPRequestOperationManager request?

I'm having some trouble with RESTfull web service and I'm trying to see my request as a text using NSLog. I tried this:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
...
[manager POST:urlString parameters:mutableParameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
...
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Response: %#", [operation description]) ;
if (block) {
block(error);
}
NSLog(#"-------------------------------");
NSLog(#"Request: %#", manager.requestSerializer.debugDescription);
NSLog(#"-------------------------------");
NSLog(#"Request: %#", manager.requestSerializer.description);
NSLog(#"-------------------------------");
NSLog(#"Request: %#", operation.request.HTTPBodyStream);
NSLog(#"-------------------------------");
NSLog(#"Request: %#", operation.request);
NSLog(#"-------------------------------");
NSLog(#"Error: %#", error);
NSLog(#"-------------------------------");
}];
Is there any way to NSLog the request from AFHTTPRequestOperationManager (AFNetworking 2) ?
Have a look to the POST method:
[manager POST:urlString parameters:mutableParameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
You have a AFHTTPRequestOperation *operation and an id responseObject in the success block.
The best thing that you can do is to put a:
NSLog(#"AFHttpRequestOperation %#", operation);
and set there a breakpoint so you can inspect what's happening there:
What do you want to see about the operation's request?
Not exactly logging but this answer explains how to convert NSURLRequest to NSString

AFNetworking 2.0 JSON Parse [closed]

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

Resources