wireapp/AFNetworking

Name: AFNetworking

Owner: Wire Swiss GmbH

Description: A delightful networking framework for iOS, OS X, watchOS, and tvOS.

Forked from: AFNetworking/AFNetworking

Created: 2016-07-14 14:49:00.0

Updated: 2017-10-19 12:26:53.0

Pushed: 2017-01-10 15:46:59.0

Homepage: http://afnetworking.com

Size: 5208

Language: Objective-C

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

AFNetworking

Build Status codecov.io CocoaPods Compatible Carthage Compatible Platform Twitter

AFNetworking is a delightful networking library for iOS and Mac OS X. 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.

Choose AFNetworking for your next project, or migrate over your existing projects?you'll be happy you did!

How To Get Started
Communication
Installation

AFNetworking supports multiple methods for installing the library in a project.

Installation with CocoaPods

CocoaPods is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries like AFNetworking in your projects. See the “Getting Started” guide for more information. You can install it with the following command:

m install cocoapods

CocoaPods 0.39.0+ is required to build AFNetworking 3.0.0+.

Podfile

To integrate AFNetworking into your Xcode project using CocoaPods, specify it in your Podfile:

ce 'https://github.com/CocoaPods/Specs.git'
form :ios, '8.0'

et 'TargetName' do
'AFNetworking', '~> 3.0'

Then, run the following command:

d install
Installation with Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

ew update
ew install carthage

To integrate AFNetworking into your Xcode project using Carthage, specify it in your Cartfile:

ub "AFNetworking/AFNetworking" ~> 3.0

Run carthage to build the framework and drag the built AFNetworking.framework into your Xcode project.

Requirements

| AFNetworking Version | Minimum iOS Target | Minimum OS X Target | Minimum watchOS Target | Minimum tvOS Target | Notes | |:——————–:|:—————————:|:—————————-:|:—————————-:|:—————————-:|:————————————————————————-:| | 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 |

(OS X projects must support 64-bit with modern Cocoa runtime).

Programming in Swift? Try Alamofire for a more conventional set of APIs.

Architecture
NSURLSession
Serialization
Additional Functionality
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
LSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
LSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

L *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
LRequest *request = [NSURLRequest requestWithURL:URL];

LSessionDownloadTask *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]];
mpletionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"File downloaded to: %@", filePath);

nloadTask resume];
Creating an Upload Task
LSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
LSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

L *URL = [NSURL URLWithString:@"http://example.com/upload"];
LRequest *request = [NSURLRequest requestWithURL:URL];

L *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
LSessionUploadTask *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);
}

oadTask resume];
Creating an Upload Task for a Multi-Part Request, with Progress
tableURLRequest *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];

LSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

LSessionUploadTask *uploadTask;
adTask = [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);
              }
          }];

oadTask resume];
Creating a Data Task
LSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
LSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

L *URL = [NSURL URLWithString:@"http://httpbin.org/get"];
LRequest *request = [NSURLRequest requestWithURL:URL];

LSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
    NSLog(@"Error: %@", error);
} else {
    NSLog(@"%@ %@", response, responseObject);
}

aTask resume];

Request Serialization

Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.

ring *URLString = @"http://example.com";
ctionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
Query String Parameter Encoding
HTTPRequestSerializer 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
HTTPRequestSerializer 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
JSONRequestSerializer 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.

See also WWDC 2012 session 706, “Networking Best Practices.”.

Shared Network Reachability
NetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));


NetworkReachabilityManager 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
TPSessionManager *manager = [AFHTTPSessionManager manager];
ger.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.


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.