You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 14 KiB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. <p align="center" >
  2. <img src="https://raw.github.com/AFNetworking/AFNetworking/assets/afnetworking-logo.png" alt="AFNetworking" title="AFNetworking">
  3. </p>
  4. [![Build Status](https://travis-ci.org/AFNetworking/AFNetworking.svg)](https://travis-ci.org/AFNetworking/AFNetworking)
  5. [![codecov.io](https://codecov.io/github/AFNetworking/AFNetworking/coverage.svg?branch=master)](https://codecov.io/github/AFNetworking/AFNetworking?branch=master)
  6. [![CocoaPods Compatible](https://img.shields.io/cocoapods/v/AFNetworking.svg)](https://img.shields.io/cocoapods/v/AFNetworking.svg)
  7. [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
  8. [![Platform](https://img.shields.io/cocoapods/p/AFNetworking.svg?style=flat)](http://cocoadocs.org/docsets/AFNetworking)
  9. [![Twitter](https://img.shields.io/badge/twitter-@AFNetworking-blue.svg?style=flat)](http://twitter.com/AFNetworking)
  10. AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of the [Foundation URL Loading System](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html), 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.
  11. 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.
  12. Choose AFNetworking for your next project, or migrate over your existing projects—you'll be happy you did!
  13. ## How To Get Started
  14. - [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/archive/master.zip) and try out the included Mac and iPhone example apps
  15. - Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles on the Wiki](https://github.com/AFNetworking/AFNetworking/wiki)
  16. - Check out the [documentation](http://cocoadocs.org/docsets/AFNetworking/) for a comprehensive look at all of the APIs available in AFNetworking
  17. - Read the [AFNetworking 3.0 Migration Guide](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-3.0-Migration-Guide) for an overview of the architectural changes from 2.0.
  18. ## Communication
  19. - If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). (Tag 'afnetworking')
  20. - If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking).
  21. - If you **found a bug**, _and can provide steps to reliably reproduce it_, open an issue.
  22. - If you **have a feature request**, open an issue.
  23. - If you **want to contribute**, submit a pull request.
  24. ## Installation
  25. AFNetworking supports multiple methods for installing the library in a project.
  26. ## Installation with CocoaPods
  27. [CocoaPods](http://cocoapods.org) 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](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking). You can install it with the following command:
  28. ```bash
  29. $ gem install cocoapods
  30. ```
  31. > CocoaPods 0.39.0+ is required to build AFNetworking 3.0.0+.
  32. #### Podfile
  33. To integrate AFNetworking into your Xcode project using CocoaPods, specify it in your `Podfile`:
  34. ```ruby
  35. source 'https://github.com/CocoaPods/Specs.git'
  36. platform :ios, '8.0'
  37. pod 'AFNetworking', '~> 3.0'
  38. ```
  39. Then, run the following command:
  40. ```bash
  41. $ pod install
  42. ```
  43. ### Installation with Carthage
  44. [Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.
  45. You can install Carthage with [Homebrew](http://brew.sh/) using the following command:
  46. ```bash
  47. $ brew update
  48. $ brew install carthage
  49. ```
  50. To integrate AFNetworking into your Xcode project using Carthage, specify it in your `Cartfile`:
  51. ```ogdl
  52. github "AFNetworking/AFNetworking" ~> 3.0
  53. ```
  54. Run `carthage` to build the framework and drag the built `AFNetworking.framework` into your Xcode project.
  55. ## Requirements
  56. | AFNetworking Version | Minimum iOS Target | Minimum OS X Target | Minimum watchOS Target | Minimum tvOS Target | Notes |
  57. |:--------------------:|:---------------------------:|:----------------------------:|:----------------------------:|:----------------------------:|:-------------------------------------------------------------------------:|
  58. | 3.x | iOS 7 | OS X 10.9 | watchOS 2.0 | tvOS 9.0 | Xcode 7+ is required. `NSURLConnectionOperation` support has been removed. |
  59. | 2.6 -> 2.6.3 | iOS 7 | OS X 10.9 | watchOS 2.0 | n/a | Xcode 7+ is required. |
  60. | 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. |
  61. | 1.x | iOS 5 | Mac OS X 10.7 | n/a | n/a |
  62. | 0.10.x | iOS 4 | Mac OS X 10.6 | n/a | n/a |
  63. (OS X projects must support [64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)).
  64. > Programming in Swift? Try [Alamofire](https://github.com/Alamofire/Alamofire) for a more conventional set of APIs.
  65. ## Architecture
  66. ### NSURLSession
  67. - `AFURLSessionManager`
  68. - `AFHTTPSessionManager`
  69. ### Serialization
  70. * `<AFURLRequestSerialization>`
  71. - `AFHTTPRequestSerializer`
  72. - `AFJSONRequestSerializer`
  73. - `AFPropertyListRequestSerializer`
  74. * `<AFURLResponseSerialization>`
  75. - `AFHTTPResponseSerializer`
  76. - `AFJSONResponseSerializer`
  77. - `AFXMLParserResponseSerializer`
  78. - `AFXMLDocumentResponseSerializer` _(Mac OS X)_
  79. - `AFPropertyListResponseSerializer`
  80. - `AFImageResponseSerializer`
  81. - `AFCompoundResponseSerializer`
  82. ### Additional Functionality
  83. - `AFSecurityPolicy`
  84. - `AFNetworkReachabilityManager`
  85. ## Usage
  86. ### AFURLSessionManager
  87. `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
  88. #### Creating a Download Task
  89. ```objective-c
  90. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  91. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
  92. NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
  93. NSURLRequest *request = [NSURLRequest requestWithURL:URL];
  94. NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
  95. NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
  96. return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
  97. } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
  98. NSLog(@"File downloaded to: %@", filePath);
  99. }];
  100. [downloadTask resume];
  101. ```
  102. #### Creating an Upload Task
  103. ```objective-c
  104. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  105. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
  106. NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
  107. NSURLRequest *request = [NSURLRequest requestWithURL:URL];
  108. NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
  109. NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
  110. if (error) {
  111. NSLog(@"Error: %@", error);
  112. } else {
  113. NSLog(@"Success: %@ %@", response, responseObject);
  114. }
  115. }];
  116. [uploadTask resume];
  117. ```
  118. #### Creating an Upload Task for a Multi-Part Request, with Progress
  119. ```objective-c
  120. NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  121. [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
  122. } error:nil];
  123. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  124. NSURLSessionUploadTask *uploadTask;
  125. uploadTask = [manager
  126. uploadTaskWithStreamedRequest:request
  127. progress:^(NSProgress * _Nonnull uploadProgress) {
  128. // This is not called back on the main queue.
  129. // You are responsible for dispatching to the main queue for UI updates
  130. dispatch_async(dispatch_get_main_queue(), ^{
  131. //Update the progress view
  132. [progressView setProgress:uploadProgress.fractionCompleted];
  133. });
  134. }
  135. completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
  136. if (error) {
  137. NSLog(@"Error: %@", error);
  138. } else {
  139. NSLog(@"%@ %@", response, responseObject);
  140. }
  141. }];
  142. [uploadTask resume];
  143. ```
  144. #### Creating a Data Task
  145. ```objective-c
  146. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  147. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
  148. NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"];
  149. NSURLRequest *request = [NSURLRequest requestWithURL:URL];
  150. NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
  151. if (error) {
  152. NSLog(@"Error: %@", error);
  153. } else {
  154. NSLog(@"%@ %@", response, responseObject);
  155. }
  156. }];
  157. [dataTask resume];
  158. ```
  159. ---
  160. ### Request Serialization
  161. Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.
  162. ```objective-c
  163. NSString *URLString = @"http://example.com";
  164. NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
  165. ```
  166. #### Query String Parameter Encoding
  167. ```objective-c
  168. [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
  169. ```
  170. GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
  171. #### URL Form Parameter Encoding
  172. ```objective-c
  173. [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
  174. ```
  175. POST http://example.com/
  176. Content-Type: application/x-www-form-urlencoded
  177. foo=bar&baz[]=1&baz[]=2&baz[]=3
  178. #### JSON Parameter Encoding
  179. ```objective-c
  180. [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
  181. ```
  182. POST http://example.com/
  183. Content-Type: application/json
  184. {"foo": "bar", "baz": [1,2,3]}
  185. ---
  186. ### Network Reachability Manager
  187. `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
  188. * Do not use Reachability to determine if the original request should be sent.
  189. * You should try to send it.
  190. * You can use Reachability to determine when a request should be automatically retried.
  191. * Although it may still fail, a Reachability notification that the connectivity is available is a good time to retry something.
  192. * Network reachability is a useful tool for determining why a request might have failed.
  193. * 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."
  194. See also [WWDC 2012 session 706, "Networking Best Practices."](https://developer.apple.com/videos/play/wwdc2012-706/).
  195. #### Shared Network Reachability
  196. ```objective-c
  197. [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
  198. NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
  199. }];
  200. [[AFNetworkReachabilityManager sharedManager] startMonitoring];
  201. ```
  202. ---
  203. ### Security Policy
  204. `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
  205. 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.
  206. #### Allowing Invalid SSL Certificates
  207. ```objective-c
  208. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  209. manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production
  210. ```
  211. ---
  212. ## Unit Tests
  213. 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.
  214. ## Credits
  215. AFNetworking is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org).
  216. AFNetworking was originally created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla).
  217. AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/).
  218. And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors).
  219. ### Security Disclosure
  220. 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.
  221. ## License
  222. AFNetworking is released under the MIT license. See LICENSE for details.