maxisme
maxisme

Reputation: 4245

How to use AFNetworking to create JSON array

I am currently trying to create a JSON array like I do here like this:

NSURL *url = [NSURL URLWithString:currentJSON];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
if (jsonData) {

    result = [NSJSONSerialization JSONObjectWithData:jsonData
                                             options:NSJSONReadingMutableContainers
                                               error:&error];
}

Which works fine. Apart from I want it to time out if the internet connection is not great.

So I then wen to AFNetworking where I wrote code like this:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:currentJSON parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) 
{
    NSError *error = nil;
    result = [NSJSONSerialization JSONObjectWithData:responseObject
                                             options:NSJSONReadingMutableContainers 
                                               error:&error];
    [[NSUserDefaults standardUserDefaults] setObject:result forKey:@"All"];
    [[NSUserDefaults standardUserDefaults] synchronize];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) 
{
    result = [[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:@"All"];
}

But this method always runs to a failure How come? What am I doing wrong?

Upvotes: 1

Views: 319

Answers (2)

JaanusSiim
JaanusSiim

Reputation: 2192

Check that server is sending JSON using correct content type 'application/json'. AFNetowrking checks this out of the box and if receives something else (for example 'text/html'), failure block will be called.

Also AFNetworking does JSON to object parsing out of the box. 'id responseObject' is already the result of '[NSJSONSerialization JSONObjectWithData]'.

If you can't change content type sent by server, you could add that content type to accepted types using following snippet

NSMutableSet *accepted = [NSMutableSet set];
[accepted addObject:@"text/html"];
[accepted addObject:@"application/json"];
manager.responseSerializer.acceptableContentTypes = accepted;

Upvotes: 2

jithinroy
jithinroy

Reputation: 1885

Try this :

  NSURL *url = [NSURL URLWithString:string];
  NSURLRequest *request = [NSURLRequest requestWithURL:url];


    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {


        result = (NSDictionary *)responseObject;


    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {


    }];


    [operation start];

Upvotes: 0

Related Questions