AFNetworking - A delightful networking framework for iOS, OS X, watchOS, and tvOS. GitHub - AFNetworking/AFNetworking: A delightful networking framework for iOS, OS X, watchOS, and tvOS. afnetworking - a delightful networking framework for ios, os x, watchos, and tvos.

AFNetworking Post Request

I'm a newbie in obj-c and have been using asihttp for some of my projects. When doing a post request in asihttp its done this way.

    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setPostValue:height forKey:@"user[height]"];
    [request setPostValue:weight forKey:@"user[weight]"];
    [request setDelegate:self];
    [request startAsynchronous];

How would go about doing this is AFNetworking with a code example ?
I already got the get Json getrequest working in AFNetworking but this post request is giving me some problems. Thanks for help in advance.

Source: (StackOverflow)

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

I'm trying out the new version 2.0 of AFNetworking and I'm getting the error above. Any idea why this is happening? Here's my code:

    NSURL *URL = [NSURL URLWithString:kJSONlink];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    op.responseSerializer = [AFJSONResponseSerializer serializer];
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    [[NSOperationQueue mainQueue] addOperation:op];

Any ideas will be appreciated. I'm also using Xcode 5.0 if that helps. Thanks!

Also, here's the error message:

Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0xda2e670 {NSErrorFailingURLKey=kJSONlink, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0xda35180> { URL: kJSONlink } { status code: 200, headers {
    Connection = "Keep-Alive";
    "Content-Encoding" = gzip;
    "Content-Length" = 2898;
    "Content-Type" = "text/html";
    Date = "Tue, 01 Oct 2013 10:59:45 GMT";
    "Keep-Alive" = "timeout=5, max=100";
    Server = Apache;
    Vary = "Accept-Encoding";
} }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}

I just hid the JSON using kJSONlink. This should return a JSON.

Source: (StackOverflow)

NSURLSession/NSURLConnection HTTP load failed on iOS 9

Tried to run my existing app on iOS9 but getting failure while using AFURLSessionManager.

