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.

298 lines
13 KiB

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