chevron-up bell reply instagram twitter2 feed3 finder search-25px-p0

AFNetworking 3 common usage template

2017-03-18

AFNetworking 3 has coming out earlier this year (2016), which supports iOS 7+, Mac OS X 10.9+, watchOS 2+, tvOS 9, and Xcode 7. This article can be appendix of its official documents.

According to its official updates:

https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-3.0-Migration-Guide

  • Some NSURLConnection APIs Have Been Removed
  • In AFNetworking 1 or 2, AFHTTPRequestOperationManager is commonly used. In AFNetworking 3, it has been depreciated and use AFHTTPSessionManager instead.

Sometimes, we need to render view under the status bar or navigation bar. In this tutorial there will be two examples on this:

Example 1: GET

// GET
NSURL *URL                      = [NSURL URLWithString:@"http://example.com/resources/123.json"];
AFHTTPSessionManager *manager   = [AFHTTPSessionManager manager];
[manager    GET:URL.absoluteString 
    parameters:nil 
    progress:nil 
    success:^(NSURLSessionTask *task, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } 
    failure:^(NSURLSessionTask *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }
];

Example 2: POST

NSURL *URL                      = [NSURL URLWithString:@"http://yoururl"];
AFHTTPSessionManager *manager   = [AFHTTPSessionManager manager];
[manager POST:URL.absoluteString
   parameters:@{    
                @"key1":@"val1",
                @"key2":@"val2"
                }
    progress:nil
    success:^(NSURLSessionTask *task, id responseObject) {
        //NSLog(@"JSON: %@", responseObject);
    }
    failure:^(NSURLSessionTask *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }
    ];
};

You can add timeout for specific scenario.

// POST
NSURL *URL                      = [NSURL URLWithString:@"http://yoururl"];
AFHTTPSessionManager *manager   = [AFHTTPSessionManager manager];
[manager.requestSerializer setTimeoutInterval:300]; // set up time out as 5 mins
[manager POST:URL.absoluteString
   parameters:@{    
                @"key1":@"val1",
                @"key2":@"val2"
                }
    progress:nil
    success:^(NSURLSessionTask *task, id responseObject) {
        //NSLog(@"JSON: %@", responseObject);
    }
    failure:^(NSURLSessionTask *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }
    ];
}

However, when you are doing a POST, you might get an error of .Unaccepted content-type., which happened in AFNetworking 2 as well. Not quite sure why it is still in AFNetworking 3 version, if anyone knows about this, please let me know. So to fix this, a quick solution is go to AFURLResponseSerialization.m, line 226, add @.text/html. for the NSSet:

Thanks for your patience.

arkilis

Make Your Comments