__block NSURLSessionDataTask *task = [self.sessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
    if (error) {

    } else {


[task resume];

I get the following error:

Error Domain=NSURLErrorDomain Code=-999 "cancelled.

Also getting following logs:

 NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9824
 CFNetwork SSLHandshake failed (-9824)

Update: I have added multiple updates to my solution: NSURLSession/NSURLConnection HTTP load failed on iOS 9

Source: (StackOverflow)

What major ASIHTTPRequest features is AFNetworking missing?

With work having recently stopped on ASIHTTPRequest, it seems like attention is shifting to AFNetworking.

However, I've not yet found a good comparison of the features of the two libraries, so I don't know what I might lose if/when I switch over.

Major differences I've spotted so far are:

  1. AFNetworking has a much smaller code size (which is good)
  2. AFNetworking is being rapidly improved (so it may not yet be mature, may not have a stable API yet?)
  3. Both seem to have caching, though I've seen hints that because AFNetworking uses NSURLConnection it won't cache objects over 50K
  4. ASIHTTPRequest has very good support for manual & automatic (PAC) http proxies; I can't find any information on what level of support AFNetworking has for proxies
  5. AFNetworking requires iOS 4+, whereas ASIHTTPRequest works right back to iOS 2 (not really an issue for me, but it is an issue for some people)
  6. AFNetworking doesn't (yet) have a built in persistent cache, but there's a persistent cache which has a pending pull request: https://github.com/gowalla/AFNetworking/pull/25

Has anyone seen any good comparisons of the two libraries or any documented experiences of switching from one to the other?

Source: (StackOverflow)

is there an easy way to get the http status code in the failure block from AFHTTPClient?

I see that there is a list of accepted http status codes that I can modify, but I think it would be cleaner if I can get the http status code in the failure block ..

Ok, found the answer with the operation object

failure:^(AFHTTPRequestOperation *operation, NSError *error){ 
        NSLog(@"error code %d",[operation.response statusCode]);

Source: (StackOverflow)

AFNetworking 2.0 add headers to GET request

I've just started using AFNetworking 2.0 and I was wondering how I put in headers into a HTTP Get request. The documentation sets up a GET like this:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);

But since we're not handling NSURLRequests I'm not sure how to set HTTP Headers.

Any help would be appreciated.

Source: (StackOverflow)

How to set a timeout with AFNetworking

My project is using AFNetworking.


How do I dial down the timeout? Atm with no internet connection the fail block isn't triggered for what feels like about 2 mins. Waay to long....

Source: (StackOverflow)

List saved files in iOS documents directory in a UITableView?

I have set up the following code to save a file to the documents directory:

NSLog(@"Saving File...");

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.reddexuk.com/logo.png"]];
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"logo.png"];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Successfully downloaded file to %@", path);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);

[operation start];

However, I wish to add each file to a UITableView when it is successfully saved. When the file in the UITableView is tapped, I'd like a UIWebView to navigate to that file (all offline).

Also - how can I just get the filename and ending such as "logo.png" instead of http://www.reddexuk.com/logo.png?

How can I do this?

Source: (StackOverflow)

How to manage sessions with AFNetworking?

As the title implies, I am using AFNetworking in an iOS project in which the application talks to a server. When the user signs in, the server responds by sending back a success flag and the response headers contain the session ID.

I am wondering if AFNetworking automatically sends the session ID with every subsequent request or should I take care of this myself in some way?

For your information, I have no control over the back-end in terms of how requests are authenticated. I am only building a client that talks to the server.

Source: (StackOverflow)

How to batch request with AFNetworking 2?

So I'm rewriting an app for iOS 7 with AFNetworking 2.0 and I'm running into the issue of sending a batch of requests at once and tracking their progress. In the old AFNetworking there was the enqueueBatchOfHTTPRequestOperations:progressBlock:completionBlock: method on AFHTTPClient, this is clearly refactored out and I'm a bit confused on how to enqueue multiple requests.

I have created a subclass of AFHTTPSessionManager and I'm using the POST:... and GET:... methods to communicate with the server. But I can't find anything in the code and/or docs to enqueue multiple requests at once like with the old AFHTTPClient.

The only thing I can find is the undocumented batchOfRequestOperations:progressBlock:completionBlock: method on AFURLConnectionOperation, but that looks like the iOS 6 way of doing this.

Clearly I'm missing something in the new NSURLSession concept that I should use to batch requests or looking over a new AFNetworking feature. Hope someone can help me on the right track here!

tl;dr: How can I send a batch of requests with my AFHTTPSessionManager subclass?

Source: (StackOverflow)

How to download a file and save it to the documents directory with AFNetworking?

I am using the AFNetworking library. I can't figure out how to download a file and save it to the documents directory.

Source: (StackOverflow)

cocoapods - use specific pod version

I am using cocoapods for an OS X app. I have compilation errors with AFNetworking (current version, 1.2.1) and saw, that these didn't exist in the previous version (1.2.0). I did some research but did not find a possibility to define, that cocoapods only should use version 1.2.0 instead of 1.2.1. Is this possible or do I have to wait until there is a new version of that library?

Source: (StackOverflow)

how to use Alamofire with custom headers

I am just starting to take a look at Mattt's wonderful new Alamofire swift networking library and am not quite sure how one would use it with custom headers.

The code i am trying to convert from AFNetworking to Alamofire is this:

let request = NSMutableURLRequest(URL: url)
request.setValue(authorizationToken, forHTTPHeaderField:"Authorization")

Source: (StackOverflow)

Cannot install Alamofire in new Xcode Project. "No Such module Alamofire"

I follow the instructions to the T. Fresh install of all, yet getting the error:

"No Such module Alamofire"

Directions here:

In the meantime, you can simply add Alamofire as a git submodule, drag the Alamofire.xcodeproj file into your Xcode project, and add the framework product as a dependency for your application target.

And my screenshots

enter image description here

enter image description here

Source: (StackOverflow)

AFNetworking and background transfers

I'm a bit confuse of how to take advantage of the new iOS 7 NSURLSession background transfers features and AFNetworking (versions 2 and 3).

I saw the WWDC 705 - What’s New in Foundation Networking session, and they demonstrated background download that continues after the app terminated or even crashes.

This is done using the new API application:handleEventsForBackgroundURLSession:completionHandler: and the fact that the session's delegate will eventually get the callbacks and can complete its task.

So I'm wondering how to use it with AFNetworking (if possible) to continue downloading in background.

The problem is, AFNetworking conveniently uses block based API to do all the requests, but if the app terminated or crashes those block are also gone. So how can I complete the task?

Or maybe I'm missing something here...

Let me explain what I mean:

For example my app is a photo messaging app, lets say that I have a PhotoMessage object that represent one message and this object has properties like

  • state - describe the state of the photo download.
  • resourcePath - the path to the final downloaded photo file.

So when I get a new message from the server, I create a new PhotoMessage object, and start downloading its photo resource.

PhotoMessage *newPhotoMsg = [[PhotoMessage alloc] initWithInfoFromServer:info];
newPhotoMsg.state = kStateDownloading;

self.photoDownloadTask = [[BGSessionManager sharedManager] downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSURL *filePath = // some file url
    return filePath;
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    if (!error) {
        // update the PhotoMessage Object
        newPhotoMsg.state = kStateDownloadFinished;
        newPhotoMsg.resourcePath = filePath;

[self.photoDownloadTask resume];   

As you can see, I use the completion block to update that PhotoMessage object according to the response I get.

How can I accomplish that with a background transfer? This completion block won't be called and as a result, I can't update the newPhotoMsg.

Source: (StackOverflow)