Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge branch 2.0 into master

commit 9a40c0dc0f27e9a547fb173a0b1b5a06072e91f9 1 parent ce1ebf3
@mattt mattt authored
Showing with 7,429 additions and 3,659 deletions.
  1. +0 −7 .travis.yml
  2. +49 −24 AFNetworking.podspec
  3. +93 −27 AFNetworking.xcworkspace/contents.xcworkspacedata
  4. +0 −641 AFNetworking/AFHTTPClient.h
  5. +7 −77 AFNetworking/AFHTTPRequestOperation.h
  6. +77 −248 AFNetworking/AFHTTPRequestOperation.m
  7. +276 −0 AFNetworking/AFHTTPRequestOperationManager.h
  8. +235 −0 AFNetworking/AFHTTPRequestOperationManager.m
  9. +234 −0 AFNetworking/AFHTTPSessionManager.h
  10. +315 −0 AFNetworking/AFHTTPSessionManager.m
  11. +0 −113 AFNetworking/AFImageRequestOperation.h
  12. +0 −321 AFNetworking/AFImageRequestOperation.m
  13. +0 −71 AFNetworking/AFJSONRequestOperation.h
  14. +0 −150 AFNetworking/AFJSONRequestOperation.m
  15. +167 −0 AFNetworking/AFNetworkReachabilityManager.h
  16. +224 −0 AFNetworking/AFNetworkReachabilityManager.m
  17. +9 −12 AFNetworking/AFNetworking.h
  18. +0 −68 AFNetworking/AFPropertyListRequestOperation.h
  19. +0 −143 AFNetworking/AFPropertyListRequestOperation.m
  20. +74 −0 AFNetworking/AFSecurityPolicy.h
  21. +214 −0 AFNetworking/AFSecurityPolicy.m
  22. +37 −31 AFNetworking/AFURLConnectionOperation.h
  23. +104 −226 AFNetworking/AFURLConnectionOperation.m
  24. +346 −0 AFNetworking/AFURLRequestSerialization.h
  25. +234 −503 AFNetworking/{AFHTTPClient.m → AFURLRequestSerialization.m}
  26. +258 −0 AFNetworking/AFURLResponseSerialization.h
  27. +713 −0 AFNetworking/AFURLResponseSerialization.m
  28. +429 −0 AFNetworking/AFURLSessionManager.h
  29. +839 −0 AFNetworking/AFURLSessionManager.m
  30. +0 −89 AFNetworking/AFXMLRequestOperation.h
  31. +0 −167 AFNetworking/AFXMLRequestOperation.m
  32. +6 −30 Example/AFNetworking Mac Example.xcodeproj/project.pbxproj
  33. +96 −0 Example/AFNetworking Mac Example.xcodeproj/xcshareddata/xcschemes/AFNetworking Example.xcscheme
  34. +150 −50 Example/AFNetworking iOS Example.xcodeproj/project.pbxproj
  35. +96 −0 Example/AFNetworking iOS Example.xcodeproj/xcshareddata/xcschemes/AFNetworking iOS Example.xcscheme
  36. +0 −6 Example/AppDelegate.m
  37. +3 −3 Example/Classes/AFAppDotNetAPIClient.h
  38. +3 −26 Example/Classes/AFAppDotNetAPIClient.m
  39. +13 −23 Example/Classes/Controllers/GlobalTimelineViewController.m
  40. +5 −5 Example/Classes/Models/Post.h
  41. +8 −11 Example/Classes/Models/Post.m
  42. +1 −1  Example/Classes/Models/User.h
  43. +39 −42 Example/Classes/Models/User.m
  44. +7 −7 Example/Classes/Views/PostTableViewCell.m
  45. BIN  Example/adn.cer
  46. +4 −0 Example/iOS-Info.plist
  47. +1 −1  LICENSE
  48. +24 −131 README.md
  49. +343 −177 Tests/AFNetworking Tests.xcodeproj/project.pbxproj
  50. +22 −0 Tests/OS X Tests/OS X Tests-Info.plist
  51. +10 −0 Tests/OS X Tests/OS X Tests-Prefix.pch
  52. +2 −0  Tests/OS X Tests/en.lproj/InfoPlist.strings
  53. +2 −3 Tests/Podfile
  54. +15 −9 Tests/Podfile.lock
  55. BIN  Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_0.cer
  56. BIN  Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_1.cer
  57. BIN  Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_2.cer
  58. BIN  Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_0.cer
  59. BIN  Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_1.cer
  60. BIN  Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_2.cer
  61. BIN  Tests/Resources/HTTPBin.org/httpbinorg_10242013.cer
  62. BIN  Tests/Resources/ca.cer
  63. BIN  Tests/Resources/derived.cert
  64. BIN  Tests/Resources/root_certificate.cer
  65. +0 −15 Tests/Resources/root_certificate.key
  66. +5 −124 Tests/{ → Tests/1.0 Tests}/AFHTTPClientTests.m
  67. +0 −3  Tests/{ → Tests/1.0 Tests}/AFHTTPRequestOperationTests.m
  68. +1 −4 Tests/{ → Tests/1.0 Tests}/AFImageRequestOperationTests.m
  69. +0 −1  Tests/{ → Tests/1.0 Tests}/AFJSONRequestOperationTests.m
  70. 0  Tests/{ → Tests/1.0 Tests}/AFMockURLProtocol.h
  71. 0  Tests/{ → Tests/1.0 Tests}/AFMockURLProtocol.m
  72. +1 −0  Tests/{ → Tests/1.0 Tests}/AFNetworkingTests.h
  73. 0  Tests/{ → Tests/1.0 Tests}/AFNetworkingTests.m
  74. +0 −1  Tests/{ → Tests/1.0 Tests}/AFURLConnectionOperationTests.m
  75. +278 −0 Tests/Tests/AFHTTPRequestOperationTests.m
  76. +62 −0 Tests/Tests/AFHTTPSerializationTests.m
  77. +99 −0 Tests/Tests/AFJSONSerializationTests.m
  78. +168 −0 Tests/Tests/AFSecurityPolicyTests.m
  79. +35 −0 Tests/Tests/AFTestCase.h
  80. +45 −0 Tests/Tests/AFTestCase.m
  81. +2 −0  Tests/iOS Tests/en.lproj/InfoPlist.strings
  82. +22 −0 Tests/iOS Tests/iOS Tests-Info.plist
  83. +10 −0 Tests/iOS Tests/iOS Tests-Prefix.pch
  84. +1 −1  {AFNetworking → UIKit+AFNetworking}/AFNetworkActivityIndicatorManager.h
  85. +25 −20 {AFNetworking → UIKit+AFNetworking}/AFNetworkActivityIndicatorManager.m
  86. +44 −0 UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h
  87. +68 −0 UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m
  88. +70 −0 UIKit+AFNetworking/UIAlertView+AFNetworking.h
  89. +99 −0 UIKit+AFNetworking/UIAlertView+AFNetworking.m
  90. +100 −0 UIKit+AFNetworking/UIButton+AFNetworking.h
  91. +134 −0 UIKit+AFNetworking/UIButton+AFNetworking.m
  92. +12 −2 {AFNetworking → UIKit+AFNetworking}/UIImageView+AFNetworking.h
  93. +55 −45 {AFNetworking → UIKit+AFNetworking}/UIImageView+AFNetworking.m
  94. +60 −0 UIKit+AFNetworking/UIProgressView+AFNetworking.h
  95. +134 −0 UIKit+AFNetworking/UIProgressView+AFNetworking.m
  96. +38 −0 UIKit+AFNetworking/UIWebView+AFNetworking.h
  97. +77 −0 UIKit+AFNetworking/UIWebView+AFNetworking.m
