AFNetworking
A delightful networking framework for iOS, macOS, watchOS, and tvOS.
Top Related Projects
Elegant HTTP Networking in Swift
Promises for Swift & ObjC.
Network abstraction layer written in Swift.
Model framework for Cocoa and Cocoa Touch
Reactive Programming in Swift
The better way to deal with JSON data in Swift.
Quick Overview
AFNetworking is a popular networking library for iOS and macOS applications. It provides a powerful and elegant interface for making HTTP requests, handling responses, and managing network operations. AFNetworking is built on top of Apple's Foundation networking stack and offers additional features and conveniences for developers.
Pros
- Easy to use and well-documented API
- Supports modern networking features like JSON parsing and SSL pinning
- Highly customizable and extensible
- Large and active community support
Cons
- Dependency on third-party library may increase app size
- Learning curve for developers new to the library
- Occasional breaking changes between major versions
- May be overkill for simple networking tasks
Code Examples
- Making a GET request:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:@"https://api.example.com/data" parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"Response: %@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"Error: %@", error);
}];
- Uploading an image:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
[manager POST:@"https://api.example.com/upload" parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFileData:imageData name:@"image" fileName:@"image.jpg" mimeType:@"image/jpeg"];
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"Upload successful");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"Upload failed: %@", error);
}];
- Setting up SSL pinning:
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey];
securityPolicy.allowInvalidCertificates = NO;
securityPolicy.validatesDomainName = YES;
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
Getting Started
- Install AFNetworking using CocoaPods by adding the following to your Podfile:
pod 'AFNetworking', '~> 4.0'
-
Run
pod install
in your project directory. -
Import AFNetworking in your source files:
#import <AFNetworking/AFNetworking.h>
- Create an instance of
AFHTTPSessionManager
and start making requests:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:@"https://api.example.com/data" parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
// Handle successful response
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
// Handle error
}];
Competitor Comparisons
Elegant HTTP Networking in Swift
Pros of Alamofire
- Written in Swift, providing better performance and type safety
- More modern API design with cleaner syntax
- Better support for Swift concurrency and async/await
Cons of Alamofire
- Limited support for Objective-C projects
- Smaller community and ecosystem compared to AFNetworking
- Steeper learning curve for developers transitioning from AFNetworking
Code Comparison
AFNetworking (Objective-C):
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:@"https://api.example.com/data" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"Response: %@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"Error: %@", error);
}];
Alamofire (Swift):
AF.request("https://api.example.com/data").responseJSON { response in
switch response.result {
case .success(let value):
print("Response: \(value)")
case .failure(let error):
print("Error: \(error)")
}
}
Both libraries provide similar functionality for making HTTP requests, but Alamofire's syntax is more concise and Swift-friendly. AFNetworking remains a solid choice for Objective-C projects, while Alamofire is better suited for modern Swift development.
Promises for Swift & ObjC.
Pros of PromiseKit
- Simplifies asynchronous programming with a clean, chainable syntax
- Provides better error handling and propagation
- Supports a wide range of programming languages and platforms
Cons of PromiseKit
- Steeper learning curve for developers new to promises
- May introduce additional overhead for simple network requests
- Less focused on networking specifically compared to AFNetworking
Code Comparison
AFNetworking:
[manager GET:URLString parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"Error: %@", error);
}];
PromiseKit:
firstly {
URLSession.shared.dataTask(.promise, with: url)
}.map {
try JSONDecoder().decode(MyModel.self, from: $0.data)
}.done { object in
print(object)
}.catch { error in
print(error)
}
PromiseKit offers a more linear and readable approach to handling asynchronous operations, while AFNetworking provides a more traditional callback-based API specifically tailored for networking tasks. PromiseKit's flexibility allows it to be used for various asynchronous operations beyond networking, making it a more versatile choice for complex applications. However, AFNetworking's focus on networking may make it more suitable for projects primarily dealing with HTTP requests and responses.
Network abstraction layer written in Swift.
Pros of Moya
- Higher level of abstraction, simplifying network layer setup
- Built-in support for reactive programming (RxSwift, ReactiveSwift)
- Type-safe API definitions using enums
Cons of Moya
- Steeper learning curve for developers new to the concept
- Less flexibility for complex custom networking requirements
- Smaller community and ecosystem compared to AFNetworking
Code Comparison
AFNetworking:
AF.request("https://api.example.com/users")
.responseDecodable(of: [User].self) { response in
switch response.result {
case .success(let users):
print("Users: \(users)")
case .failure(let error):
print("Error: \(error)")
}
}
Moya:
provider.request(.getUsers) { result in
switch result {
case let .success(response):
let users = try? response.map([User].self)
print("Users: \(users ?? [])")
case let .failure(error):
print("Error: \(error)")
}
}
Both AFNetworking and Moya are popular networking libraries for iOS development. AFNetworking is a more established and lower-level framework, offering greater flexibility and control over network requests. Moya, on the other hand, provides a higher level of abstraction, making it easier to set up and maintain a clean network layer. While AFNetworking may be more suitable for complex networking requirements, Moya excels in simplifying API interactions and promoting cleaner, more maintainable code.
Model framework for Cocoa and Cocoa Touch
Pros of Mantle
- Focused on object modeling and JSON parsing
- Simplifies data transformation between JSON and model objects
- Provides type-safe model properties with automatic validation
Cons of Mantle
- Limited to data modeling and doesn't handle networking
- Steeper learning curve for complex data structures
- Less actively maintained compared to AFNetworking
Code Comparison
Mantle:
@interface Person : MTLModel <MTLJSONSerializing>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSNumber *age;
@end
@implementation Person
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
return @{@"name": @"full_name", @"age": @"years_old"};
}
@end
AFNetworking:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:@"https://api.example.com/people" parameters:nil progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"Error: %@", error);
}];
While AFNetworking focuses on networking operations, Mantle specializes in object modeling. AFNetworking is more versatile for general networking tasks, while Mantle excels at transforming JSON data into model objects. AFNetworking is more actively maintained and has a larger community, but Mantle offers a more streamlined approach to data modeling when that's the primary need.
Reactive Programming in Swift
Pros of RxSwift
- Provides a comprehensive reactive programming framework for Swift
- Offers powerful tools for handling asynchronous operations and event streams
- Integrates well with other Swift libraries and frameworks
Cons of RxSwift
- Steeper learning curve compared to AFNetworking
- Can lead to more complex code for simple tasks
- Requires a shift in programming paradigm for developers new to reactive programming
Code Comparison
AFNetworking (HTTP request):
AF.request("https://api.example.com/data").responseJSON { response in
switch response.result {
case .success(let value):
print("Success: \(value)")
case .failure(let error):
print("Error: \(error)")
}
}
RxSwift (HTTP request with Observable):
URLSession.shared.rx.data(request: URLRequest(url: URL(string: "https://api.example.com/data")!))
.subscribe(onNext: { data in
print("Received data: \(data)")
}, onError: { error in
print("Error: \(error)")
})
.disposed(by: disposeBag)
Both AFNetworking and RxSwift are popular iOS networking libraries, but they serve different purposes. AFNetworking focuses on simplifying network requests, while RxSwift provides a reactive programming framework that can be used for networking and beyond. The choice between them depends on the project's requirements and the team's familiarity with reactive programming concepts.
The better way to deal with JSON data in Swift.
Pros of SwiftyJSON
- Focused specifically on JSON parsing in Swift, making it more lightweight and specialized
- Simpler syntax for accessing JSON data, with less boilerplate code
- Better type safety and error handling for JSON parsing
Cons of SwiftyJSON
- Limited to JSON parsing, while AFNetworking offers a broader range of networking features
- May require additional libraries for more complex networking tasks
- Less actively maintained compared to AFNetworking
Code Comparison
SwiftyJSON:
if let json = try? JSON(data: data) {
let name = json["name"].stringValue
let age = json["age"].intValue
}
AFNetworking:
[manager GET:URLString parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSString *name = responseObject[@"name"];
NSNumber *age = responseObject[@"age"];
} failure:nil];
SwiftyJSON provides a more concise and type-safe way to parse JSON data, while AFNetworking offers a broader set of networking capabilities, including request handling and response serialization. SwiftyJSON is ideal for projects focused on JSON parsing in Swift, whereas AFNetworking is better suited for more comprehensive networking needs in Objective-C or Swift projects.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
AFNetworking is Deprecated
As of Jan. 17, 2023, AFNetworking is deprecated and there will be no further releases. This repo will remain online in perpetuity as an archive. There are a couple options for continued AFNetworking use:
- Copy AFNetworking into your project and compile it directly. This gives you full control over the code.
- Fork AFNetworking and use the fork in your dependency manager. There will be no official forks but anyone can fork at any time and can even publish those forks under a different name, in accordance with AFNetworking's license.
Moving forward, Alamofire is the suggested migration path for networking in modern Swift. Anyone who needs help making that migration is welcome to ask on StackOverflow and tag alamofire
and afnetworking
, or open a discussion on Alamofire's GitHub Discussions regarding any migration issues or missing features.
AFNetworking is a delightful networking library for iOS, macOS, watchOS, and tvOS. It's built on top of the Foundation URL Loading System, extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use.
Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac.
How To Get Started
- Download AFNetworking and try out the included Mac and iPhone example apps
- Read the "Getting Started" guide, FAQ, or other articles on the Wiki
Communication
- If you need help, use Stack Overflow. (Tag 'afnetworking')
- If you'd like to ask a general question, use Stack Overflow.
- If you found a bug, and can provide steps to reliably reproduce it, open an issue.
- If you have a feature request, open an issue.
- If you want to contribute, submit a pull request.
Installation
AFNetworking supports multiple methods for installing the library in a project.
Installation with CocoaPods
To integrate AFNetworking into your Xcode project using CocoaPods, specify it in your Podfile
:
pod 'AFNetworking', '~> 4.0'
Installation with Swift Package Manager
Once you have your Swift package set up, adding AFNetworking as a dependency is as easy as adding it to the dependencies
value of your Package.swift
.
dependencies: [
.package(url: "https://github.com/AFNetworking/AFNetworking.git", .upToNextMajor(from: "4.0.0"))
]
Note: AFNetworking's Swift package does not include it's UIKit extensions.
Installation with Carthage
Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate AFNetworking, add the following to your Cartfile
.
github "AFNetworking/AFNetworking" ~> 4.0
Requirements
AFNetworking Version | Minimum iOS Target | Minimum macOS Target | Minimum watchOS Target | Minimum tvOS Target | Notes |
---|---|---|---|---|---|
4.x | iOS 9 | macOS 10.10 | watchOS 2.0 | tvOS 9.0 | Xcode 11+ is required. |
3.x | iOS 7 | OS X 10.9 | watchOS 2.0 | tvOS 9.0 | Xcode 7+ is required. NSURLConnectionOperation support has been removed. |
2.6 -> 2.6.3 | iOS 7 | OS X 10.9 | watchOS 2.0 | n/a | Xcode 7+ is required. |
2.0 -> 2.5.4 | iOS 6 | OS X 10.8 | n/a | n/a | Xcode 5+ is required. NSURLSession subspec requires iOS 7 or OS X 10.9. |
1.x | iOS 5 | Mac OS X 10.7 | n/a | n/a | |
0.10.x | iOS 4 | Mac OS X 10.6 | n/a | n/a |
(macOS projects must support 64-bit with modern Cocoa runtime).
Programming in Swift? Try Alamofire for a more conventional set of APIs.
Architecture
NSURLSession
AFURLSessionManager
AFHTTPSessionManager
Serialization
<AFURLRequestSerialization>
AFHTTPRequestSerializer
AFJSONRequestSerializer
AFPropertyListRequestSerializer
<AFURLResponseSerialization>
AFHTTPResponseSerializer
AFJSONResponseSerializer
AFXMLParserResponseSerializer
AFXMLDocumentResponseSerializer
(macOS)AFPropertyListResponseSerializer
AFImageResponseSerializer
AFCompoundResponseSerializer
Additional Functionality
AFSecurityPolicy
AFNetworkReachabilityManager
Usage
AFURLSessionManager
AFURLSessionManager
creates and manages an NSURLSession
object based on a specified NSURLSessionConfiguration
object, which conforms to <NSURLSessionTaskDelegate>
, <NSURLSessionDataDelegate>
, <NSURLSessionDownloadDelegate>
, and <NSURLSessionDelegate>
.
Creating a Download Task
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];
Creating an Upload Task
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"Success: %@ %@", response, responseObject);
}
}];
[uploadTask resume];
Creating an Upload Task for a Multi-Part Request, with Progress
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[progressView setProgress:uploadProgress.fractionCompleted];
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[uploadTask resume];
Creating a Data Task
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[dataTask resume];
Request Serialization
Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.
NSString *URLString = @"http://example.com";
NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
Query String Parameter Encoding
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
URL Form Parameter Encoding
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
POST http://example.com/
Content-Type: application/x-www-form-urlencoded
foo=bar&baz[]=1&baz[]=2&baz[]=3
JSON Parameter Encoding
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
POST http://example.com/
Content-Type: application/json
{"foo": "bar", "baz": [1,2,3]}
Network Reachability Manager
AFNetworkReachabilityManager
monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
- Do not use Reachability to determine if the original request should be sent.
- You should try to send it.
- You can use Reachability to determine when a request should be automatically retried.
- Although it may still fail, a Reachability notification that the connectivity is available is a good time to retry something.
- Network reachability is a useful tool for determining why a request might have failed.
- After a network request has failed, telling the user they're offline is better than giving them a more technical but accurate error, such as "request timed out."
See also WWDC 2012 session 706, "Networking Best Practices.".
Shared Network Reachability
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
Security Policy
AFSecurityPolicy
evaluates server trust against pinned X.509 certificates and public keys over secure connections.
Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.
Allowing Invalid SSL Certificates
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production
Unit Tests
AFNetworking includes a suite of unit tests within the Tests subdirectory. These tests can be run simply be executed the test action on the platform framework you would like to test.
Credits
AFNetworking is owned and maintained by the Alamofire Software Foundation.
AFNetworking was originally created by Scott Raymond and Mattt Thompson in the development of Gowalla for iPhone.
AFNetworking's logo was designed by Alan Defibaugh.
And most of all, thanks to AFNetworking's growing list of contributors.
Security Disclosure
If you believe you have identified a security vulnerability with AFNetworking, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker.
License
AFNetworking is released under the MIT license. See LICENSE for details.
Top Related Projects
Elegant HTTP Networking in Swift
Promises for Swift & ObjC.
Network abstraction layer written in Swift.
Model framework for Cocoa and Cocoa Touch
Reactive Programming in Swift
The better way to deal with JSON data in Swift.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot