AFNetworking
Post Request
iOS Development
Networking Library
API Integration

AFNetworking Post Request

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

AFNetworking is still common in older Objective-C iOS and macOS projects even though newer apps often use URLSession directly. A solid POST request with AFNetworking comes down to matching the server's expected body format, configuring serializers deliberately, and handling failure details instead of treating every network error the same way.

Basic POST Request with AFHTTPSessionManager

The usual entry point is AFHTTPSessionManager. For form-style API input, the default request serializer is often enough.

objc
1#import <AFNetworking/AFNetworking.h>
2
3AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
4
5NSDictionary *parameters = @{
6    @"username": @"alice",
7    @"email": @"[email protected]"
8};
9
10[manager POST:@"https://api.example.com/register"
11   parameters:parameters
12      headers:nil
13     progress:nil
14      success:^(NSURLSessionDataTask *task, id responseObject) {
15          NSLog(@"Success: %@", responseObject);
16      }
17      failure:^(NSURLSessionDataTask *task, NSError *error) {
18          NSLog(@"Failed: %@", error.localizedDescription);
19      }];

With the default serializer, AFNetworking sends parameters as application/x-www-form-urlencoded. That is correct for many older APIs and login endpoints, but it is wrong for APIs that expect JSON.

Sending JSON in the Request Body

If the server expects JSON, switch the request serializer before sending the request. That changes both the body format and the Content-Type header.

objc
1#import <AFNetworking/AFNetworking.h>
2
3AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
4manager.requestSerializer = [AFJSONRequestSerializer serializer];
5manager.responseSerializer = [AFJSONResponseSerializer serializer];
6
7NSDictionary *payload = @{
8    @"title": @"New Post",
9    @"published": @YES
10};
11
12[manager POST:@"https://api.example.com/posts"
13   parameters:payload
14      headers:@{ @"Authorization": @"Bearer YOUR_TOKEN" }
15     progress:nil
16      success:^(NSURLSessionDataTask *task, id responseObject) {
17          NSLog(@"Created: %@", responseObject);
18      }
19      failure:^(NSURLSessionDataTask *task, NSError *error) {
20          NSLog(@"POST failed: %@", error.localizedDescription);
21      }];

This is one of the most common AFNetworking mistakes: the code looks correct, but the body format does not match what the server expects. That usually turns into 400 or 415 responses.

Inspecting Status Codes and Error Context

A generic error log is not enough when debugging real API problems. In failure blocks, it is often useful to inspect the HTTP response object as well.

objc
1failure:^(NSURLSessionDataTask *task, NSError *error) {
2    NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
3    NSLog(@"Status: %ld", (long)response.statusCode);
4    NSLog(@"Error: %@", error.localizedDescription);
5}

This helps you separate transport failures from application-level failures such as 401, 403, or 422. It also helps when the backend returns a structured error payload but the top-level message alone is too vague to be useful.

Multipart POST for File Uploads

If the request includes an image or document, use AFNetworking's multipart API instead of trying to build the body manually.

objc
1#import <AFNetworking/AFNetworking.h>
2
3AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
4UIImage *image = [UIImage imageNamed:@"avatar"];
5NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
6
7[manager POST:@"https://api.example.com/upload"
8   parameters:@{ @"description": @"profile photo" }
9      headers:nil
10constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
11    [formData appendPartWithFileData:imageData
12                                name:@"photo"
13                            fileName:@"avatar.jpg"
14                            mimeType:@"image/jpeg"];
15}
16     progress:^(NSProgress *uploadProgress) {
17         NSLog(@"Progress: %.0f%%", uploadProgress.fractionCompleted * 100.0);
18     }
19      success:^(NSURLSessionDataTask *task, id responseObject) {
20          NSLog(@"Upload complete: %@", responseObject);
21      }
22      failure:^(NSURLSessionDataTask *task, NSError *error) {
23          NSLog(@"Upload failed: %@", error.localizedDescription);
24      }];

The multipart helper handles boundaries and file metadata correctly, which is exactly the sort of boilerplate you do not want to hand-roll.

Headers and Shared Configuration

Authentication and content negotiation usually belong in headers. If the same token is needed across many requests, set it on the serializer once.

objc
1[manager.requestSerializer setValue:@"Bearer YOUR_TOKEN"
2                 forHTTPHeaderField:@"Authorization"];
3[manager.requestSerializer setValue:@"application/json"
4                 forHTTPHeaderField:@"Accept"];

If only one request needs a special header, pass it in the headers: argument instead. That keeps per-request behavior explicit and avoids surprising side effects on unrelated calls.

Common Pitfalls

  • Using the default form serializer when the backend expects JSON.
  • Ignoring the HTTP status code and logging only NSError.localizedDescription.
  • Forgetting to widen acceptableContentTypes when the backend returns JSON with an unexpected content type.
  • Uploading files through a normal parameter dictionary instead of the multipart API.
  • Capturing self strongly inside success and failure blocks in view controllers that retain the manager.

Summary

  • 'AFHTTPSessionManager is the standard AFNetworking entry point for POST requests.'
  • Match the request serializer to the server's expected body format.
  • Inspect status codes and response details when handling failures.
  • Use multipart helpers for file uploads instead of building the body manually.
  • Treat headers, serializers, and error handling as part of the API contract, not optional extras.

Course illustration
Course illustration

All Rights Reserved.