View
7 .travis.yml
@@ -1,7 +0,0 @@
-language: objective-c
-before_install:
- - brew update
- - brew uninstall xctool && brew install https://raw.github.com/fpotter/homebrew/246a1439dab49542d4531ad7e1bac7048151f601/Library/Formula/xctool.rb
- - gem install cocoapods -v 0.22.2
- - cd Tests && pod install && cd $TRAVIS_BUILD_DIR
-script: rake test
View
73 AFNetworking.podspec
@@ -1,31 +1,56 @@
Pod::Spec.new do |s|
s.name = 'AFNetworking'
- s.version = '1.3.3'
+ s.version = '2.0.0-RC3'
s.license = 'MIT'
s.summary = 'A delightful iOS and OS X networking framework.'
s.homepage = 'https://github.com/AFNetworking/AFNetworking'
- s.authors = { 'Mattt Thompson' => 'm@mattt.me', 'Scott Raymond' => 'sco@gowalla.com' }
- s.source = { :git => 'https://github.com/AFNetworking/AFNetworking.git', :tag => '1.3.3' }
- s.source_files = 'AFNetworking'
+ s.authors = { 'Mattt Thompson' => 'm@mattt.me', 'Scott Raymond' => 'sco@scottraymond.net' }
+ s.source = { :git => 'https://github.com/AFNetworking/AFNetworking.git', :tag => '2.0.0-RC3', :submodules => true }
s.requires_arc = true
- s.ios.deployment_target = '5.0'
- s.ios.frameworks = 'MobileCoreServices', 'SystemConfiguration', 'Security', 'CoreGraphics'
-
- s.osx.deployment_target = '10.7'
- s.osx.frameworks = 'CoreServices', 'SystemConfiguration', 'Security'
-
- s.prefix_header_contents = <<-EOS
-#import <Availability.h>
-
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
- #import <SystemConfiguration/SystemConfiguration.h>
- #import <MobileCoreServices/MobileCoreServices.h>
- #import <Security/Security.h>
-#else
- #import <SystemConfiguration/SystemConfiguration.h>
- #import <CoreServices/CoreServices.h>
- #import <Security/Security.h>
-#endif
-EOS
-end
+ s.ios.deployment_target = '6.0'
+ s.osx.deployment_target = '10.8'
+
+ s.default_subspec = 'Core'
+
+ s.subspec 'Core' do |ss|
+ ss.source_files = 'AFNetworking'
+
+ ss.dependency 'AFNetworking/Serialization'
+ ss.dependency 'AFNetworking/Reachability'
+ ss.dependency 'AFNetworking/Security'
+
+ ss.dependency 'AFNetworking/NSURLConnection'
+ end
+
+ s.subspec 'Serialization' do |ss|
+ ss.source_files = 'AFNetworking/AFURL{Request,Response}Serialization.{h,m}'
+ ss.ios.frameworks = 'MobileCoreServices', 'CoreGraphics'
+ ss.osx.frameworks = 'CoreServices'
+ end
+
+ s.subspec 'Security' do |ss|
+ ss.source_files = 'AFNetworking/AFSecurityPolicy.{h,m}'
+ ss.frameworks = 'Security'
+ end
+
+ s.subspec 'Reachability' do |ss|
+ ss.source_files = 'AFNetworking/AFNetworkReachabilityManager.{h,m}'
+ ss.frameworks = 'SystemConfiguration'
+ end
+
+ s.subspec 'NSURLConnection' do |ss|
+ ss.source_files = 'AFNetworking/AFURLConnectionOperation.{h,m}', 'AFNetworking/AFHTTPRequestOperation.{h,m}', 'AFNetworking/AFHTTPRequestOperationManager.{h,m}'
+ end
+
+ s.subspec 'NSURLSession' do |ss|
+ ss.ios.deployment_target = '7.0'
+ ss.osx.deployment_target = '10.9'
+
+ ss.source_files = 'AFNetworking/AFURLSessionManager.{h,m}', 'AFNetworking/AFHTTPSessionManager.{h,m}'
+ end
+
+ s.subspec 'UIKit' do |ss|
+ ss.ios.source_files = 'UIKit+AFNetworking'
+ end
+end
View
120 AFNetworking.xcworkspace/contents.xcworkspacedata
@@ -5,61 +5,127 @@
location = "group:AFNetworking"
name = "AFNetworking">
<FileRef
- location = "group:AFHTTPClient.h">
- </FileRef>
- <FileRef
- location = "group:AFHTTPClient.m">
- </FileRef>
- <FileRef
- location = "group:AFHTTPRequestOperation.h">
- </FileRef>
- <FileRef
- location = "group:AFHTTPRequestOperation.m">
- </FileRef>
- <FileRef
- location = "group:AFImageRequestOperation.h">
+ location = "group:AFNetworking.h">
</FileRef>
+ <Group
+ location = "container:"
+ name = "NSURLConnection">
+ <FileRef
+ location = "group:AFNetworking/AFURLConnectionOperation.h">
+ </FileRef>
+ <FileRef
+ location = "group:AFNetworking/AFURLConnectionOperation.m">
+ </FileRef>
+ <FileRef
+ location = "group:AFNetworking/AFHTTPRequestOperation.h">
+ </FileRef>
+ <FileRef
+ location = "group:AFNetworking/AFHTTPRequestOperation.m">
+ </FileRef>
+ <FileRef
+ location = "group:AFNetworking/AFHTTPRequestOperationManager.h">
+ </FileRef>
+ <FileRef
+ location = "group:AFNetworking/AFHTTPRequestOperationManager.m">
+ </FileRef>
+ </Group>
+ <Group
+ location = "container:"
+ name = "NSURLSession">
+ <FileRef
+ location = "group:AFNetworking/AFURLSessionManager.h">
+ </FileRef>
+ <FileRef
+ location = "group:AFNetworking/AFURLSessionManager.m">
+ </FileRef>
+ <FileRef
+ location = "group:AFNetworking/AFHTTPSessionManager.h">
+ </FileRef>
+ <FileRef
+ location = "group:AFNetworking/AFHTTPSessionManager.m">
+ </FileRef>
+ </Group>
+ <Group
+ location = "container:"
+ name = "Security">
+ <FileRef
+ location = "group:AFNetworking/AFSecurityPolicy.h">
+ </FileRef>
+ <FileRef
+ location = "group:AFNetworking/AFSecurityPolicy.m">
+ </FileRef>
+ </Group>
+ <Group
+ location = "container:"
+ name = "Reachability">
+ <FileRef
+ location = "group:AFNetworking/AFNetworkReachabilityManager.h">
+ </FileRef>
+ <FileRef
+ location = "group:AFNetworking/AFNetworkReachabilityManager.m">
+ </FileRef>
+ </Group>
+ <Group
+ location = "container:"
+ name = "Serialization">
+ <FileRef
+ location = "group:AFNetworking/AFURLRequestSerialization.h">
+ </FileRef>
+ <FileRef
+ location = "group:AFNetworking/AFURLRequestSerialization.m">
+ </FileRef>
+ <FileRef
+ location = "group:AFNetworking/AFURLResponseSerialization.h">
+ </FileRef>
+ <FileRef
+ location = "group:AFNetworking/AFURLResponseSerialization.m">
+ </FileRef>
+ </Group>
+ </Group>
+ <Group
+ location = "group:UIKit+AFNetworking"
+ name = "UIKit+AFNetworking">
<FileRef
- location = "group:AFImageRequestOperation.m">
+ location = "group:AFNetworkActivityIndicatorManager.h">
</FileRef>
<FileRef
- location = "group:AFJSONRequestOperation.h">
+ location = "group:AFNetworkActivityIndicatorManager.m">
</FileRef>
<FileRef
- location = "group:AFJSONRequestOperation.m">
+ location = "group:UIActivityIndicatorView+AFNetworking.h">
</FileRef>
<FileRef
- location = "group:AFNetworkActivityIndicatorManager.h">
+ location = "group:UIActivityIndicatorView+AFNetworking.m">
</FileRef>
<FileRef
- location = "group:AFNetworkActivityIndicatorManager.m">
+ location = "group:UIAlertView+AFNetworking.h">
</FileRef>
<FileRef
- location = "group:AFNetworking.h">
+ location = "group:UIAlertView+AFNetworking.m">
</FileRef>
<FileRef
- location = "group:AFPropertyListRequestOperation.h">
+ location = "group:UIButton+AFNetworking.h">
</FileRef>
<FileRef
- location = "group:AFPropertyListRequestOperation.m">
+ location = "group:UIButton+AFNetworking.m">
</FileRef>
<FileRef
- location = "group:AFURLConnectionOperation.h">
+ location = "group:UIImageView+AFNetworking.h">
</FileRef>
<FileRef
- location = "group:AFURLConnectionOperation.m">
+ location = "group:UIImageView+AFNetworking.m">
</FileRef>
<FileRef
- location = "group:AFXMLRequestOperation.h">
+ location = "group:UIProgressView+AFNetworking.h">
</FileRef>
<FileRef
- location = "group:AFXMLRequestOperation.m">
+ location = "group:UIProgressView+AFNetworking.m">
</FileRef>
<FileRef
- location = "group:UIImageView+AFNetworking.h">
+ location = "group:UIWebView+AFNetworking.h">
</FileRef>
<FileRef
- location = "group:UIImageView+AFNetworking.m">
+ location = "group:UIWebView+AFNetworking.m">
</FileRef>
</Group>
<FileRef
View
641 AFNetworking/AFHTTPClient.h
@@ -1,641 +0,0 @@
-// AFHTTPClient.h
-//
-// Copyright (c) 2011 Gowalla (http://gowalla.com/)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-#import <Foundation/Foundation.h>
-#import "AFURLConnectionOperation.h"
-
-#import <Availability.h>
-
-/**
- `AFHTTPClient` captures the common patterns of communicating with an web application over HTTP. It encapsulates information like base URL, authorization credentials, and HTTP headers, and uses them to construct and manage the execution of HTTP request operations.
-
- ## Automatic Content Parsing
-
- Instances of `AFHTTPClient` may specify which types of requests it expects and should handle by registering HTTP operation classes for automatic parsing. Registered classes will determine whether they can handle a particular request, and then construct a request operation accordingly in `enqueueHTTPRequestOperationWithRequest:success:failure`.
-
- ## Subclassing Notes
-
- In most cases, one should create an `AFHTTPClient` subclass for each website or web application that your application communicates with. It is often useful, also, to define a class method that returns a singleton shared HTTP client in each subclass, that persists authentication credentials and other configuration across the entire application.
-
- ## Methods to Override
-
- To change the behavior of all url request construction for an `AFHTTPClient` subclass, override `requestWithMethod:path:parameters`.
-
- To change the behavior of all request operation construction for an `AFHTTPClient` subclass, override `HTTPRequestOperationWithRequest:success:failure`.
-
- ## Default Headers
-
- By default, `AFHTTPClient` sets the following HTTP headers:
-
- - `Accept-Language: (comma-delimited preferred languages), en-us;q=0.8`
- - `User-Agent: (generated user agent)`
-
- You can override these HTTP headers or define new ones using `setDefaultHeader:value:`.
-
- ## URL Construction Using Relative Paths
-
- Both `-requestWithMethod:path:parameters:` and `-multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:` construct URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`. Below are a few examples of how `baseURL` and relative paths interact:
-
- NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
- [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo
- [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz
- [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo
- [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo
- [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/
- [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
-
- Also important to note is that a trailing slash will be added to any `baseURL` without one, which would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.
-
- ## NSCoding / NSCopying Conformance
-
- `AFHTTPClient` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however:
-
- - Archives and copies of HTTP clients will be initialized with an empty operation queue.
- - NSCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set.
- */
-
-#ifdef _SYSTEMCONFIGURATION_H
-typedef enum {
- AFNetworkReachabilityStatusUnknown = -1,
- AFNetworkReachabilityStatusNotReachable = 0,
- AFNetworkReachabilityStatusReachableViaWWAN = 1,
- AFNetworkReachabilityStatusReachableViaWiFi = 2,
-} AFNetworkReachabilityStatus;
-#else
-#pragma message("SystemConfiguration framework not found in project, or not included in precompiled header. Network reachability functionality will not be available.")
-#endif
-
-#ifndef __UTTYPE__
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
-#pragma message("MobileCoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.")
-#else
-#pragma message("CoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.")
-#endif
-#endif
-
-typedef enum {
- AFFormURLParameterEncoding,
- AFJSONParameterEncoding,
- AFPropertyListParameterEncoding,
-} AFHTTPClientParameterEncoding;
-
-@class AFHTTPRequestOperation;
-@protocol AFMultipartFormData;
-
-@interface AFHTTPClient : NSObject <NSCoding, NSCopying>
-
-///---------------------------------------
-/// @name Accessing HTTP Client Properties
-///---------------------------------------
-
-/**
- The url used as the base for paths specified in methods such as `getPath:parameters:success:failure`
- */
-@property (readonly, nonatomic, strong) NSURL *baseURL;
-
-/**
- The string encoding used in constructing url requests. This is `NSUTF8StringEncoding` by default.
- */
-@property (nonatomic, assign) NSStringEncoding stringEncoding;
-
-/**
- The `AFHTTPClientParameterEncoding` value corresponding to how parameters are encoded into a request body for request methods other than `GET`, `HEAD` or `DELETE`. This is `AFFormURLParameterEncoding` by default.
-
- @warning Some nested parameter structures, such as a keyed array of hashes containing inconsistent keys (i.e. `@{@"": @[@{@"a" : @(1)}, @{@"b" : @(2)}]}`), cannot be unambiguously represented in query strings. It is strongly recommended that an unambiguous encoding, such as `AFJSONParameterEncoding`, is used when posting complicated or nondeterministic parameter structures.
- */
-@property (nonatomic, assign) AFHTTPClientParameterEncoding parameterEncoding;
-
-/**
- The operation queue which manages operations enqueued by the HTTP client.
- */
-@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;
-
-/**
- The reachability status from the device to the current `baseURL` of the `AFHTTPClient`.
-
- @warning This property requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
- */
-#ifdef _SYSTEMCONFIGURATION_H
-@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
-#endif
-
-/**
- Default SSL pinning mode for each `AFHTTPRequestOperation` created by `HTTPRequestOperationWithRequest:success:failure:`.
- */
-@property (nonatomic, assign) AFURLConnectionOperationSSLPinningMode defaultSSLPinningMode;
-
-/**
- Whether each `AFHTTPRequestOperation` created by `HTTPRequestOperationWithRequest:success:failure:` should accept an invalid SSL certificate.
-
- If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is set, this property defaults to `YES` for backwards compatibility. Otherwise, this property defaults to `NO`.
- */
-@property (nonatomic, assign) BOOL allowsInvalidSSLCertificate;
-
-///---------------------------------------------
-/// @name Creating and Initializing HTTP Clients
-///---------------------------------------------
-
-/**
- Creates and initializes an `AFHTTPClient` object with the specified base URL.
-
- @param url The base URL for the HTTP client. This argument must not be `nil`.
-
- @return The newly-initialized HTTP client
- */
-+ (instancetype)clientWithBaseURL:(NSURL *)url;
-
-/**
- Initializes an `AFHTTPClient` object with the specified base URL.
-
- This is the designated initializer.
-
- @param url The base URL for the HTTP client. This argument must not be `nil`.
-
- @return The newly-initialized HTTP client
- */
-- (id)initWithBaseURL:(NSURL *)url;
-
-///-----------------------------------
-/// @name Managing Reachability Status
-///-----------------------------------
-
-/**
- Sets a callback to be executed when the network availability of the `baseURL` host changes.
-
- @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`.
-
- @warning This method requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
- */
-#ifdef _SYSTEMCONFIGURATION_H
-- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block;
-#endif
-
-///-------------------------------
-/// @name Managing HTTP Operations
-///-------------------------------
-
-/**
- Attempts to register a subclass of `AFHTTPRequestOperation`, adding it to a chain to automatically generate request operations from a URL request.
-
- When `enqueueHTTPRequestOperationWithRequest:success:failure` is invoked, each registered class is consulted in turn to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to create an operation using `initWithURLRequest:` and do `setCompletionBlockWithSuccess:failure:`. There is no guarantee that all registered classes will be consulted. Classes are consulted in the reverse order of their registration. Attempting to register an already-registered class will move it to the top of the list.
-
- @param operationClass The subclass of `AFHTTPRequestOperation` to register
-
- @return `YES` if the registration is successful, `NO` otherwise. The only failure condition is if `operationClass` is not a subclass of `AFHTTPRequestOperation`.
- */
-- (BOOL)registerHTTPOperationClass:(Class)operationClass;
-
-/**
- Unregisters the specified subclass of `AFHTTPRequestOperation` from the chain of classes consulted when `-requestWithMethod:path:parameters` is called.
-
- @param operationClass The subclass of `AFHTTPRequestOperation` to register
- */
-- (void)unregisterHTTPOperationClass:(Class)operationClass;
-
-///----------------------------------
-/// @name Managing HTTP Header Values
-///----------------------------------
-
-/**
- Returns the value for the HTTP headers set in request objects created by the HTTP client.
-
- @param header The HTTP header to return the default value for
-
- @return The default value for the HTTP header, or `nil` if unspecified
- */
-- (NSString *)defaultValueForHeader:(NSString *)header;
-
-/**
- Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header.
-
- @param header The HTTP header to set a default value for
- @param value The value set as default for the specified header, or `nil
- */
-- (void)setDefaultHeader:(NSString *)header
- value:(NSString *)value;
-
-/**
- Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header.
-
- @param username The HTTP basic auth username
- @param password The HTTP basic auth password
- */
-- (void)setAuthorizationHeaderWithUsername:(NSString *)username
- password:(NSString *)password;
-
-/**
- Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a token-based authentication value, such as an OAuth access token. This overwrites any existing value for this header.
-
- @param token The authentication token
- */
-- (void)setAuthorizationHeaderWithToken:(NSString *)token;
-
-
-/**
- Clears any existing value for the "Authorization" HTTP header.
- */
-- (void)clearAuthorizationHeader;
-
-///-------------------------------
-/// @name Managing URL Credentials
-///-------------------------------
-
-/**
- Set the default URL credential to be set for request operations.
-
- @param credential The URL credential
- */
-- (void)setDefaultCredential:(NSURLCredential *)credential;
-
-///-------------------------------
-/// @name Creating Request Objects
-///-------------------------------
-
-/**
- Creates an `NSMutableURLRequest` object with the specified HTTP method and path.
-
- If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body.
-
- @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`.
- @param path The path to be appended to the HTTP client's base URL and used as the request URL. If `nil`, no path will be appended to the base URL.
- @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
-
- @return An `NSMutableURLRequest` object
- */
-- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
- path:(NSString *)path
- parameters:(NSDictionary *)parameters;
-
-/**
- Creates an `NSMutableURLRequest` object with the specified HTTP method and path, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2
-
- Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream.
-
- @param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`.
- @param path The path to be appended to the HTTP client's base URL and used as the request URL.
- @param parameters The parameters to be encoded and set in the request HTTP body.
- @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. This can be used to upload files, encode HTTP body as JSON or XML, or specify multiple values for the same parameter, as one might for array values.
-
- @return An `NSMutableURLRequest` object
- */
-- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
- path:(NSString *)path
- parameters:(NSDictionary *)parameters
- constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block;
-
-///-------------------------------
-/// @name Creating HTTP Operations
-///-------------------------------
-
-/**
- Creates an `AFHTTPRequestOperation`.
-
- In order to determine what kind of operation is created, each registered subclass conforming to the `AFHTTPClient` protocol is consulted (in reverse order of when they were specified) to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to generate an operation using `HTTPRequestOperationWithRequest:success:failure:`.
-
- @param urlRequest The request object to be loaded asynchronously during execution of the operation.
- @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
- @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
- */
-- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
- success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
-
-///----------------------------------------
-/// @name Managing Enqueued HTTP Operations
-///----------------------------------------
-
-/**
- Enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue.
-
- @param operation The HTTP request operation to be enqueued.
- */
-- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation;
-
-/**
- Cancels all operations in the HTTP client's operation queue whose URLs match the specified HTTP method and path.
-
- This method only cancels `AFHTTPRequestOperations` whose request URL matches the HTTP client base URL with the path appended. For complete control over the lifecycle of enqueued operations, you can access the `operationQueue` property directly, which allows you to, for instance, cancel operations filtered by a predicate, or simply use `-cancelAllRequests`. Note that the operation queue may include non-HTTP operations, so be sure to check the type before attempting to directly introspect an operation's `request` property.
-
- @param method The HTTP method to match for the cancelled requests, such as `GET`, `POST`, `PUT`, or `DELETE`. If `nil`, all request operations with URLs matching the path will be cancelled.
- @param path The path appended to the HTTP client base URL to match against the cancelled requests. If `nil`, no path will be appended to the base URL.
- */
-- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path;
-
-///---------------------------------------
-/// @name Batching HTTP Request Operations
-///---------------------------------------
-
-/**
- Creates and enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue for each specified request object into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.
-
- Operations are created by passing the specified `NSURLRequest` objects in `requests`, using `-HTTPRequestOperationWithRequest:success:failure:`, with `nil` for both the `success` and `failure` parameters.
-
- @param urlRequests The `NSURLRequest` objects used to create and enqueue operations.
- @param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations.
- @param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations.
- */
-- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)urlRequests
- progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
- completionBlock:(void (^)(NSArray *operations))completionBlock;
-
-/**
- Enqueues the specified request operations into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.
-
- @param operations The request operations used to be batched and enqueued.
- @param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations.
- @param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations.
- */
-- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
- progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
- completionBlock:(void (^)(NSArray *operations))completionBlock;
-
-///---------------------------
-/// @name Making HTTP Requests
-///---------------------------
-
-/**
- Creates an `AFHTTPRequestOperation` with a `GET` request, and enqueues it to the HTTP client's operation queue.
-
- @param path The path to be appended to the HTTP client's base URL and used as the request URL.
- @param parameters The parameters to be encoded and appended as the query string for the request URL.
- @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
- @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
-
- @see -HTTPRequestOperationWithRequest:success:failure:
- */
-- (void)getPath:(NSString *)path
- parameters:(NSDictionary *)parameters
- success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
-
-/**
- Creates an `AFHTTPRequestOperation` with a `POST` request, and enqueues it to the HTTP client's operation queue.
-
- @param path The path to be appended to the HTTP client's base URL and used as the request URL.
- @param parameters The parameters to be encoded and set in the request HTTP body.
- @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
- @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
-
- @see -HTTPRequestOperationWithRequest:success:failure:
- */
-- (void)postPath:(NSString *)path
- parameters:(NSDictionary *)parameters
- success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
-
-/**
- Creates an `AFHTTPRequestOperation` with a `PUT` request, and enqueues it to the HTTP client's operation queue.
-
- @param path The path to be appended to the HTTP client's base URL and used as the request URL.
- @param parameters The parameters to be encoded and set in the request HTTP body.
- @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
- @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
-
- @see -HTTPRequestOperationWithRequest:success:failure:
- */
-- (void)putPath:(NSString *)path
- parameters:(NSDictionary *)parameters
- success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
-
-/**
- Creates an `AFHTTPRequestOperation` with a `DELETE` request, and enqueues it to the HTTP client's operation queue.
-
- @param path The path to be appended to the HTTP client's base URL and used as the request URL.
- @param parameters The parameters to be encoded and appended as the query string for the request URL.
- @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
- @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
-
- @see -HTTPRequestOperationWithRequest:success:failure:
- */
-- (void)deletePath:(NSString *)path
- parameters:(NSDictionary *)parameters
- success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
-
-/**
- Creates an `AFHTTPRequestOperation` with a `PATCH` request, and enqueues it to the HTTP client's operation queue.
-
- @param path The path to be appended to the HTTP client's base URL and used as the request URL.
- @param parameters The parameters to be encoded and set in the request HTTP body.
- @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
- @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred.
-
- @see -HTTPRequestOperationWithRequest:success:failure:
- */
-- (void)patchPath:(NSString *)path
- parameters:(NSDictionary *)parameters
- success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
-@end
-
-///----------------
-/// @name Constants
-///----------------
-
-/**
- ## Network Reachability
-
- The following constants are provided by `AFHTTPClient` as possible network reachability statuses.
-
- enum {
- AFNetworkReachabilityStatusUnknown,
- AFNetworkReachabilityStatusNotReachable,
- AFNetworkReachabilityStatusReachableViaWWAN,
- AFNetworkReachabilityStatusReachableViaWiFi,
- }
-
- `AFNetworkReachabilityStatusUnknown`
- The `baseURL` host reachability is not known.
-
- `AFNetworkReachabilityStatusNotReachable`
- The `baseURL` host cannot be reached.
-
- `AFNetworkReachabilityStatusReachableViaWWAN`
- The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
-
- `AFNetworkReachabilityStatusReachableViaWiFi`
- The `baseURL` host can be reached via a Wi-Fi connection.
-
- ### Keys for Notification UserInfo Dictionary
-
- Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
-
- `AFNetworkingReachabilityNotificationStatusItem`
- A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
- The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
-
- ## Parameter Encoding
-
- The following constants are provided by `AFHTTPClient` as possible methods for serializing parameters into query string or message body values.
-
- enum {
- AFFormURLParameterEncoding,
- AFJSONParameterEncoding,
- AFPropertyListParameterEncoding,
- }
-
- `AFFormURLParameterEncoding`
- Parameters are encoded into field/key pairs in the URL query string for `GET` `HEAD` and `DELETE` requests, and in the message body otherwise. Dictionary keys are sorted with the `caseInsensitiveCompare:` selector of their description, in order to mitigate the possibility of ambiguous query strings being generated non-deterministically. See the warning for the `parameterEncoding` property for additional information.
-
- `AFJSONParameterEncoding`
- Parameters are encoded into JSON in the message body.
-
- `AFPropertyListParameterEncoding`
- Parameters are encoded into a property list in the message body.
- */
-
-///----------------
-/// @name Functions
-///----------------
-
-/**
- Returns a query string constructed by a set of parameters, using the specified encoding.
-
- Query strings are constructed by collecting each key-value pair, percent escaping a string representation of the key-value pair, and then joining the pairs with "&".
-
- If a query string pair has a an `NSArray` for its value, each member of the array will be represented in the format `field[]=value1&field[]value2`. Otherwise, the pair will be formatted as "field=value". String representations of both keys and values are derived using the `-description` method. The constructed query string does not include the ? character used to delimit the query component.
-
- @param parameters The parameters used to construct the query string
- @param encoding The encoding to use in constructing the query string. If you are uncertain of the correct encoding, you should use UTF-8 (`NSUTF8StringEncoding`), which is the encoding designated by RFC 3986 as the correct encoding for use in URLs.
-
- @return A percent-escaped query string
- */
-extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding encoding);
-
-///--------------------
-/// @name Notifications
-///--------------------
-
-/**
- Posted when network reachability changes.
- This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.
-
- @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
- */
-#ifdef _SYSTEMCONFIGURATION_H
-extern NSString * const AFNetworkingReachabilityDidChangeNotification;
-extern NSString * const AFNetworkingReachabilityNotificationStatusItem;
-#endif
-
-#pragma mark -
-
-extern NSUInteger const kAFUploadStream3GSuggestedPacketSize;
-extern NSTimeInterval const kAFUploadStream3GSuggestedDelay;
-
-/**
- The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPClient -multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:`.
- */
-@protocol AFMultipartFormData
-
-/**
- Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary.
-
- The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively.
-
- @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
- @param name The name to be associated with the specified data. This parameter must not be `nil`.
- @param error If an error occurs, upon return contains an `NSError` object that describes the problem.
-
- @return `YES` if the file data was successfully appended, otherwise `NO`.
- */
-- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
- name:(NSString *)name
- error:(NSError * __autoreleasing *)error;
-
-/**
- Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
-
- @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
- @param name The name to be associated with the specified data. This parameter must not be `nil`.
- @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`.
- @param mimeType The declared MIME type of the file data. This parameter must not be `nil`.
- @param error If an error occurs, upon return contains an `NSError` object that describes the problem.
-
- @return `YES` if the file data was successfully appended otherwise `NO`.
- */
-- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
- name:(NSString *)name
- fileName:(NSString *)fileName
- mimeType:(NSString *)mimeType
- error:(NSError * __autoreleasing *)error;
-
-/**
- Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary.
-
- @param inputStream The input stream to be appended to the form data
- @param name The name to be associated with the specified input stream. This parameter must not be `nil`.
- @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`.
- @param length The length of the specified input stream in bytes.
- @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
- */
-- (void)appendPartWithInputStream:(NSInputStream *)inputStream
- name:(NSString *)name
- fileName:(NSString *)fileName
- length:(unsigned long long)length
- mimeType:(NSString *)mimeType;
-
-/**
- Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
-
- @param data The data to be encoded and appended to the form data.
- @param name The name to be associated with the specified data. This parameter must not be `nil`.
- @param fileName The filename to be associated with the specified data. This parameter must not be `nil`.
- @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
- */
-- (void)appendPartWithFileData:(NSData *)data
- name:(NSString *)name
- fileName:(NSString *)fileName
- mimeType:(NSString *)mimeType;
-
-/**
- Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary.
-
- @param data The data to be encoded and appended to the form data.
- @param name The name to be associated with the specified data. This parameter must not be `nil`.
- */
-
-- (void)appendPartWithFormData:(NSData *)data
- name:(NSString *)name;
-
-
-/**
- Appends HTTP headers, followed by the encoded data and the multipart form boundary.
-
- @param headers The HTTP headers to be appended to the form data.
- @param body The data to be encoded and appended to the form data.
- */
-- (void)appendPartWithHeaders:(NSDictionary *)headers
- body:(NSData *)body;
-
-/**
- Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.
-
- When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, as of iOS 6, there is no definite way to distinguish between a 3G, EDGE, or LTE connection. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth.
-
- @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 32kb.
- @param delay Duration of delay each time a packet is read. By default, no delay is set.
- */
-- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
- delay:(NSTimeInterval)delay;
-
-@end
View
84 AFNetworking/AFHTTPRequestOperation.h
@@ -1,6 +1,6 @@
// AFHTTPRequestOperation.h
//
-// Copyright (c) 2011 Gowalla (http://gowalla.com/)
+// Copyright (c) 2013 AFNetworking (http://afnetworking.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -22,88 +22,28 @@
#import <Foundation/Foundation.h>
#import "AFURLConnectionOperation.h"
+#import "AFURLResponseSerialization.h"
/**
`AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.
*/
@interface AFHTTPRequestOperation : AFURLConnectionOperation
-///----------------------------------------------
+///------------------------------------------------
/// @name Getting HTTP URL Connection Information
-///----------------------------------------------
+///------------------------------------------------
/**
The last HTTP response received by the operation's connection.
*/
@property (readonly, nonatomic, strong) NSHTTPURLResponse *response;
-///----------------------------------------------------------
-/// @name Managing And Checking For Acceptable HTTP Responses
-///----------------------------------------------------------
-
-/**
- A Boolean value that corresponds to whether the status code of the response is within the specified set of acceptable status codes. Returns `YES` if `acceptableStatusCodes` is `nil`.
- */
-@property (nonatomic, readonly) BOOL hasAcceptableStatusCode;
-
-/**
- A Boolean value that corresponds to whether the MIME type of the response is among the specified set of acceptable content types. Returns `YES` if `acceptableContentTypes` is `nil`.
- */
-@property (nonatomic, readonly) BOOL hasAcceptableContentType;
-
/**
- The callback dispatch queue on success. If `NULL` (default), the main queue is used.
- */
-@property (nonatomic, assign) dispatch_queue_t successCallbackQueue;
+ Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to a compound serializer, which serializes data from responses with either a `application/json` or `application/x-plist` MIME type, and falls back to the raw data object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed.
-/**
- The callback dispatch queue on failure. If `NULL` (default), the main queue is used.
+ @warning `responseSerializer` must not be `nil`.
*/
-@property (nonatomic, assign) dispatch_queue_t failureCallbackQueue;
-
-///------------------------------------------------------------
-/// @name Managing Acceptable HTTP Status Codes & Content Types
-///------------------------------------------------------------
-
-/**
- Returns an `NSIndexSet` object containing the ranges of acceptable HTTP status codes. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
-
- By default, this is the range 200 to 299, inclusive.
- */
-+ (NSIndexSet *)acceptableStatusCodes;
-
-/**
- Adds status codes to the set of acceptable HTTP status codes returned by `+acceptableStatusCodes` in subsequent calls by this class and its descendants.
-
- @param statusCodes The status codes to be added to the set of acceptable HTTP status codes
- */
-+ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes;
-
-/**
- Returns an `NSSet` object containing the acceptable MIME types. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17
-
- By default, this is `nil`.
- */
-+ (NSSet *)acceptableContentTypes;
-
-/**
- Adds content types to the set of acceptable MIME types returned by `+acceptableContentTypes` in subsequent calls by this class and its descendants.
-
- @param contentTypes The content types to be added to the set of acceptable MIME types
- */
-+ (void)addAcceptableContentTypes:(NSSet *)contentTypes;
-
-
-///-----------------------------------------------------
-/// @name Determining Whether A Request Can Be Processed
-///-----------------------------------------------------
-
-/**
- A Boolean value determining whether or not the class can process the specified request. For example, `AFJSONRequestOperation` may check to make sure the content type was `application/json` or the URL path extension was `.json`.
-
- @param urlRequest The request that is determined to be supported or not supported for this class.
- */
-+ (BOOL)canProcessRequest:(NSURLRequest *)urlRequest;
+@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
///-----------------------------------------------------------
/// @name Setting Completion Block Success / Failure Callbacks
@@ -121,13 +61,3 @@
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
@end
-
-///----------------
-/// @name Functions
-///----------------
-
-/**
- Returns a set of MIME types detected in an HTTP `Accept` or `Content-Type` header.
- */
-extern NSSet * AFContentTypesFromHTTPHeader(NSString *string);
-
View
325 AFNetworking/AFHTTPRequestOperation.m
@@ -1,6 +1,6 @@
// AFHTTPRequestOperation.m
//
-// Copyright (c) 2011 Gowalla (http://gowalla.com/)
+// Copyright (c) 2013 AFNetworking (http://afnetworking.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -21,88 +21,25 @@
// THE SOFTWARE.
#import "AFHTTPRequestOperation.h"
-#import <objc/runtime.h>
-// Workaround for change in imp_implementationWithBlock() with Xcode 4.5
-#if defined(__IPHONE_6_0) || defined(__MAC_10_8)
-#define AF_CAST_TO_BLOCK id
-#else
-#define AF_CAST_TO_BLOCK __bridge void *
-#endif
-
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wstrict-selector-match"
-
-NSSet * AFContentTypesFromHTTPHeader(NSString *string) {
- if (!string) {
- return nil;
- }
-
- NSArray *mediaRanges = [string componentsSeparatedByString:@","];
- NSMutableSet *mutableContentTypes = [NSMutableSet setWithCapacity:mediaRanges.count];
-
- [mediaRanges enumerateObjectsUsingBlock:^(NSString *mediaRange, __unused NSUInteger idx, __unused BOOL *stop) {
- NSRange parametersRange = [mediaRange rangeOfString:@";"];
- if (parametersRange.location != NSNotFound) {
- mediaRange = [mediaRange substringToIndex:parametersRange.location];
- }
-
- mediaRange = [mediaRange stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
-
- if (mediaRange.length > 0) {
- [mutableContentTypes addObject:mediaRange];
- }
- }];
-
- return [NSSet setWithSet:mutableContentTypes];
-}
-
-static void AFGetMediaTypeAndSubtypeWithString(NSString *string, NSString **type, NSString **subtype) {
- if (!string) {
- return;
- }
+static dispatch_queue_t http_request_operation_processing_queue() {
+ static dispatch_queue_t af_http_request_operation_processing_queue;
+ static dispatch_once_t onceToken;
+ dispatch_once(&onceToken, ^{
+ af_http_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.http-request.processing", DISPATCH_QUEUE_CONCURRENT);
+ });
- NSScanner *scanner = [NSScanner scannerWithString:string];
- [scanner setCharactersToBeSkipped:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
- [scanner scanUpToString:@"/" intoString:type];
- [scanner scanString:@"/" intoString:nil];
- [scanner scanUpToString:@";" intoString:subtype];
+ return af_http_request_operation_processing_queue;
}
-static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) {
- NSMutableString *string = [NSMutableString string];
-
- NSRange range = NSMakeRange([indexSet firstIndex], 1);
- while (range.location != NSNotFound) {
- NSUInteger nextIndex = [indexSet indexGreaterThanIndex:range.location];
- while (nextIndex == range.location + range.length) {
- range.length++;
- nextIndex = [indexSet indexGreaterThanIndex:nextIndex];
- }
-
- if (string.length) {
- [string appendString:@","];
- }
-
- if (range.length == 1) {
- [string appendFormat:@"%lu", (long)range.location];
- } else {
- NSUInteger firstIndex = range.location;
- NSUInteger lastIndex = firstIndex + range.length - 1;
- [string appendFormat:@"%lu-%lu", (long)firstIndex, (long)lastIndex];
- }
-
- range.location = nextIndex;
- range.length = 1;
- }
-
- return string;
-}
+static dispatch_group_t http_request_operation_completion_group() {
+ static dispatch_group_t af_http_request_operation_completion_group;
+ static dispatch_once_t onceToken;
+ dispatch_once(&onceToken, ^{
+ af_http_request_operation_completion_group = dispatch_group_create();
+ });
-static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL selector, id block) {
- Method originalMethod = class_getClassMethod(klass, selector);
- IMP implementation = imp_implementationWithBlock((AF_CAST_TO_BLOCK)block);
- class_replaceMethod(objc_getMetaClass([NSStringFromClass(klass) UTF8String]), selector, implementation, method_getTypeEncoding(originalMethod));
+ return af_http_request_operation_completion_group;
}
#pragma mark -
@@ -110,83 +47,63 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
@interface AFHTTPRequestOperation ()
@property (readwrite, nonatomic, strong) NSURLRequest *request;
@property (readwrite, nonatomic, strong) NSHTTPURLResponse *response;
-@property (readwrite, nonatomic, strong) NSError *HTTPError;
-@property (readwrite, nonatomic, strong) NSRecursiveLock *lock;
+@property (readwrite, nonatomic, strong) NSError *error;
@end
@implementation AFHTTPRequestOperation
-@synthesize HTTPError = _HTTPError;
-@synthesize successCallbackQueue = _successCallbackQueue;
-@synthesize failureCallbackQueue = _failureCallbackQueue;
-@dynamic lock;
-@dynamic request;
-@dynamic response;
-- (void)dealloc {
- if (_successCallbackQueue) {
-#if !OS_OBJECT_USE_OBJC
- dispatch_release(_successCallbackQueue);
-#endif
- _successCallbackQueue = NULL;
- }
+- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
+ NSParameterAssert(responseSerializer);
- if (_failureCallbackQueue) {
-#if !OS_OBJECT_USE_OBJC
- dispatch_release(_failureCallbackQueue);
-#endif
- _failureCallbackQueue = NULL;
- }
+ _responseSerializer = responseSerializer;
}
-- (NSError *)error {
- [self.lock lock];
- if (!self.HTTPError && self.response) {
- if (![self hasAcceptableStatusCode] || ![self hasAcceptableContentType]) {
- NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
- [userInfo setValue:self.responseString forKey:NSLocalizedRecoverySuggestionErrorKey];
- [userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
- [userInfo setValue:self.request forKey:AFNetworkingOperationFailingURLRequestErrorKey];
- [userInfo setValue:self.response forKey:AFNetworkingOperationFailingURLResponseErrorKey];
+#pragma mark - AFHTTPRequestOperation
- if (![self hasAcceptableStatusCode]) {
- NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
- [userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected status code in (%@), got %d", @"AFNetworking", nil), AFStringFromIndexSet([[self class] acceptableStatusCodes]), statusCode] forKey:NSLocalizedDescriptionKey];
- self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo];
- } else if (![self hasAcceptableContentType]) {
- // Don't invalidate content type if there is no content
- if ([self.responseData length] > 0) {
- [userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected content type %@, got %@", @"AFNetworking", nil), [[self class] acceptableContentTypes], [self.response MIMEType]] forKey:NSLocalizedDescriptionKey];
- self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
+- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+ // completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle.
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Warc-retain-cycles"
+#pragma clang diagnostic ignored "-Wgnu"
+ self.completionBlock = ^{
+ dispatch_async(http_request_operation_processing_queue(), ^{
+ if (self.error) {
+ if (failure) {
+ dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
+ failure(self, self.error);
+ });
}
- }
- }
- }
- [self.lock unlock];
-
- if (self.HTTPError) {
- return self.HTTPError;
- } else {
- return [super error];
- }
+ } else {
+ NSError *error = nil;
+ id responseObject = [self.responseSerializer responseObjectForResponse:self.response data:self.responseData error:&error];
+
+ if (error) {
+ self.error = error;
+
+ if (failure) {
+ dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
+ failure(self, self.error);
+ });
+ }
+ } else {
+ if (success) {
+ dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
+ success(self, responseObject);
+ });
+ }
+ }
+ }
+ });
+ };
+#pragma clang diagnostic pop
}
-- (NSStringEncoding)responseStringEncoding {
- // When no explicit charset parameter is provided by the sender, media subtypes of the "text" type are defined to have a default charset value of "ISO-8859-1" when received via HTTP. Data in character sets other than "ISO-8859-1" or its subsets MUST be labeled with an appropriate charset value.
- // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.4.1
- if (self.response && !self.response.textEncodingName && self.responseData && [self.response respondsToSelector:@selector(allHeaderFields)]) {
- NSString *type = nil;
- AFGetMediaTypeAndSubtypeWithString([[self.response allHeaderFields] valueForKey:@"Content-Type"], &type, nil);
-
- if ([type isEqualToString:@"text"]) {
- return NSISOLatin1StringEncoding;
- }
- }
-
- return [super responseStringEncoding];
-}
+#pragma mark - AFURLRequestOperation
- (void)pause {
- unsigned long long offset = 0;
+ int64_t offset = 0;
if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) {
offset = [[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue];
} else {
@@ -203,125 +120,37 @@ - (void)pause {
[super pause];
}
-- (BOOL)hasAcceptableStatusCode {
- if (!self.response) {
- return NO;
- }
-
- NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
- return ![[self class] acceptableStatusCodes] || [[[self class] acceptableStatusCodes] containsIndex:statusCode];
-}
+#pragma mark - NSCoding
-- (BOOL)hasAcceptableContentType {
- if (!self.response) {
- return NO;
- }
-
- // Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream".
- // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html
- NSString *contentType = [self.response MIMEType];
- if (!contentType) {
- contentType = @"application/octet-stream";
- }
+- (id)initWithCoder:(NSCoder *)aDecoder {
+ NSURLRequest *request = [aDecoder decodeObjectForKey:@"request"];
- return ![[self class] acceptableContentTypes] || [[[self class] acceptableContentTypes] containsObject:contentType];
-}
-
-- (void)setSuccessCallbackQueue:(dispatch_queue_t)successCallbackQueue {
- if (successCallbackQueue != _successCallbackQueue) {
- if (_successCallbackQueue) {
-#if !OS_OBJECT_USE_OBJC
- dispatch_release(_successCallbackQueue);
-#endif
- _successCallbackQueue = NULL;
- }
-
- if (successCallbackQueue) {
-#if !OS_OBJECT_USE_OBJC
- dispatch_retain(successCallbackQueue);
-#endif
- _successCallbackQueue = successCallbackQueue;
- }
+ self = [self initWithRequest:request];
+ if (!self) {
+ return nil;
}
-}
-- (void)setFailureCallbackQueue:(dispatch_queue_t)failureCallbackQueue {
- if (failureCallbackQueue != _failureCallbackQueue) {
- if (_failureCallbackQueue) {
-#if !OS_OBJECT_USE_OBJC
- dispatch_release(_failureCallbackQueue);
-#endif
- _failureCallbackQueue = NULL;
- }
+ self.responseSerializer = [aDecoder decodeObjectForKey:@"responseSerializer"];
- if (failureCallbackQueue) {
-#if !OS_OBJECT_USE_OBJC
- dispatch_retain(failureCallbackQueue);
-#endif
- _failureCallbackQueue = failureCallbackQueue;
- }
- }
-}
-
-- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
- // completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle.
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Warc-retain-cycles"
-#pragma clang diagnostic ignored "-Wgnu"
- self.completionBlock = ^{
- if (self.error) {
- if (failure) {
- dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
- failure(self, self.error);
- });
- }
- } else {
- if (success) {
- dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
- success(self, self.responseData);
- });
- }
- }
- };
-#pragma clang diagnostic pop
+ return self;
}
-#pragma mark - AFHTTPRequestOperation
+- (void)encodeWithCoder:(NSCoder *)aCoder {
+ [super encodeWithCoder:aCoder];
-+ (NSIndexSet *)acceptableStatusCodes {
- return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
+ [aCoder encodeObject:self.responseSerializer forKey:@"responseSerializer"];
}
-+ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes {
- NSMutableIndexSet *mutableStatusCodes = [[NSMutableIndexSet alloc] initWithIndexSet:[self acceptableStatusCodes]];
- [mutableStatusCodes addIndexes:statusCodes];
- AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableStatusCodes), ^(__unused id _self) {
- return mutableStatusCodes;
- });
-}
+#pragma mark - NSCopying
-+ (NSSet *)acceptableContentTypes {
- return nil;
-}
+- (id)copyWithZone:(NSZone *)zone {
+ AFHTTPRequestOperation *operation = [[[self class] allocWithZone:zone] initWithRequest:self.request];
-+ (void)addAcceptableContentTypes:(NSSet *)contentTypes {
- NSMutableSet *mutableContentTypes = [[NSMutableSet alloc] initWithSet:[self acceptableContentTypes] copyItems:YES];
- [mutableContentTypes unionSet:contentTypes];
- AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableContentTypes), ^(__unused id _self) {
- return mutableContentTypes;
- });
-}
+ operation.responseSerializer = [self.responseSerializer copyWithZone:zone];
+ operation.completionQueue = self.completionQueue;
+ operation.completionGroup = self.completionGroup;
-+ (BOOL)canProcessRequest:(NSURLRequest *)request {
- if ([[self class] isEqual:[AFHTTPRequestOperation class]]) {
- return YES;
- }
-
- return [[self acceptableContentTypes] intersectsSet:AFContentTypesFromHTTPHeader([request valueForHTTPHeaderField:@"Accept"])];
+ return operation;
}
@end
-
-#pragma clang diagnostic pop
View
276 AFNetworking/AFHTTPRequestOperationManager.h
@@ -0,0 +1,276 @@
+// AFHTTPRequestOperationManager.h
+//
+// Copyright (c) 2013 AFNetworking (http://afnetworking.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+#import <SystemConfiguration/SystemConfiguration.h>
+#import <Availability.h>
+
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+#import <MobileCoreServices/MobileCoreServices.h>
+#else
+#import <CoreServices/CoreServices.h>
+#endif
+
+#import "AFHTTPRequestOperation.h"
+#import "AFURLResponseSerialization.h"
+#import "AFURLRequestSerialization.h"
+#import "AFSecurityPolicy.h"
+#import "AFNetworkReachabilityManager.h"
+
+/**
+ `AFHTTPRequestOperationManager` encapsulates the common patterns of communicating with an web application over HTTP, including request creation, response serialization, network reachability monitoring, and security, as well as both request operation and session task management.
+
+ ## Subclassing Notes
+
+ Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application.
+
+ For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect.
+
+ ## Methods to Override
+
+ To change the behavior of all request operation construction for an `AFHTTPRequestOperationManager` subclass, override `HTTPRequestOperationWithRequest:success:failure`.
+
+ ## Serialization
+
+ Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to `<AFURLRequestSerialization>`.
+
+ Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<AFURLResponseSerialization>`
+
+ ## URL Construction Using Relative Paths
+
+ For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`.
+
+ Below are a few examples of how `baseURL` and relative paths interact:
+
+ NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
+ [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo
+ [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz
+ [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo
+ [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo
+ [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/
+ [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
+
+ Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.
+
+ ## Network Reachability Monitoring
+
+ Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details.
+
+ ## NSCoding & NSCopying Caveats
+
+ `AFHTTPClient` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however:
+
+ - Archives and copies of HTTP clients will be initialized with an empty operation queue.
+ - NSCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set.
+ */
+@interface AFHTTPRequestOperationManager : NSObject <NSCoding, NSCopying>
+
+/**
+ The URL used to monitor reachability, and construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods.
+ */
+@property (readonly, nonatomic, strong) NSURL *baseURL;
+
+/**
+ Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies.
+
+ @warning `requestSerializer` must not be `nil`.
+ */
+@property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;
+
+/**
+ Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to a compound serializer, which serializes data from responses with either a `application/json` or `application/x-plist` MIME type, and falls back to the raw data object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed.
+
+ @warning `responseSerializer` must not be `nil`.
+ */
+@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
+
+/**
+ The operation queue on which request operations are scheduled and run.
+ */
+@property (nonatomic, strong) NSOperationQueue *operationQueue;
+
+///-------------------------------
+/// @name Managing Security Policy
+///-------------------------------
+
+/**
+ The security policy used by created request operations to evaluate server trust for secure connections. `AFHTTPRequestOperationManager` uses the `defaultPolicy` unless otherwise specified.
+ */
+@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
+
+///------------------------------------
+/// @name Managing Network Reachability
+///------------------------------------
+
+/**
+ The network reachability manager. `AFHTTPRequestOperationManager` uses the `sharedManager` by default.
+ */
+@property (readonly, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
+
+///---------------------------------------------
+/// @name Creating and Initializing HTTP Clients
+///---------------------------------------------
+
+/**
+ Creates and returns an `AFHTTPClient` object.
+ */
++ (instancetype)manager;
+
+/**
+ Initializes an `AFHTTPClient` object with the specified base URL.
+
+ This is the designated initializer.
+
+ @param url The base URL for the HTTP client.
+
+ @return The newly-initialized HTTP client
+ */
+- (instancetype)initWithBaseURL:(NSURL *)url;
+
+///---------------------------------------
+/// @name Managing HTTP Request Operations
+///---------------------------------------
+
+/**
+ Creates an `AFHTTPRequestOperation`, setting the operation's request serializer and response serializers to those of the HTTP client.
+
+ @param request The request object to be loaded asynchronously during execution of the operation.
+ @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
+ */
+- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
+
+///---------------------------
+/// @name Making HTTP Requests
+///---------------------------
+
+/**
+ Creates and runs an `AFHTTPRequestOperation` with a `GET` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
+
+ @see -HTTPRequestOperationWithRequest:success:failure:
+ */
+- (AFHTTPRequestOperation *)GET:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
+
+/**
+ Creates and runs an `AFHTTPRequestOperation` with a `HEAD` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes a single arguments: the request operation.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
+
+ @see -HTTPRequestOperationWithRequest:success:failure:
+ */
+- (AFHTTPRequestOperation *)HEAD:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
+
+/**
+ Creates and runs an `AFHTTPRequestOperation` with a `POST` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
+
+ @see -HTTPRequestOperationWithRequest:success:failure:
+ */
+- (AFHTTPRequestOperation *)POST:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
+
+/**
+ Creates and runs an `AFHTTPRequestOperation` with a multipart `POST` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
+
+ @see -HTTPRequestOperationWithRequest:success:failure:
+ */
+- (AFHTTPRequestOperation *)POST:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
+
+/**
+ Creates and runs an `AFHTTPRequestOperation` with a `PUT` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
+
+ @see -HTTPRequestOperationWithRequest:success:failure:
+ */
+- (AFHTTPRequestOperation *)PUT:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
+
+/**
+ Creates and runs an `AFHTTPRequestOperation` with a `PATCH` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
+
+ @see -HTTPRequestOperationWithRequest:success:failure:
+ */
+- (AFHTTPRequestOperation *)PATCH:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
+
+/**
+ Creates and runs an `AFHTTPRequestOperation` with a `DELETE` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
+
+ @see -HTTPRequestOperationWithRequest:success:failure:
+ */
+- (AFHTTPRequestOperation *)DELETE:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
+
+@end
+
View
235 AFNetworking/AFHTTPRequestOperationManager.m
@@ -0,0 +1,235 @@
+// AFHTTPRequestOperationManager.m
+//
+// Copyright (c) 2013 AFNetworking (http://afnetworking.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+
+#import "AFHTTPRequestOperationManager.h"
+#import "AFHTTPRequestOperation.h"
+
+#import <Availability.h>
+#import <Security/Security.h>
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+#import <UIKit/UIKit.h>
+#endif
+
+@interface AFHTTPRequestOperationManager ()
+@property (readwrite, nonatomic, strong) NSURL *baseURL;
+@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
+@end
+
+@implementation AFHTTPRequestOperationManager
+
++ (instancetype)manager {
+ return [[AFHTTPRequestOperationManager alloc] initWithBaseURL:nil];
+}
+
+- (instancetype)initWithBaseURL:(NSURL *)url {
+ self = [super init];
+ if (!self) {
+ return nil;
+ }
+
+ // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected
+ if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
+ url = [url URLByAppendingPathComponent:@""];
+ }
+
+ self.baseURL = url;
+
+ self.requestSerializer = [AFHTTPRequestSerializer serializer];
+ self.responseSerializer = [AFJSONResponseSerializer serializer];
+
+ self.securityPolicy = [AFSecurityPolicy defaultPolicy];
+
+ if (self.baseURL.host) {
+ self.reachabilityManager = [AFNetworkReachabilityManager managerForDomain:self.baseURL.host];
+ } else {
+ self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
+ }
+
+ self.operationQueue = [[NSOperationQueue alloc] init];
+
+ return self;
+}
+
+- (NSString *)description {
+ return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.operationQueue];
+}
+
+#pragma mark -
+
+#ifdef _SYSTEMCONFIGURATION_H
+#endif
+
+- (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer {
+ NSParameterAssert(requestSerializer);
+
+ _requestSerializer = requestSerializer;
+}
+
+- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
+ NSParameterAssert(responseSerializer);
+
+ _responseSerializer = responseSerializer;
+}
+
+#pragma mark -
+
+- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+ AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
+ operation.responseSerializer = self.responseSerializer;
+ operation.securityPolicy = self.securityPolicy;
+
+ [operation setCompletionBlockWithSuccess:success failure:failure];
+
+ return operation;
+}
+
+#pragma mark -
+
+- (AFHTTPRequestOperation *)GET:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+ NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"GET" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters];
+ AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
+ [self.operationQueue addOperation:operation];
+
+ return operation;
+}
+
+- (AFHTTPRequestOperation *)HEAD:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+ NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"HEAD" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters];
+ AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *requestOperation, __unused id responseObject) {
+ if (success) {
+ success(requestOperation);
+ }
+ } failure:failure];
+ [self.operationQueue addOperation:operation];
+
+ return operation;
+}
+
+- (AFHTTPRequestOperation *)POST:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+ NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters];
+ AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
+ [self.operationQueue addOperation:operation];
+
+ return operation;
+}
+
+- (AFHTTPRequestOperation *)POST:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+ NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block];
+ AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
+ [self.operationQueue addOperation:operation];
+
+ return operation;
+}
+
+- (AFHTTPRequestOperation *)PUT:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+ NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"PUT" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters];
+ AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
+ [self.operationQueue addOperation:operation];
+
+ return operation;
+}
+
+- (AFHTTPRequestOperation *)PATCH:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+ NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"PATCH" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters];
+ AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
+ [self.operationQueue addOperation:operation];
+
+ return operation;
+}
+
+- (AFHTTPRequestOperation *)DELETE:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+ NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"DELETE" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters];
+ AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
+ [self.operationQueue addOperation:operation];
+
+ return operation;
+}
+
+#pragma mark - NSCoding
+
+- (id)initWithCoder:(NSCoder *)aDecoder {
+ NSURL *baseURL = [aDecoder decodeObjectForKey:@"baseURL"];
+
+ self = [self initWithBaseURL:baseURL];
+ if (!self) {
+ return nil;
+ }
+
+ self.requestSerializer = [aDecoder decodeObjectForKey:@"requestSerializer"];
+ self.responseSerializer = [aDecoder decodeObjectForKey:@"responseSerializer"];
+
+ return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)aCoder {
+ [aCoder encodeObject:self.baseURL forKey:@"baseURL"];
+ [aCoder encodeObject:self.requestSerializer forKey:@"requestSerializer"];
+ [aCoder encodeObject:self.responseSerializer forKey:@"responseSerializer"];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+ AFHTTPRequestOperationManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL];
+
+ HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone];
+ HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone];
+
+ return HTTPClient;
+}
+
+@end
View
234 AFNetworking/AFHTTPSessionManager.h
@@ -0,0 +1,234 @@
+// AFHTTPSessionManager.h
+//
+// Copyright (c) 2013 AFNetworking (http://afnetworking.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+#import <SystemConfiguration/SystemConfiguration.h>
+#import <Availability.h>
+
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+#import <MobileCoreServices/MobileCoreServices.h>
+#else
+#import <CoreServices/CoreServices.h>
+#endif
+
+#import "AFURLSessionManager.h"
+
+/**
+ `AFHTTPSessionManager` is a subclass of `AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths; network reachability is also scoped to the host of the base URL as well.
+
+ ## Subclassing Notes
+
+ Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application.
+
+ For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect.
+
+ ## Methods to Override
+
+ To change the behavior of all data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:completionHandler:`.
+
+ ## Serialization
+
+ Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to `<AFURLRequestSerialization>`.
+
+ Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<AFURLResponseSerialization>`
+
+ ## URL Construction Using Relative Paths
+
+ For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`.
+
+ Below are a few examples of how `baseURL` and relative paths interact:
+
+ NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
+ [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo
+ [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz
+ [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo
+ [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo
+ [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/
+ [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
+
+ Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.
+ */
+@interface AFHTTPSessionManager : AFURLSessionManager <NSCoding, NSCopying>
+
+/**
+ The URL used to monitor reachability, and construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods.
+ */
+@property (readonly, nonatomic, strong) NSURL *baseURL;
+
+/**
+ Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies.
+
+ @warning `requestSerializer` must not be `nil`.
+ */
+@property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;
+
+/**
+ Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to a compound serializer, which serializes data from responses with either a `application/json` or `application/x-plist` MIME type, and falls back to the raw data object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed.
+
+ @warning `responseSerializer` must not be `nil`.
+ */
+@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
+
+///---------------------------------------------
+/// @name Creating and Initializing HTTP Clients
+///---------------------------------------------
+
+/**
+ Creates and returns an `AFHTTPSessionManager` object.
+ */
++ (instancetype)manager;
+
+/**
+ Initializes an `AFHTTPSessionManager` object with the specified base URL.
+
+ @param url The base URL for the HTTP client.
+
+ @return The newly-initialized HTTP client
+ */
+- (instancetype)initWithBaseURL:(NSURL *)url;
+
+/**
+ Initializes an `AFHTTPSessionManager` object with the specified base URL.
+
+ This is the designated initializer.
+
+ @param url The base URL for the HTTP client.
+ @param configuration The configuration used to create the managed session.
+
+ @return The newly-initialized HTTP client
+ */
+- (instancetype)initWithBaseURL:(NSURL *)url
+ sessionConfiguration:(NSURLSessionConfiguration *)configuration;
+
+///---------------------------
+/// @name Making HTTP Requests
+///---------------------------
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a `GET` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
+
+ @see -dataTaskWithRequest:completionHandler:
+ */
+- (NSURLSessionDataTask *)GET:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
+ failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a `HEAD` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes a single arguments: the data task.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
+
+ @see -dataTaskWithRequest:completionHandler:
+ */
+- (NSURLSessionDataTask *)HEAD:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(NSURLSessionDataTask *task))success
+ failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a `POST` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
+
+ @see -dataTaskWithRequest:completionHandler:
+ */
+- (NSURLSessionDataTask *)POST:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
+ failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
+
+ @see -dataTaskWithRequest:completionHandler:
+ */
+- (NSURLSessionDataTask *)POST:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
+ success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
+ failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a `PUT` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
+
+ @see -dataTaskWithRequest:completionHandler:
+ */
+- (NSURLSessionDataTask *)PUT:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
+ failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a `PATCH` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
+
+ @see -dataTaskWithRequest:completionHandler:
+ */
+- (NSURLSessionDataTask *)PATCH:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
+ failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
+
+/**
+ Creates and runs an `NSURLSessionDataTask` with a `DELETE` request.
+
+ @param URLString The URL string used to create the request URL.
+ @param parameters The parameters to be encoded according to the client request serializer.
+ @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
+ @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
+
+ @see -dataTaskWithRequest:completionHandler:
+ */
+- (NSURLSessionDataTask *)DELETE:(NSString *)URLString
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
+ failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
+
+@end
+
View
315 AFNetworking/AFHTTPSessionManager.m
@@ -0,0 +1,315 @@
+// AFHTTPSessionManager.m
+//
+// Copyright (c) 2013 AFNetworking (http://afnetworking.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+
+#import "AFHTTPSessionManager.h"
+#import "AFHTTPRequestOperation.h"
+
+#import <Availability.h>
+#import <Security/Security.h>
+
+#ifdef _SYSTEMCONFIGURATION_H
+#import <netinet/in.h>
+#import <netinet6/in6.h>
+#import <arpa/inet.h>
+#import <ifaddrs.h>
+#import <netdb.h>
+#endif
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+#import <UIKit/UIKit.h>
+#endif
+
+@interface AFHTTPSessionManager ()
+@property (readwrite, nonatomic, strong) NSURL *baseURL;
+@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
+@end
+
+@implementation AFHTTPSessionManager
+
++ (instancetype)manager {
+ return [[AFHTTPSessionManager alloc] initWithBaseURL:nil];
+}
+
+- (instancetype)initWithBaseURL:(NSURL *)url {
+ return [self initWith