Sfoglia il codice sorgente

Merge branch 2.0 into master

Mattt Thompson 12 anni fa
parent
commit
9a40c0dc0f
97 ha cambiato i file con 7429 aggiunte e 3659 eliminazioni
  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/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 0
      Tests/Tests/1.0 Tests/AFMockURLProtocol.h
  71. 0 0
      Tests/Tests/1.0 Tests/AFMockURLProtocol.m
  72. 1 0
      Tests/Tests/1.0 Tests/AFNetworkingTests.h
  73. 0 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
      UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h
  85. 25 20
      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
      UIKit+AFNetworking/UIImageView+AFNetworking.h
  93. 55 45
      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

+ 0 - 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

+ 49 - 24
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

+ 93 - 27
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

+ 0 - 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

+ 7 - 77
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);
-

+ 77 - 248
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 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
     [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

+ 276 - 0
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
+

+ 235 - 0
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

+ 234 - 0
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
+

+ 315 - 0
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 initWithBaseURL:url sessionConfiguration:nil];
+}
+
+- (instancetype)initWithBaseURL:(NSURL *)url
+           sessionConfiguration:(NSURLSessionConfiguration *)configuration
+{
+    self = [super initWithSessionConfiguration:configuration];
+    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];
+    }
+
+    return self;
+}
+
+- (NSString *)description {
+    return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue];
+}
+
+#pragma mark -
+
+#ifdef _SYSTEMCONFIGURATION_H
+#endif
+
+- (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer {
+    NSParameterAssert(requestSerializer);
+
+    _requestSerializer = requestSerializer;
+}
+
+- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
+    NSParameterAssert(responseSerializer);
+
+    [super setResponseSerializer:responseSerializer];
+}
+
+#pragma mark -
+
+- (NSURLSessionDataTask *)GET:(NSString *)URLString
+                   parameters:(NSDictionary *)parameters
+                      success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
+                      failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
+{
+    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"GET" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters];
+
+    __block NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
+        if (error) {
+            if (failure) {
+                failure(task, error);
+            }
+        } else {
+            if (success) {
+                success(task, responseObject);
+            }
+        }
+    }];
+
+    [task resume];
+
+    return task;
+}
+
+- (NSURLSessionDataTask *)HEAD:(NSString *)URLString
+                    parameters:(NSDictionary *)parameters
+                       success:(void (^)(NSURLSessionDataTask *task))success
+                       failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
+{
+    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"HEAD" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters];
+
+    __block NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
+        if (error) {
+            if (failure) {
+                failure(task, error);
+            }
+        } else {
+            if (success) {
+                success(task);
+            }
+        }
+    }];
+
+    [task resume];
+
+    return task;
+}
+
+- (NSURLSessionDataTask *)POST:(NSString *)URLString
+                    parameters:(NSDictionary *)parameters
+                       success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
+                       failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
+{
+    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters];
+
+    __block NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
+        if (error) {
+            if (failure) {
+                failure(task, error);
+            }
+        } else {
+            if (success) {
+                success(task, responseObject);
+            }
+        }
+    }];
+
+    [task resume];
+
+    return task;
+}
+
+- (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
+{
+    NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block];
+
+    __block NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
+        if (error) {
+            if (failure) {
+                failure(task, error);
+            }
+        } else {
+            if (success) {
+                success(task, responseObject);
+            }
+        }
+    }];
+
+    [task resume];
+
+    return task;
+}
+
+- (NSURLSessionDataTask *)PUT:(NSString *)URLString
+                   parameters:(NSDictionary *)parameters
+                      success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
+                      failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
+{
+    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"PUT" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters];
+
+    __block NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
+        if (error) {
+            if (failure) {
+                failure(task, error);
+            }
+        } else {
+            if (success) {
+                success(task, responseObject);
+            }
+        }
+    }];
+
+    [task resume];
+
+    return task;
+}
+
+- (NSURLSessionDataTask *)PATCH:(NSString *)URLString
+                     parameters:(NSDictionary *)parameters
+                        success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
+                        failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
+{
+    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"PATCH" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters];
+
+    __block NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
+        if (error) {
+            if (failure) {
+                failure(task, error);
+            }
+        } else {
+            if (success) {
+                success(task, responseObject);
+            }
+        }
+    }];
+    
+    [task resume];
+
+    return task;
+}
+
+- (NSURLSessionDataTask *)DELETE:(NSString *)URLString
+                      parameters:(NSDictionary *)parameters
+                         success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
+                         failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
+{
+    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"DELETE" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters];
+
+    __block NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
+        if (error) {
+            if (failure) {
+                failure(task, error);
+            }
+        } else {
+            if (success) {
+                success(task, responseObject);
+            }
+        }
+    }];
+
+    [task resume];
+
+    return task;
+}
+
+#pragma mark - NSCoding
+
+- (id)initWithCoder:(NSCoder *)aDecoder {
+    NSURL *baseURL = [aDecoder decodeObjectForKey:@"baseURL"];
+    NSURLSessionConfiguration *configuration = [aDecoder decodeObjectForKey:@"sessionConfiguration"];
+
+    self = [self initWithBaseURL:baseURL sessionConfiguration:configuration];
+    if (!self) {
+        return nil;
+    }
+
+    self.requestSerializer = [aDecoder decodeObjectForKey:@"requestSerializer"];
+    self.responseSerializer = [aDecoder decodeObjectForKey:@"responseSerializer"];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)aCoder {
+    [super encodeWithCoder: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 {
+    AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration];
+
+    HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone];
+    HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone];
+    
+    return HTTPClient;
+}
+
+@end

+ 0 - 113
AFNetworking/AFImageRequestOperation.h

@@ -1,113 +0,0 @@
-// AFImageRequestOperation.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 "AFHTTPRequestOperation.h"
-
-#import <Availability.h>
-
-#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-#import <UIKit/UIKit.h>
-#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
-#import <Cocoa/Cocoa.h>
-#endif
-
-/**
- `AFImageRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and processing images.
-
- ## Acceptable Content Types
-
- By default, `AFImageRequestOperation` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
-
- - `image/tiff`
- - `image/jpeg`
- - `image/gif`
- - `image/png`
- - `image/ico`
- - `image/x-icon`
- - `image/bmp`
- - `image/x-bmp`
- - `image/x-xbitmap`
- - `image/x-win-bitmap`
- */
-@interface AFImageRequestOperation : AFHTTPRequestOperation
-
-/**
- An image constructed from the response data. If an error occurs during the request, `nil` will be returned, and the `error` property will be set to the error.
- */
-#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-@property (readonly, nonatomic, strong) UIImage *responseImage;
-#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
-@property (readonly, nonatomic, strong) NSImage *responseImage;
-#endif
-
-#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-/**
- The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance.
- */
-@property (nonatomic, assign) CGFloat imageScale;
-
-/**
- Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default.
- */
-@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage;
-#endif
-
-/**
- Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
-
- @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 finishes successfully. This block has no return value and takes a single argument, the image created from the response data of the request.
-
- @return A new image request operation
- */
-#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
-										 success:(void (^)(UIImage *image))success;
-#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
-+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
-										 success:(void (^)(NSImage *image))success;
-#endif
-
-/**
- Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
-
- @param urlRequest The request object to be loaded asynchronously during execution of the operation.
- @param imageProcessingBlock A block object to be executed after the image request finishes successfully, but before the image is returned in the `success` block. This block takes a single argument, the image loaded from the response body, and returns the processed image.
- @param success A block object to be executed when the request finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the image created from the response data.
- @param failure A block object to be executed when the request finishes unsuccessfully. This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the error associated with the cause for the unsuccessful operation.
-
- @return A new image request operation
- */
-#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
-							imageProcessingBlock:(UIImage *(^)(UIImage *image))imageProcessingBlock
-										 success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
-										 failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
-#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
-+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
-							imageProcessingBlock:(NSImage *(^)(NSImage *image))imageProcessingBlock
-										 success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success
-										 failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
-#endif
-
-@end

+ 0 - 321
AFNetworking/AFImageRequestOperation.m

@@ -1,321 +0,0 @@
-// AFImageRequestOperation.m
-//
-// 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 "AFImageRequestOperation.h"
-
-static dispatch_queue_t image_request_operation_processing_queue() {
-    static dispatch_queue_t af_image_request_operation_processing_queue;
-    static dispatch_once_t onceToken;
-    dispatch_once(&onceToken, ^{
-        af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.image-request.processing", DISPATCH_QUEUE_CONCURRENT);
-    });
-
-    return af_image_request_operation_processing_queue;
-}
-
-#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-#import <CoreGraphics/CoreGraphics.h>
-
-static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) {
-    UIImage *image = [[UIImage alloc] initWithData:data];
-    
-    return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation];
-}
-
-static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) {
-    if (!data || [data length] == 0) {
-        return nil;
-    }
-
-    UIImage *image = AFImageWithDataAtScale(data, scale);
-    if (image.images) {
-        return image;
-    }
-    
-    CGImageRef imageRef = nil;
-    CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
-
-    if ([response.MIMEType isEqualToString:@"image/png"]) {
-        imageRef = CGImageCreateWithPNGDataProvider(dataProvider,  NULL, true, kCGRenderingIntentDefault);
-    } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) {
-        imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
-    }
-    
-    if (!imageRef) {
-        imageRef = CGImageCreateCopy([image CGImage]);
-
-        if (!imageRef) {
-            CGDataProviderRelease(dataProvider);
-            return image;
-        }
-    }
-
-    CGDataProviderRelease(dataProvider);
-
-    size_t width = CGImageGetWidth(imageRef);
-    size_t height = CGImageGetHeight(imageRef);
-    size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
-    size_t bytesPerRow = 0; // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate()
-    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
-    CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
-
-    if (CGColorSpaceGetNumberOfComponents(colorSpace) == 3) {
-        int alpha = (bitmapInfo & kCGBitmapAlphaInfoMask);
-        if (alpha == kCGImageAlphaNone) {
-            bitmapInfo &= ~kCGBitmapAlphaInfoMask;
-            bitmapInfo |= kCGImageAlphaNoneSkipFirst;
-        } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) {
-            bitmapInfo &= ~kCGBitmapAlphaInfoMask;
-            bitmapInfo |= kCGImageAlphaPremultipliedFirst;
-        }
-    }
-
-    CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
-
-    CGColorSpaceRelease(colorSpace);
-
-    if (!context) {
-        CGImageRelease(imageRef);
-
-        return image;
-    }
-
-    CGRect rect = CGRectMake(0.0f, 0.0f, width, height);
-    CGContextDrawImage(context, rect, imageRef);
-    CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context);
-    CGContextRelease(context);
-
-    UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation];
-    CGImageRelease(inflatedImageRef);
-    CGImageRelease(imageRef);
-    
-    return inflatedImage;
-}
-#endif
-
-@interface AFImageRequestOperation ()
-#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-@property (readwrite, nonatomic, strong) UIImage *responseImage;
-#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
-@property (readwrite, nonatomic, strong) NSImage *responseImage;
-#endif
-@end
-
-@implementation AFImageRequestOperation
-@synthesize responseImage = _responseImage;
-#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-@synthesize imageScale = _imageScale;
-#endif
-
-#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
-										 success:(void (^)(UIImage *image))success
-{
-    return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) {
-        if (success) {
-            success(image);
-        }
-    } failure:nil];
-}
-#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
-+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
-										 success:(void (^)(NSImage *image))success
-{
-    return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) {
-        if (success) {
-            success(image);
-        }
-    } failure:nil];
-}
-#endif
-
-
-#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
-							imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock
-										 success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
-										 failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
-{
-    AFImageRequestOperation *requestOperation = [(AFImageRequestOperation *)[self alloc] initWithRequest:urlRequest];
-    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
-        if (success) {
-            UIImage *image = responseObject;
-            if (imageProcessingBlock) {
-                dispatch_async(image_request_operation_processing_queue(), ^(void) {
-                    UIImage *processedImage = imageProcessingBlock(image);
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wgnu"
-                    dispatch_async(operation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) {
-                        success(operation.request, operation.response, processedImage);
-                    });
-#pragma clang diagnostic pop
-                });
-            } else {
-                success(operation.request, operation.response, image);
-            }
-        }
-    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
-        if (failure) {
-            failure(operation.request, operation.response, error);
-        }
-    }];
-
-
-    return requestOperation;
-}
-#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
-+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
-							imageProcessingBlock:(NSImage *(^)(NSImage *))imageProcessingBlock
-										 success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success
-										 failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
-{
-    AFImageRequestOperation *requestOperation = [(AFImageRequestOperation *)[self alloc] initWithRequest:urlRequest];
-    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
-        if (success) {
-            NSImage *image = responseObject;
-            if (imageProcessingBlock) {
-                dispatch_async(image_request_operation_processing_queue(), ^(void) {
-                    NSImage *processedImage = imageProcessingBlock(image);
-
-                    dispatch_async(operation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) {
-                        success(operation.request, operation.response, processedImage);
-                    });
-                });
-            } else {
-                success(operation.request, operation.response, image);
-            }
-        }
-    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
-        if (failure) {
-            failure(operation.request, operation.response, error);
-        }
-    }];
-
-    return requestOperation;
-}
-#endif
-
-- (id)initWithRequest:(NSURLRequest *)urlRequest {
-    self = [super initWithRequest:urlRequest];
-    if (!self) {
-        return nil;
-    }
-
-#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-    self.imageScale = [[UIScreen mainScreen] scale];
-    self.automaticallyInflatesResponseImage = YES;
-#endif
-
-    return self;
-}
-
-
-#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-- (UIImage *)responseImage {
-    if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) {
-        if (self.automaticallyInflatesResponseImage) {
-            self.responseImage = AFInflatedImageFromResponseWithDataAtScale(self.response, self.responseData, self.imageScale);
-        } else {
-            self.responseImage = AFImageWithDataAtScale(self.responseData, self.imageScale);
-        }
-    }
-
-    return _responseImage;
-}
-
-- (void)setImageScale:(CGFloat)imageScale {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wfloat-equal"
-    if (imageScale == _imageScale) {
-        return;
-    }
-#pragma clang diagnostic pop
-
-    _imageScale = imageScale;
-
-    self.responseImage = nil;
-}
-#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
-- (NSImage *)responseImage {
-    if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) {
-        // Ensure that the image is set to it's correct pixel width and height
-        NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:self.responseData];
-        self.responseImage = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
-        [self.responseImage addRepresentation:bitimage];
-    }
-
-    return _responseImage;
-}
-#endif
-
-#pragma mark - AFHTTPRequestOperation
-
-+ (NSSet *)acceptableContentTypes {
-    return [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
-}
-
-+ (BOOL)canProcessRequest:(NSURLRequest *)request {
-    static NSSet * _acceptablePathExtension = nil;
-    static dispatch_once_t onceToken;
-    dispatch_once(&onceToken, ^{
-        _acceptablePathExtension = [[NSSet alloc] initWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil];
-    });
-
-    return [_acceptablePathExtension containsObject:[[request URL] pathExtension]] || [super canProcessRequest:request];
-}
-
-- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
-                              failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Warc-retain-cycles"
-#pragma clang diagnostic ignored "-Wgnu"
-
-    self.completionBlock = ^ {
-        dispatch_async(image_request_operation_processing_queue(), ^(void) {
-            if (self.error) {
-                if (failure) {
-                    dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
-                        failure(self, self.error);
-                    });
-                }
-            } else {
-                if (success) {
-#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-                    UIImage *image = nil;
-#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
-                    NSImage *image = nil;
-#endif
-
-                    image = self.responseImage;
-
-                    dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
-                        success(self, image);
-                    });
-                }
-            }
-        });
-    };
-#pragma clang diagnostic pop
-}
-
-@end

+ 0 - 71
AFNetworking/AFJSONRequestOperation.h

@@ -1,71 +0,0 @@
-// AFJSONRequestOperation.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 "AFHTTPRequestOperation.h"
-
-/**
- `AFJSONRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with JSON response data.
- 
- ## Acceptable Content Types
- 
- By default, `AFJSONRequestOperation` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types:
- 
- - `application/json`
- - `text/json`
-
- @warning JSON parsing will use the built-in `NSJSONSerialization` class.
- */
-@interface AFJSONRequestOperation : AFHTTPRequestOperation
-
-///----------------------------
-/// @name Getting Response Data
-///----------------------------
-
-/**
- A JSON object constructed from the response data. If an error occurs while parsing, `nil` will be returned, and the `error` property will be set to the error.
- */
-@property (readonly, nonatomic, strong) id responseJSON;
-
-/**
- Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions".
- */
-@property (nonatomic, assign) NSJSONReadingOptions JSONReadingOptions;
- 
-///----------------------------------
-/// @name Creating Request Operations
-///----------------------------------
-
-/**
- Creates and returns an `AFJSONRequestOperation` object and sets the specified success and failure callbacks.
- 
- @param urlRequest The request object to be loaded asynchronously during execution of the operation
- @param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the JSON object created from the response data of request.
- @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data as JSON. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred.
-  
- @return A new JSON request operation
- */
-+ (instancetype)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
-                                        success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
-                                        failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure;
-
-@end

+ 0 - 150
AFNetworking/AFJSONRequestOperation.m

@@ -1,150 +0,0 @@
-// AFJSONRequestOperation.m
-//
-// 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 "AFJSONRequestOperation.h"
-
-static dispatch_queue_t json_request_operation_processing_queue() {
-    static dispatch_queue_t af_json_request_operation_processing_queue;
-    static dispatch_once_t onceToken;
-    dispatch_once(&onceToken, ^{
-        af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.json-request.processing", DISPATCH_QUEUE_CONCURRENT);
-    });
-
-    return af_json_request_operation_processing_queue;
-}
-
-@interface AFJSONRequestOperation ()
-@property (readwrite, nonatomic, strong) id responseJSON;
-@property (readwrite, nonatomic, strong) NSError *JSONError;
-@property (readwrite, nonatomic, strong) NSRecursiveLock *lock;
-@end
-
-@implementation AFJSONRequestOperation
-@synthesize responseJSON = _responseJSON;
-@synthesize JSONReadingOptions = _JSONReadingOptions;
-@synthesize JSONError = _JSONError;
-@dynamic lock;
-
-+ (instancetype)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
-										success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
-										failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure
-{
-    AFJSONRequestOperation *requestOperation = [(AFJSONRequestOperation *)[self alloc] initWithRequest:urlRequest];
-    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
-        if (success) {
-            success(operation.request, operation.response, responseObject);
-        }
-    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
-        if (failure) {
-            failure(operation.request, operation.response, error, [(AFJSONRequestOperation *)operation responseJSON]);
-        }
-    }];
-
-    return requestOperation;
-}
-
-
-- (id)responseJSON {
-    [self.lock lock];
-    if (!_responseJSON && [self.responseData length] > 0 && [self isFinished] && !self.JSONError) {
-        NSError *error = nil;
-
-        // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization.
-        // See https://github.com/rails/rails/issues/1742
-        if (self.responseString && ![self.responseString isEqualToString:@" "]) {
-            // Workaround for a bug in NSJSONSerialization when Unicode character escape codes are used instead of the actual character
-            // See http://stackoverflow.com/a/12843465/157142
-            NSData *data = [self.responseString dataUsingEncoding:NSUTF8StringEncoding];
-
-            if (data) {
-                self.responseJSON = [NSJSONSerialization JSONObjectWithData:data options:self.JSONReadingOptions error:&error];
-            } else {
-                NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
-                [userInfo setValue:@"Operation responseData failed decoding as a UTF-8 string" forKey:NSLocalizedDescriptionKey];
-                [userInfo setValue:[NSString stringWithFormat:@"Could not decode string: %@", self.responseString] forKey:NSLocalizedFailureReasonErrorKey];
-                error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
-            }
-        }
-
-        self.JSONError = error;
-    }
-    [self.lock unlock];
-
-    return _responseJSON;
-}
-
-- (NSError *)error {
-    if (_JSONError) {
-        return _JSONError;
-    } else {
-        return [super error];
-    }
-}
-
-#pragma mark - AFHTTPRequestOperation
-
-+ (NSSet *)acceptableContentTypes {
-    return [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
-}
-
-+ (BOOL)canProcessRequest:(NSURLRequest *)request {
-    return [[[request URL] pathExtension] isEqualToString:@"json"] || [super canProcessRequest:request];
-}
-
-- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
-                              failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
-#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 {
-            dispatch_async(json_request_operation_processing_queue(), ^{
-                id JSON = self.responseJSON;
-
-                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, JSON);
-                        });
-                    }
-                }
-            });
-        }
-    };
-#pragma clang diagnostic pop
-}
-
-@end

+ 167 - 0
AFNetworking/AFNetworkReachabilityManager.h

@@ -0,0 +1,167 @@
+// AFNetworkReachabilityManager.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 <netinet/in.h>
+#import <netinet6/in6.h>
+#import <arpa/inet.h>
+#import <ifaddrs.h>
+#import <netdb.h>
+
+typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
+    AFNetworkReachabilityStatusUnknown          = -1,
+    AFNetworkReachabilityStatusNotReachable     = 0,
+    AFNetworkReachabilityStatusReachableViaWWAN = 1,
+    AFNetworkReachabilityStatusReachableViaWiFi = 2,
+};
+
+/**
+
+ */
+@interface AFNetworkReachabilityManager : NSObject
+
+/**
+ 
+ */
+@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
+
+
+/**
+
+ */
+@property (readonly, nonatomic, assign) SCNetworkReachabilityFlags networkReachabilityFlags;
+
+/**
+ 
+ */
+@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable;
+
+/**
+ 
+ */
+@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN;
+
+/**
+ 
+ */
+@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi;
+
+///
+
+/**
+ 
+ */
++ (instancetype)sharedManager;
+
+/**
+ 
+ */
++ (instancetype)managerForDomain:(NSString *)domain;
+
+/**
+ 
+ */
++ (instancetype)managerForAddress:(const struct sockaddr_in *)address;
+
+/**
+ 
+ */
+- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability;
+
+///
+
+/**
+ 
+ */
+- (void)startMonitoring;
+
+/**
+ 
+ */
+- (void)stopMonitoring;
+
+///
+
+- (NSString *)localizedNetworkReachabilityStatusString;
+
+///
+
+/**
+ 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`.
+ */
+- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block;
+
+@end
+
+///----------------
+/// @name Constants
+///----------------
+
+/**
+ ## Network Reachability
+
+ The following constants are provided by `AFNetworkReachabilityManager` 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.
+ */
+
+///--------------------
+/// @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`).
+ */
+extern NSString * const AFNetworkingReachabilityDidChangeNotification;
+extern NSString * const AFNetworkingReachabilityNotificationStatusItem;

+ 224 - 0
AFNetworking/AFNetworkReachabilityManager.m

@@ -0,0 +1,224 @@
+// AFNetworkReachabilityManager.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 "AFNetworkReachabilityManager.h"
+
+NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
+NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem";
+
+typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status);
+
+static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) {
+    BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
+    BOOL canConnectionAutomatically = ((flags & kSCNetworkReachabilityFlagsTransientConnection) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0);
+    BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0);
+    BOOL isNetworkReachable = (isReachable && canConnectWithoutUserInteraction);
+
+    AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown;
+    if (isNetworkReachable == NO) {
+        status = AFNetworkReachabilityStatusNotReachable;
+    }
+#if	TARGET_OS_IPHONE
+    else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) {
+        status = AFNetworkReachabilityStatusReachableViaWWAN;
+    }
+#endif
+    else {
+        status = AFNetworkReachabilityStatusReachableViaWiFi;
+    }
+
+    return status;
+}
+
+static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
+    AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
+    AFNetworkReachabilityStatusBlock block = (__bridge AFNetworkReachabilityStatusBlock)info;
+    if (block) {
+        block(status);
+    }
+
+
+    dispatch_async(dispatch_get_main_queue(), ^{
+        NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
+        [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:@{ AFNetworkingReachabilityNotificationStatusItem: @(status) }];
+    });
+}
+
+static const void * AFNetworkReachabilityRetainCallback(const void *info) {
+    return Block_copy(info);
+}
+
+static void AFNetworkReachabilityReleaseCallback(const void *info) {
+    if (info) {
+        Block_release(info);
+    }
+}
+
+@interface AFNetworkReachabilityManager ()
+@property (readwrite, nonatomic, assign) SCNetworkReachabilityRef networkReachability;
+@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
+@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
+@end
+
+@implementation AFNetworkReachabilityManager
+@dynamic networkReachabilityFlags;
+
++ (instancetype)sharedManager {
+    static AFNetworkReachabilityManager *_sharedManager = nil;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        struct sockaddr_in address;
+        bzero(&address, sizeof(address));
+        address.sin_len = sizeof(address);
+        address.sin_family = AF_INET;
+
+        _sharedManager = [self managerForAddress:&address];
+    });
+
+    return _sharedManager;
+}
+
++ (instancetype)managerForDomain:(NSString *)domain {
+    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]);
+
+    return [[self alloc] initWithReachability:reachability];
+}
+
++ (instancetype)managerForAddress:(const struct sockaddr_in *)address {
+    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address);
+
+    return [[self alloc] initWithReachability:reachability];
+}
+
+- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.networkReachability = reachability;
+
+    self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown;
+
+    return self;
+}
+
+- (void)dealloc {
+    [self stopMonitoring];
+
+    CFRelease(_networkReachability);
+    _networkReachability = NULL;
+}
+
+#pragma mark -
+
+- (SCNetworkReachabilityFlags)networkReachabilityFlags {
+    SCNetworkReachabilityFlags flags;
+    SCNetworkReachabilityGetFlags(self.networkReachability, &flags);
+    return flags;
+}
+
+- (BOOL)isReachable {
+    return [self isReachableViaWWAN] || [self isReachableViaWiFi];
+}
+
+- (BOOL)isReachableViaWWAN {
+    return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN;
+}
+
+- (BOOL)isReachableViaWiFi {
+    return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi;
+}
+
+#pragma mark -
+
+- (void)startMonitoring {
+    [self stopMonitoring];
+
+    if (!self.networkReachability) {
+        return;
+    }
+
+    __weak __typeof(self)weakSelf = self;
+    AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) {
+        __strong __typeof(weakSelf)strongSelf = weakSelf;
+
+        strongSelf.networkReachabilityStatus = status;
+        if (strongSelf.networkReachabilityStatusBlock) {
+            strongSelf.networkReachabilityStatusBlock(status);
+        }
+    };
+
+    SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
+    SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
+
+    SCNetworkReachabilityFlags flags;
+    SCNetworkReachabilityGetFlags(self.networkReachability, &flags);
+    dispatch_async(dispatch_get_main_queue(), ^{
+        AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
+        callback(status);
+    });
+
+    SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
+}
+
+- (void)stopMonitoring {
+    if (!self.networkReachability) {
+        return;
+    }
+
+    SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
+}
+
+#pragma mark -
+
+- (NSString *)localizedNetworkReachabilityStatusString {
+    switch (self.networkReachabilityStatus) {
+        case AFNetworkReachabilityStatusNotReachable:
+            return NSLocalizedStringFromTable(@"Network Unreachable", @"AFNetworking", nil);
+        case AFNetworkReachabilityStatusReachableViaWWAN:
+            return NSLocalizedStringFromTable(@"Network Reachable via WWAN", @"AFNetworking", nil);
+        case AFNetworkReachabilityStatusReachableViaWiFi:
+            return NSLocalizedStringFromTable(@"Network Reachable via WiFi", @"AFNetworking", nil);
+        case AFNetworkReachabilityStatusUnknown:
+        default:
+            return NSLocalizedStringFromTable(@"Unknown Network Reachability", @"AFNetworking", nil);
+    }
+}
+
+#pragma mark -
+
+- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block {
+    self.networkReachabilityStatusBlock = block;
+}
+
+#pragma mark - NSKeyValueObserving
+
++ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
+    if ([key isEqualToString:@"networkReachabilityFlags"] || [key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) {
+        return [NSSet setWithObject:@"networkReachabilityStatus"];
+    }
+
+    return [super keyPathsForValuesAffectingValueForKey:key];
+}
+
+@end

+ 9 - 12
AFNetworking/AFNetworking.h

@@ -1,6 +1,6 @@
 // AFNetworking.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
@@ -26,18 +26,15 @@
 #ifndef _AFNETWORKING_
     #define _AFNETWORKING_
 
-    #import "AFURLConnectionOperation.h"
+    #import "AFURLRequestSerialization.h"
+    #import "AFURLResponseSerialization.h"
+    #import "AFSecurityPolicy.h"
+    #import "AFNetworkReachabilityManager.h"
 
+    #import "AFURLConnectionOperation.h"
     #import "AFHTTPRequestOperation.h"
-    #import "AFJSONRequestOperation.h"
-    #import "AFXMLRequestOperation.h"
-    #import "AFPropertyListRequestOperation.h"
-    #import "AFHTTPClient.h"
-
-    #import "AFImageRequestOperation.h"
+    #import "AFHTTPRequestOperationManager.h"
 
-    #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-        #import "AFNetworkActivityIndicatorManager.h"
-        #import "UIImageView+AFNetworking.h"
-    #endif
+    #import "AFURLSessionManager.h"
+    #import "AFHTTPSessionManager.h"
 #endif /* _AFNETWORKING_ */

+ 0 - 68
AFNetworking/AFPropertyListRequestOperation.h

@@ -1,68 +0,0 @@
-// AFPropertyListRequestOperation.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 "AFHTTPRequestOperation.h"
-
-/**
- `AFPropertyListRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and deserializing objects with property list (plist) response data.
-
- ## Acceptable Content Types
-
- By default, `AFPropertyListRequestOperation` accepts the following MIME types:
-
- - `application/x-plist`
- */
-@interface AFPropertyListRequestOperation : AFHTTPRequestOperation
-
-///----------------------------
-/// @name Getting Response Data
-///----------------------------
-
-/**
- An object deserialized from a plist constructed using the response data.
- */
-@property (readonly, nonatomic) id responsePropertyList;
-
-///--------------------------------------
-/// @name Managing Property List Behavior
-///--------------------------------------
-
-/**
- One of the `NSPropertyListMutabilityOptions` options, specifying the mutability of objects deserialized from the property list. By default, this is `NSPropertyListImmutable`.
- */
-@property (nonatomic, assign) NSPropertyListReadOptions propertyListReadOptions;
-
-/**
- Creates and returns an `AFPropertyListRequestOperation` object and sets the specified success and failure callbacks.
-
- @param urlRequest The request object to be loaded asynchronously during execution of the operation
- @param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the object deserialized from a plist constructed using the response data.
- @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while deserializing the object from a property list. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred.
-
- @return A new property list request operation
- */
-+ (instancetype)propertyListRequestOperationWithRequest:(NSURLRequest *)urlRequest
-												success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success
-												failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList))failure;
-
-@end

+ 0 - 143
AFNetworking/AFPropertyListRequestOperation.m

@@ -1,143 +0,0 @@
-// AFPropertyListRequestOperation.m
-//
-// 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 "AFPropertyListRequestOperation.h"
-
-static dispatch_queue_t property_list_request_operation_processing_queue() {
-    static dispatch_queue_t af_property_list_request_operation_processing_queue;
-    static dispatch_once_t onceToken;
-    dispatch_once(&onceToken, ^{
-        af_property_list_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.property-list-request.processing", DISPATCH_QUEUE_CONCURRENT);
-    });
-
-    return af_property_list_request_operation_processing_queue;
-}
-
-@interface AFPropertyListRequestOperation ()
-@property (readwrite, nonatomic) id responsePropertyList;
-@property (readwrite, nonatomic, assign) NSPropertyListFormat propertyListFormat;
-@property (readwrite, nonatomic) NSError *propertyListError;
-@end
-
-@implementation AFPropertyListRequestOperation
-@synthesize responsePropertyList = _responsePropertyList;
-@synthesize propertyListReadOptions = _propertyListReadOptions;
-@synthesize propertyListFormat = _propertyListFormat;
-@synthesize propertyListError = _propertyListError;
-
-+ (instancetype)propertyListRequestOperationWithRequest:(NSURLRequest *)request
-												success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success
-												failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList))failure
-{
-    AFPropertyListRequestOperation *requestOperation = [(AFPropertyListRequestOperation *)[self alloc] initWithRequest:request];
-    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
-        if (success) {
-            success(operation.request, operation.response, responseObject);
-        }
-    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
-        if (failure) {
-            failure(operation.request, operation.response, error, [(AFPropertyListRequestOperation *)operation responsePropertyList]);
-        }
-    }];
-
-    return requestOperation;
-}
-
-- (id)initWithRequest:(NSURLRequest *)urlRequest {
-    self = [super initWithRequest:urlRequest];
-    if (!self) {
-        return nil;
-    }
-
-    self.propertyListReadOptions = NSPropertyListImmutable;
-
-    return self;
-}
-
-
-- (id)responsePropertyList {
-    if (!_responsePropertyList && [self.responseData length] > 0 && [self isFinished]) {
-        NSPropertyListFormat format;
-        NSError *error = nil;
-        self.responsePropertyList = [NSPropertyListSerialization propertyListWithData:self.responseData options:self.propertyListReadOptions format:&format error:&error];
-        self.propertyListFormat = format;
-        self.propertyListError = error;
-    }
-
-    return _responsePropertyList;
-}
-
-- (NSError *)error {
-    if (_propertyListError) {
-        return _propertyListError;
-    } else {
-        return [super error];
-    }
-}
-
-#pragma mark - AFHTTPRequestOperation
-
-+ (NSSet *)acceptableContentTypes {
-    return [NSSet setWithObjects:@"application/x-plist", nil];
-}
-
-+ (BOOL)canProcessRequest:(NSURLRequest *)request {
-    return [[[request URL] pathExtension] isEqualToString:@"plist"] || [super canProcessRequest:request];
-}
-
-- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
-                              failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
-#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 {
-            dispatch_async(property_list_request_operation_processing_queue(), ^(void) {
-                id propertyList = self.responsePropertyList;
-
-                if (self.propertyListError) {
-                    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, propertyList);
-                        });
-                    }
-                }
-            });
-        }
-    };
-#pragma clang diagnostic pop
-}
-
-@end

+ 74 - 0
AFNetworking/AFSecurityPolicy.h

@@ -0,0 +1,74 @@
+// AFSecurity.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 <Security/Security.h>
+
+/**
+ 
+ */
+typedef NS_ENUM(NSUInteger, AFSSLPinningMode) {
+    AFSSLPinningModeNone,
+    AFSSLPinningModePublicKey,
+    AFSSLPinningModeCertificate,
+};
+
+/**
+ 
+ */
+@interface AFSecurityPolicy : NSObject
+
+/**
+ 
+ */
+@property (nonatomic, assign) AFSSLPinningMode SSLPinningMode;
+
+/**
+ 
+ */
+@property (nonatomic, strong) NSArray *pinnedCertificates;
+
+/**
+ 
+ */
+@property (nonatomic, assign) BOOL allowInvalidCertificates;
+
+///
+
+/**
+ 
+ */
++ (instancetype)defaultPolicy;
+
+/**
+ 
+ */
++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode;
+
+///
+
+/**
+ 
+ */
+- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust;
+
+@end

+ 214 - 0
AFNetworking/AFSecurityPolicy.m

@@ -0,0 +1,214 @@
+// AFSecurity.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 "AFSecurityPolicy.h"
+
+#if !defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+static NSData * AFSecKeyGetData(SecKeyRef key) {
+    CFDataRef data = NULL;
+    
+    OSStatus status = SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data);
+    NSCAssert(status == errSecSuccess, @"SecItemExport error: %ld", (long int)status);
+    NSCParameterAssert(data);
+    
+    return (__bridge_transfer NSData *)data;
+}
+#endif
+
+static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+    return [(__bridge id)key1 isEqual:(__bridge id)key2];
+#else
+    return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)];
+#endif
+}
+
+static id AFPublicKeyForCertificate(NSData *certificate) {
+    SecCertificateRef allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);
+    NSCParameterAssert(allowedCertificate);
+
+    SecCertificateRef allowedCertificates[] = {allowedCertificate};
+    CFArrayRef tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL);
+
+    SecPolicyRef policy = SecPolicyCreateBasicX509();
+    SecTrustRef allowedTrust = NULL;
+    OSStatus status = SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust);
+    NSCAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status);
+
+    SecTrustResultType result = 0;
+    status = SecTrustEvaluate(allowedTrust, &result);
+    NSCAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);
+
+    SecKeyRef allowedPublicKey = SecTrustCopyPublicKey(allowedTrust);
+    NSCParameterAssert(allowedPublicKey);
+
+    CFRelease(allowedTrust);
+    CFRelease(policy);
+    CFRelease(tempCertificates);
+    CFRelease(allowedCertificate);
+
+    return (__bridge_transfer id)allowedPublicKey;
+}
+
+static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) {
+    SecTrustResultType result = 0;
+    OSStatus status = SecTrustEvaluate(serverTrust, &result);
+    NSCAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);
+    return (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
+}
+
+static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) {
+    CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
+    NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:certificateCount];
+
+    for (CFIndex i = 0; i < certificateCount; i++) {
+        SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
+        [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
+    }
+    
+    return [NSArray arrayWithArray:trustChain];
+}
+
+static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
+    SecPolicyRef policy = SecPolicyCreateBasicX509();
+    CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
+    NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:certificateCount];
+    for (CFIndex i = 0; i < certificateCount; i++) {
+        SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
+
+        SecCertificateRef someCertificates[] = {certificate};
+        CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
+
+        SecTrustRef trust = NULL;
+
+        OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &trust);
+        NSCAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status);
+
+        SecTrustResultType result;
+        status = SecTrustEvaluate(trust, &result);
+        NSCAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);
+
+        [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];
+
+        CFRelease(trust);
+        CFRelease(certificates);
+    }
+    CFRelease(policy);
+    
+    return [NSArray arrayWithArray:trustChain];
+}
+
+#pragma mark -
+
+@interface AFSecurityPolicy()
+@property (readwrite, nonatomic, strong) NSArray *pinnedPublicKeys;
+@end
+
+@implementation AFSecurityPolicy
+
++ (NSArray *)defaultPinnedCertificates {
+    static NSArray *_defaultPinnedCertificates = nil;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        NSBundle *bundle = [NSBundle bundleForClass:[self class]];
+        NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
+
+        NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]];
+        for (NSString *path in paths) {
+            NSData *certificateData = [NSData dataWithContentsOfFile:path];
+            [certificates addObject:certificateData];
+        }
+
+        _defaultPinnedCertificates = [[NSArray alloc] initWithArray:certificates];
+    });
+
+    return _defaultPinnedCertificates;
+}
+
++ (instancetype)defaultPolicy {
+    AFSecurityPolicy *securityPolicy = [[self alloc] init];
+    securityPolicy.SSLPinningMode = AFSSLPinningModeNone;
+
+    return securityPolicy;
+}
+
++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode {
+    AFSecurityPolicy *securityPolicy = [[self alloc] init];
+    securityPolicy.SSLPinningMode = pinningMode;
+
+    return securityPolicy;
+}
+
+#pragma mark -
+
+- (void)setPinnedCertificates:(NSArray *)pinnedCertificates {
+    _pinnedCertificates = pinnedCertificates;
+
+    if (self.pinnedCertificates) {
+        NSMutableArray *mutablePinnedPublicKeys = [NSMutableArray arrayWithCapacity:[self.pinnedCertificates count]];
+        for (NSData *certificate in self.pinnedCertificates) {
+            [mutablePinnedPublicKeys addObject:AFPublicKeyForCertificate(certificate)];
+        }
+        self.pinnedPublicKeys = [NSArray arrayWithArray:mutablePinnedPublicKeys];
+    } else {
+        self.pinnedCertificates = nil;
+    }
+}
+
+#pragma mark -
+
+- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust {
+    switch (self.SSLPinningMode) {
+        case AFSSLPinningModeNone:
+            return (self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust));
+        case AFSSLPinningModeCertificate: {
+            for (NSData *trustChainCertificate in AFCertificateTrustChainForServerTrust(serverTrust)) {
+                if ([self.pinnedCertificates containsObject:trustChainCertificate]) {
+                    return YES;
+                }
+            }
+        }
+            break;
+        case AFSSLPinningModePublicKey: {
+            for (id trustChainPublicKey in AFPublicKeyTrustChainForServerTrust(serverTrust)) {
+                for (id pinnedPublicKey in self.pinnedPublicKeys) {
+                    if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
+                        return YES;
+                    }
+                }
+            }
+        }
+            break;
+        default:
+            break;
+    }
+
+    return NO;
+}
+
+#pragma mark - NSKeyValueObserving
+
++ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys {
+    return [NSSet setWithObject:@"pinnedCertificates"];
+}
+
+@end

+ 37 - 31
AFNetworking/AFURLConnectionOperation.h

@@ -1,6 +1,6 @@
 // AFURLConnectionOperation.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
@@ -23,6 +23,7 @@
 #import <Foundation/Foundation.h>
 
 #import <Availability.h>
+#import "AFSecurityPolicy.h"
 
 /**
  `AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods.
@@ -44,14 +45,11 @@
  - `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:`
  - `connection:willCacheResponse:`
  - `connectionShouldUseCredentialStorage:`
+ - `connection:needNewBodyStream:` 
  - `connection:willSendRequestForAuthenticationChallenge:`
 
  If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
 
- ## Class Constructors
-
- Class constructors, or methods that return an unowned instance, are the preferred way for subclasses to encapsulate any particular logic for handling the setup or parsing of response data. For instance, `AFJSONRequestOperation` provides `JSONRequestOperationWithRequest:success:failure:`, which takes block arguments, whose parameter on for a successful request is the JSON object initialized from the `response data`.
-
  ## Callbacks and Completion Blocks
 
  The built-in `completionBlock` provided by `NSOperation` allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its `completionBlock`. Make sure to handle cancelled operations appropriately when setting a `completionBlock` (i.e. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this.
@@ -64,7 +62,7 @@
  
  SSL with certificate pinning is strongly recommended for any application that transmits sensitive information to an external webservice.
 
- When `defaultSSLPinningMode` is defined on `AFHTTPClient` and the Security framework is linked, connections will be validated on all matching certificates with a `.cer` extension in the bundle root.
+ Connections will be validated on all matching certificates with a `.cer` extension in the bundle root.
 
  ## NSCoding & NSCopying Conformance
 
@@ -79,21 +77,10 @@
 
  - `-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations.
  - A copy of an operation will not include the `outputStream` of the original.
- - Operation copies do not include `completionBlock`. `completionBlock` often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied.
+ - Operation copies do not include `completionBlock`, as it often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied.
  */
 
-typedef enum {
-    AFSSLPinningModeNone,
-    AFSSLPinningModePublicKey,
-    AFSSLPinningModeCertificate,
-} AFURLConnectionOperationSSLPinningMode;
-
-@interface AFURLConnectionOperation : NSOperation <NSURLConnectionDelegate,
-#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 50000) || \
-    (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080)
-NSURLConnectionDataDelegate, 
-#endif
-NSCoding, NSCopying>
+@interface AFURLConnectionOperation : NSOperation <NSURLConnectionDelegate, NSURLConnectionDataDelegate, NSCoding, NSCopying>
 
 ///-------------------------------
 /// @name Accessing Run Loop Modes
@@ -123,13 +110,6 @@ NSCoding, NSCopying>
  */
 @property (readonly, nonatomic, strong) NSError *error;
 
-/**
- Whether the connection 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 Getting Response Data
 ///----------------------------
@@ -169,12 +149,14 @@ NSCoding, NSCopying>
  */
 @property (nonatomic, strong) NSURLCredential *credential;
 
+///-------------------------------
+/// @name Managing Security Policy
+///-------------------------------
+
 /**
- The pinning mode which will be used for SSL connections. `AFSSLPinningModePublicKey` by default.
- 
- SSL Pinning requires that the Security framework is linked with the binary. See the "SSL Pinning" section in the `AFURLConnectionOperation`" header for more information.
+ The security policy used to evaluate server trust for secure connections.
  */
-@property (nonatomic, assign) AFURLConnectionOperationSSLPinningMode SSLPinningMode;
+@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
 
 ///------------------------
 /// @name Accessing Streams
@@ -194,6 +176,20 @@ NSCoding, NSCopying>
  */
 @property (nonatomic, strong) NSOutputStream *outputStream;
 
+///---------------------------------
+/// @name Managing Callback Queues
+///---------------------------------
+
+/**
+ The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
+ */
+@property (nonatomic, strong) dispatch_queue_t completionQueue;
+
+/**
+ The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
+ */
+@property (nonatomic, strong) dispatch_group_t completionGroup;
+
 ///---------------------------------------------
 /// @name Managing Request Operation Information
 ///---------------------------------------------
@@ -214,7 +210,7 @@ NSCoding, NSCopying>
  
  @param urlRequest The request object to be used by the operation connection.
  */
-- (id)initWithRequest:(NSURLRequest *)urlRequest;
+- (instancetype)initWithRequest:(NSURLRequest *)urlRequest;
 
 ///----------------------------------
 /// @name Pausing / Resuming Requests
@@ -292,6 +288,7 @@ NSCoding, NSCopying>
  */
 - (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block;
 
+
 /**
  Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`.
 
@@ -299,6 +296,15 @@ NSCoding, NSCopying>
  */
 - (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block;
 
+///
+
+/**
+
+ */
++ (NSArray *)batchOfRequestOperations:(NSArray *)operations
+                        progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
+                      completionBlock:(void (^)(NSArray *operations))completionBlock;
+
 @end
 
 ///----------------

+ 104 - 226
AFNetworking/AFURLConnectionOperation.m

@@ -1,6 +1,6 @@
 // AFURLConnectionOperation.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
@@ -31,14 +31,12 @@
 // You can turn on ARC for only AFNetworking files by adding -fobjc-arc to the build phase for each of its files.
 #endif
 
-typedef enum {
+typedef NS_ENUM(NSInteger, AFOperationState) {
     AFOperationPausedState      = -1,
     AFOperationReadyState       = 1,
     AFOperationExecutingState   = 2,
     AFOperationFinishedState    = 3,
-} _AFOperationState;
-
-typedef signed short AFOperationState;
+};
 
 #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
 typedef UIBackgroundTaskIdentifier AFBackgroundTaskIdentifier;
@@ -46,6 +44,16 @@ typedef UIBackgroundTaskIdentifier AFBackgroundTaskIdentifier;
 typedef id AFBackgroundTaskIdentifier;
 #endif
 
+static dispatch_group_t url_request_operation_completion_group() {
+    static dispatch_group_t af_url_request_operation_completion_group;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        af_url_request_operation_completion_group = dispatch_group_create();
+    });
+
+    return af_url_request_operation_completion_group;
+}
+
 static NSString * const kAFNetworkingLockName = @"com.alamofire.networking.operation.lock";
 
 NSString * const AFNetworkingErrorDomain = @"AFNetworkingErrorDomain";
@@ -56,6 +64,7 @@ NSString * const AFNetworkingOperationDidStartNotification = @"com.alamofire.net
 NSString * const AFNetworkingOperationDidFinishNotification = @"com.alamofire.networking.operation.finish";
 
 typedef void (^AFURLConnectionOperationProgressBlock)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected);
+typedef BOOL (^AFURLConnectionOperationAuthenticationAgainstProtectionSpaceBlock)(NSURLConnection *connection, NSURLProtectionSpace *protectionSpace);
 typedef void (^AFURLConnectionOperationAuthenticationChallengeBlock)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge);
 typedef NSCachedURLResponse * (^AFURLConnectionOperationCacheResponseBlock)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse);
 typedef NSURLRequest * (^AFURLConnectionOperationRedirectResponseBlock)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse);
@@ -104,26 +113,6 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
     }
 }
 
-#if !defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-static NSData *AFSecKeyGetData(SecKeyRef key) {
-    CFDataRef data = NULL;
-    
-    OSStatus status = SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data);
-    NSCAssert(status == errSecSuccess, @"SecItemExport error: %ld", (long int)status);
-    NSCParameterAssert(data);
-    
-    return (__bridge_transfer NSData *)data;
-}
-#endif
-
-static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
-#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-    return [(__bridge id)key1 isEqual:(__bridge id)key2];
-#else
-    return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)];
-#endif
-}
-
 @interface AFURLConnectionOperation ()
 @property (readwrite, nonatomic, assign) AFOperationState state;
 @property (readwrite, nonatomic, assign, getter = isCancelled) BOOL cancelled;
@@ -149,33 +138,9 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
 @end
 
 @implementation AFURLConnectionOperation
-@synthesize state = _state;
-@synthesize cancelled = _cancelled;
-@synthesize connection = _connection;
-@synthesize runLoopModes = _runLoopModes;
-@synthesize request = _request;
-@synthesize response = _response;
-@synthesize error = _error;
-@synthesize allowsInvalidSSLCertificate = _allowsInvalidSSLCertificate;
-@synthesize responseData = _responseData;
-@synthesize responseString = _responseString;
-@synthesize responseStringEncoding = _responseStringEncoding;
-@synthesize totalBytesRead = _totalBytesRead;
-@dynamic inputStream;
 @synthesize outputStream = _outputStream;
-@synthesize credential = _credential;
-@synthesize SSLPinningMode = _SSLPinningMode;
-@synthesize shouldUseCredentialStorage = _shouldUseCredentialStorage;
-@synthesize userInfo = _userInfo;
-@synthesize backgroundTaskIdentifier = _backgroundTaskIdentifier;
-@synthesize uploadProgress = _uploadProgress;
-@synthesize downloadProgress = _downloadProgress;
-@synthesize authenticationChallenge = _authenticationChallenge;
-@synthesize cacheResponse = _cacheResponse;
-@synthesize redirectResponse = _redirectResponse;
-@synthesize lock = _lock;
-
-+ (void)networkRequestThreadEntryPoint:(id __unused)object {
+
++ (void)networkRequestThreadEntryPoint:(id)__unused object {
     @autoreleasepool {
         [[NSThread currentThread] setName:@"AFNetworking"];
 
@@ -196,70 +161,7 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
     return _networkRequestThread;
 }
 
-+ (NSArray *)pinnedCertificates {
-    static NSArray *_pinnedCertificates = nil;
-    static dispatch_once_t onceToken;
-    dispatch_once(&onceToken, ^{
-        NSBundle *bundle = [NSBundle mainBundle];
-        NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
-        
-        NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]];
-        for (NSString *path in paths) {
-            NSData *certificateData = [NSData dataWithContentsOfFile:path];
-            [certificates addObject:certificateData];
-        }
-        
-        _pinnedCertificates = [[NSArray alloc] initWithArray:certificates];
-    });
-    
-    return _pinnedCertificates;
-}
-
-+ (NSArray *)pinnedPublicKeys {
-    static NSArray *_pinnedPublicKeys = nil;
-    static dispatch_once_t onceToken;
-    dispatch_once(&onceToken, ^{
-        NSArray *pinnedCertificates = [self pinnedCertificates];
-        NSMutableArray *publicKeys = [NSMutableArray arrayWithCapacity:[pinnedCertificates count]];
-        
-        for (NSData *data in pinnedCertificates) {
-            SecCertificateRef allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)data);
-            NSParameterAssert(allowedCertificate);
-            
-            SecCertificateRef allowedCertificates[] = {allowedCertificate};
-            CFArrayRef certificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL);
-            
-            SecPolicyRef policy = SecPolicyCreateBasicX509();
-            SecTrustRef allowedTrust = NULL;
-            OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &allowedTrust);
-            NSAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status);
-            if (status == errSecSuccess && allowedTrust) {
-                SecTrustResultType result = 0;
-                status = SecTrustEvaluate(allowedTrust, &result);
-                NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);
-                if (status == errSecSuccess) {
-                    SecKeyRef allowedPublicKey = SecTrustCopyPublicKey(allowedTrust);
-                    NSParameterAssert(allowedPublicKey);
-                    if (allowedPublicKey) {
-                        [publicKeys addObject:(__bridge_transfer id)allowedPublicKey];
-                    }
-                }
-                
-                CFRelease(allowedTrust);
-            }          
-            
-            CFRelease(policy);
-            CFRelease(certificates);
-            CFRelease(allowedCertificate);
-        }
-        
-        _pinnedPublicKeys = [[NSArray alloc] initWithArray:publicKeys];
-    });
-    
-    return _pinnedPublicKeys;
-}
-
-- (id)initWithRequest:(NSURLRequest *)urlRequest {
+- (instancetype)initWithRequest:(NSURLRequest *)urlRequest {
     NSParameterAssert(urlRequest);
 
     self = [super init];
@@ -276,13 +178,10 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
     
     self.shouldUseCredentialStorage = YES;
 
-    // #ifdef included for backwards-compatibility 
-#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
-    self.allowsInvalidSSLCertificate = YES;
-#endif
-
     self.state = AFOperationReadyState;
 
+    self.securityPolicy = [AFSecurityPolicy defaultPolicy];
+
     return self;
 }
 
@@ -309,12 +208,23 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
     if (!block) {
         [super setCompletionBlock:nil];
     } else {
-        __weak __typeof(&*self)weakSelf = self;
+        __weak __typeof(self)weakSelf = self;
         [super setCompletionBlock:^ {
-            __strong __typeof(&*weakSelf)strongSelf = weakSelf;
-            
-            block();
-            [strongSelf setCompletionBlock:nil];
+            __strong __typeof(weakSelf)strongSelf = weakSelf;
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wgnu"
+            dispatch_group_t group = strongSelf.completionGroup ?: url_request_operation_completion_group();
+            dispatch_queue_t queue = strongSelf.completionQueue ?: dispatch_get_main_queue();
+#pragma clang diagnostic pop
+
+            dispatch_group_async(group, queue, ^{
+                block();
+            });
+
+            dispatch_group_notify(group, queue, ^{
+                [strongSelf setCompletionBlock:nil];
+            });
         }];
     }
     [self.lock unlock];
@@ -358,9 +268,9 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
     [self.lock lock];
     if (!self.backgroundTaskIdentifier) {
         UIApplication *application = [UIApplication sharedApplication];
-        __weak __typeof(&*self)weakSelf = self;
+        __weak __typeof(self)weakSelf = self;
         self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
-            __strong __typeof(&*weakSelf)strongSelf = weakSelf;
+            __strong __typeof(weakSelf)strongSelf = weakSelf;
             
             if (handler) {
                 handler();
@@ -510,7 +420,7 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
 
 - (void)operationDidStart {
     [self.lock lock];
-    if (![self isCancelled]) {
+    if (! [self isCancelled]) {
         self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
         
         NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
@@ -528,12 +438,6 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
     });
     
     if ([self isCancelled]) {
-        NSDictionary *userInfo = nil;
-        if ([self.request URL]) {
-            userInfo = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
-        }
-        self.error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
-
         [self finish];
     }
 }
@@ -566,13 +470,66 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
         userInfo = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
     }
     NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
-    
+
     if (![self isFinished] && self.connection) {
         [self.connection cancel];
         [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:error];
     }
 }
 
+#pragma mark -
+
++ (NSArray *)batchOfRequestOperations:(NSArray *)operations
+                        progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
+                      completionBlock:(void (^)(NSArray *operations))completionBlock
+{
+    if (!operations || [operations count] == 0) {
+        return 0;
+    }
+
+    __block dispatch_group_t group = dispatch_group_create();
+    NSBlockOperation *batchedOperation = [NSBlockOperation blockOperationWithBlock:^{
+        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
+            if (completionBlock) {
+                completionBlock(operations);
+            }
+        });
+    }];
+
+    for (AFURLConnectionOperation *operation in operations) {
+        operation.completionGroup = group;
+        void (^originalCompletionBlock)(void) = [operation.completionBlock copy];
+        __weak __typeof(operation)weakOperation = operation;
+        operation.completionBlock = ^{
+            __strong __typeof(weakOperation)strongOperation = weakOperation;
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wgnu"
+            dispatch_queue_t queue = strongOperation.completionQueue ?: dispatch_get_main_queue();
+#pragma clang diagnostic pop
+            dispatch_group_async(group, queue, ^{
+                if (originalCompletionBlock) {
+                    originalCompletionBlock();
+                }
+
+                NSUInteger numberOfFinishedOperations = [[operations indexesOfObjectsPassingTest:^BOOL(id op, NSUInteger __unused idx,  BOOL __unused *stop) {
+                    return [op isFinished];
+                }] count];
+
+                if (progressBlock) {
+                    progressBlock(numberOfFinishedOperations, [operations count]);
+                }
+
+                dispatch_group_leave(group);
+            });
+        };
+
+        dispatch_group_enter(group);
+        [batchedOperation addDependency:operation];
+    }
+
+    return [operations arrayByAddingObject:batchedOperation];
+}
+
 #pragma mark - NSURLConnectionDelegate
 
 - (void)connection:(NSURLConnection *)connection
@@ -582,91 +539,13 @@ willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challe
         self.authenticationChallenge(connection, challenge);
         return;
     }
-    
+
     if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
-        SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
-        
-        SecPolicyRef policy = SecPolicyCreateBasicX509();
-        CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
-        NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:certificateCount];
-        
-        for (CFIndex i = 0; i < certificateCount; i++) {
-            SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
-            
-            if (self.SSLPinningMode == AFSSLPinningModeCertificate) {
-                [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
-            } else if (self.SSLPinningMode == AFSSLPinningModePublicKey) {
-                SecCertificateRef someCertificates[] = {certificate};
-                CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
-                
-                SecTrustRef trust = NULL;
-                
-                OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &trust);
-                NSAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status);
-                if (status == errSecSuccess && trust) {
-                    SecTrustResultType result;
-                    status = SecTrustEvaluate(trust, &result);
-                    NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);
-                    if (status == errSecSuccess) {
-                        [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];
-                    }
-
-                    CFRelease(trust);
-                }
-              
-                CFRelease(certificates);
-            }
-        }
-        
-        CFRelease(policy);
-        
-        switch (self.SSLPinningMode) {
-            case AFSSLPinningModePublicKey: {
-                NSArray *pinnedPublicKeys = [self.class pinnedPublicKeys];
-                
-                for (id publicKey in trustChain) {
-                    for (id pinnedPublicKey in pinnedPublicKeys) {
-                        if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)publicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
-                            NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
-                            [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
-                            return;
-                        }
-                    }
-                }
-                
-                [[challenge sender] cancelAuthenticationChallenge:challenge];
-                break;
-            }
-            case AFSSLPinningModeCertificate: {
-                for (id serverCertificateData in trustChain) {
-                    if ([[self.class pinnedCertificates] containsObject:serverCertificateData]) {
-                        NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
-                        [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
-                        return;
-                    }
-                }
-                
-                [[challenge sender] cancelAuthenticationChallenge:challenge];
-                break;
-            }
-            case AFSSLPinningModeNone: {
-                if (self.allowsInvalidSSLCertificate){
-                    NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
-                    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
-                } else {
-                    SecTrustResultType result = 0;
-                    OSStatus status = SecTrustEvaluate(serverTrust, &result);
-                    NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);
-                    
-                    if (status == errSecSuccess && (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed)) {
-                        NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
-                        [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
-                    } else {
-                        [[challenge sender] cancelAuthenticationChallenge:challenge];
-                    }
-                }
-                break;
-            }
+        if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust]) {
+            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
+            [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
+        } else {
+            [[challenge sender] cancelAuthenticationChallenge:challenge];
         }
     } else {
         if ([challenge previousFailureCount] == 0) {
@@ -740,10 +619,10 @@ didReceiveResponse:(NSURLResponse *)response
             break;
         }
     }
-    
+
     dispatch_async(dispatch_get_main_queue(), ^{
         self.totalBytesRead += length;
-        
+
         if (self.downloadProgress) {
             self.downloadProgress(length, self.totalBytesRead, self.response.expectedContentLength);
         }
@@ -801,8 +680,7 @@ didReceiveResponse:(NSURLResponse *)response
     self.response = [aDecoder decodeObjectForKey:@"response"];
     self.error = [aDecoder decodeObjectForKey:@"error"];
     self.responseData = [aDecoder decodeObjectForKey:@"responseData"];
-    self.totalBytesRead = [[aDecoder decodeObjectForKey:@"totalBytesRead"] longLongValue];
-    self.allowsInvalidSSLCertificate = [[aDecoder decodeObjectForKey:@"allowsInvalidSSLCertificate"] boolValue];
+    self.totalBytesRead = [aDecoder decodeInt64ForKey:@"totalBytesRead"];
 
     return self;
 }
@@ -826,8 +704,7 @@ didReceiveResponse:(NSURLResponse *)response
     [aCoder encodeObject:self.response forKey:@"response"];
     [aCoder encodeObject:self.error forKey:@"error"];
     [aCoder encodeObject:self.responseData forKey:@"responseData"];
-    [aCoder encodeObject:[NSNumber numberWithLongLong:self.totalBytesRead] forKey:@"totalBytesRead"];
-    [aCoder encodeObject:[NSNumber numberWithBool:self.allowsInvalidSSLCertificate] forKey:@"allowsInvalidSSLCertificate"];
+    [aCoder encodeInt64:self.totalBytesRead forKey:@"totalBytesRead"];
 }
 
 #pragma mark - NSCopying
@@ -840,7 +717,8 @@ didReceiveResponse:(NSURLResponse *)response
     operation.authenticationChallenge = self.authenticationChallenge;
     operation.cacheResponse = self.cacheResponse;
     operation.redirectResponse = self.redirectResponse;
-    operation.allowsInvalidSSLCertificate = self.allowsInvalidSSLCertificate;
+    operation.completionQueue = self.completionQueue;
+    operation.completionGroup = self.completionGroup;
     
     return operation;
 }

+ 346 - 0
AFNetworking/AFURLRequestSerialization.h

@@ -0,0 +1,346 @@
+// AFSerialization.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>
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+#import <UIKit/UIKit.h>
+#endif
+
+/**
+ The `AFURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary.
+
+ For example, a JSON request serializer may set the HTTP body of the request to a JSON representation, and set the `Content-Type` HTTP header field value to `application/json`.
+ */
+@protocol AFURLRequestSerialization <NSCoding, NSCopying>
+
+/**
+ Returns a request with the specified parameters encoded into a copy of the original request.
+
+ @param request The original request.
+ @param parameters The parameters to be encoded.
+ @param error The error that occurred while attempting to encode the request parameters.
+
+ @return A serialized request.
+ */
+- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
+                               withParameters:(NSDictionary *)parameters
+                                        error:(NSError *__autoreleasing *)error;
+
+@end
+
+#pragma mark -
+
+/**
+
+ */
+typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) {
+    AFHTTPRequestQueryStringDefaultStyle = 0,
+};
+
+@protocol AFMultipartFormData;
+
+/**
+ `AFHTTPSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.
+
+ Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPSerializer` in order to ensure consistent default behavior.
+ */
+@interface AFHTTPRequestSerializer : NSObject <AFURLRequestSerialization>
+
+/**
+ The string encoding used to serialize parameters.
+ */
+@property (nonatomic, assign) NSStringEncoding stringEncoding;
+
+///---------------------------------------
+/// @name Configuring HTTP Request Headers
+///---------------------------------------
+
+/**
+ Default HTTP header field values to be applied to serialized requests.
+ */
+@property (readonly, nonatomic, strong) NSDictionary *HTTPRequestHeaders;
+
+/**
+ Creates and returns a serializer with default configuration.
+ */
++ (instancetype)serializer;
+
+/**
+ 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)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
+
+/**
+ 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)setAuthorizationHeaderFieldWithUsername:(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)setAuthorizationHeaderFieldWithToken:(NSString *)token;
+
+
+/**
+ Clears any existing value for the "Authorization" HTTP header.
+ */
+- (void)clearAuthorizationHeader;
+
+///-------------------------------------------------------
+/// @name Configuring Query String Parameter Serialization
+///-------------------------------------------------------
+
+/**
+ HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default.
+ */
+@property (nonatomic, strong) NSSet *HTTPMethodsEncodingParametersInURI;
+
+/**
+ Set the method of query string serialization according to one of the pre-defined styles.
+
+ @param style The serialization style.
+
+ @see AFHTTPRequestQueryStringSerializationStyle
+ */
+- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style;
+
+/**
+ Set the a custom method of query string serialization according to the specified block.
+
+ @param block A block that defines a process of encoding parameters into a query string. This block returns the query string and takes three arguments: the request, the parameters to encode, and the error that occured when attempting to encode parameters for the given request.
+ */
+- (void)setQueryStringSerializationWithBlock:(NSString * (^)(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error))block;
+
+///-------------------------------
+/// @name Creating Request Objects
+///-------------------------------
+
+/**
+ Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string.
+
+ 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 URLString The URL string used to create the request 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
+                                 URLString:(NSString *)URLString
+                                parameters:(NSDictionary *)parameters;
+
+/**
+ Creates an `NSMutableURLRequest` object with the specified HTTP method and URLString, 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 URLString The URL string used to create 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.
+
+ @return An `NSMutableURLRequest` object
+ */
+- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
+                                              URLString:(NSString *)URLString
+                                             parameters:(NSDictionary *)parameters
+                              constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block;
+
+@end
+
+#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 `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString: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:(int64_t)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, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over `NSURLConnection`. 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 16kb.
+ @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
+
+///----------------
+/// @name Constants
+///----------------
+
+/**
+ ## Throttling Bandwidth for HTTP Request Input Streams
+
+ @see -throttleBandwidthWithPacketSize:delay:
+
+ `kAFUploadStream3GSuggestedPacketSize`
+ Maximum packet size, in number of bytes. Equal to 16kb.
+
+ `kAFUploadStream3GSuggestedDelay`
+ Duration of delay each time a packet is read. Equal to 0.2 seconds.
+ */
+
+#pragma mark -
+
+@interface AFJSONRequestSerializer : AFHTTPRequestSerializer
+
+/**
+ The property list format. Possible values are described in "NSPropertyListFormat".
+ */
+@property (nonatomic, assign) NSPropertyListFormat format;
+
+/**
+ Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default.
+ */
+@property (nonatomic, assign) NSJSONWritingOptions writingOptions;
+
+/**
+ Creates and returns a JSON serializer with specified reading and writing options.
+
+ @param readingOptions The specified JSON reading options.
+ @param writingOptions The specified JSON writing options.
+ */
++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions;
+
+@end
+
+@interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer
+
+/**
+ The property list format. Possible values are described in "NSPropertyListFormat".
+ */
+@property (nonatomic, assign) NSPropertyListFormat format;
+
+/**
+ @warning The `writeOptions` property is currently unused.
+ */
+@property (nonatomic, assign) NSPropertyListWriteOptions writeOptions;
+
+/**
+ Creates and returns a property list serializer with a specified format, read options, and write options.
+
+ @param format The property list format.
+ @param writeOptions The property list write options.
+ 
+ @warning The `writeOptions` property is currently unused.
+ */
++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
+                        writeOptions:(NSPropertyListWriteOptions)writeOptions;
+
+@end

+ 234 - 503
AFNetworking/AFHTTPClient.m → AFNetworking/AFURLRequestSerialization.m

@@ -1,6 +1,6 @@
-// AFHTTPClient.m
+// AFSerialization.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
@@ -8,10 +8,10 @@
 // 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
@@ -20,36 +20,11 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
-#import <Foundation/Foundation.h>
-
-#import "AFHTTPClient.h"
-#import "AFHTTPRequestOperation.h"
-
-#import <Availability.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
-
-#ifdef _SYSTEMCONFIGURATION_H
-NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
-NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem";
+#import "AFURLRequestSerialization.h"
 
-typedef SCNetworkReachabilityRef AFNetworkReachabilityRef;
-typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status);
-#else
-typedef id AFNetworkReachabilityRef;
-#endif
+extern NSString * const AFNetworkingErrorDomain;
 
-typedef void (^AFCompletionBlock)(void);
+typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error);
 
 static NSString * AFBase64EncodedStringFromString(NSString *string) {
     NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
@@ -104,8 +79,6 @@ static NSString * AFPercentEscapedQueryStringValueFromStringWithEncoding(NSStrin
 @end
 
 @implementation AFQueryStringPair
-@synthesize field = _field;
-@synthesize value = _value;
 
 - (id)initWithField:(id)field value:(id)value {
     self = [super init];
@@ -173,82 +146,42 @@ NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
     } else {
         [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]];
     }
-
+    
     return mutableQueryStringComponents;
 }
 
+#pragma mark -
+
 @interface AFStreamingMultipartFormData : NSObject <AFMultipartFormData>
-- (id)initWithURLRequest:(NSMutableURLRequest *)urlRequest
-          stringEncoding:(NSStringEncoding)encoding;
+- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest
+                    stringEncoding:(NSStringEncoding)encoding;
 
 - (NSMutableURLRequest *)requestByFinalizingMultipartFormData;
 @end
 
 #pragma mark -
 
-@interface AFHTTPClient ()
-@property (readwrite, nonatomic, strong) NSURL *baseURL;
-@property (readwrite, nonatomic, strong) NSMutableArray *registeredHTTPOperationClassNames;
-@property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders;
-@property (readwrite, nonatomic, strong) NSURLCredential *defaultCredential;
-@property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue;
-#ifdef _SYSTEMCONFIGURATION_H
-@property (readwrite, nonatomic, assign) AFNetworkReachabilityRef networkReachability;
-@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
-@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
-#endif
-
-#ifdef _SYSTEMCONFIGURATION_H
-- (void)startMonitoringNetworkReachability;
-- (void)stopMonitoringNetworkReachability;
-#endif
+@interface AFHTTPRequestSerializer ()
+@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders;
+@property (readwrite, nonatomic, assign) AFHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle;
+@property (readwrite, nonatomic, copy) AFQueryStringSerializationBlock queryStringSerialization;
 @end
 
-@implementation AFHTTPClient
-@synthesize baseURL = _baseURL;
-@synthesize stringEncoding = _stringEncoding;
-@synthesize parameterEncoding = _parameterEncoding;
-@synthesize registeredHTTPOperationClassNames = _registeredHTTPOperationClassNames;
-@synthesize defaultHeaders = _defaultHeaders;
-@synthesize defaultCredential = _defaultCredential;
-@synthesize operationQueue = _operationQueue;
-#ifdef _SYSTEMCONFIGURATION_H
-@synthesize networkReachability = _networkReachability;
-@synthesize networkReachabilityStatus = _networkReachabilityStatus;
-@synthesize networkReachabilityStatusBlock = _networkReachabilityStatusBlock;
-#endif
-@synthesize defaultSSLPinningMode = _defaultSSLPinningMode;
-@synthesize allowsInvalidSSLCertificate = _allowsInvalidSSLCertificate;
-
-+ (instancetype)clientWithBaseURL:(NSURL *)url {
-    return [[self alloc] initWithBaseURL:url];
-}
+@implementation AFHTTPRequestSerializer
 
-- (id)init {
-    @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"%@ Failed to call designated initializer. Invoke `initWithBaseURL:` instead.", NSStringFromClass([self class])] userInfo:nil];
++ (instancetype)serializer {
+    return [[self alloc] init];
 }
 
-- (id)initWithBaseURL:(NSURL *)url {
-    NSParameterAssert(url);
-
+- (instancetype)init {
     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.stringEncoding = NSUTF8StringEncoding;
-    self.parameterEncoding = AFFormURLParameterEncoding;
-
-    self.registeredHTTPOperationClassNames = [NSMutableArray array];
 
-	self.defaultHeaders = [NSMutableDictionary dictionary];
+    self.mutableHTTPRequestHeaders = [NSMutableDictionary dictionary];
 
     // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
     NSMutableArray *acceptLanguagesComponents = [NSMutableArray array];
@@ -257,7 +190,7 @@ NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
         [acceptLanguagesComponents addObject:[NSString stringWithFormat:@"%@;q=%0.1g", obj, q]];
         *stop = q <= 0.5f;
     }];
-    [self setDefaultHeader:@"Accept-Language" value:[acceptLanguagesComponents componentsJoinedByString:@", "]];
+    [self setValue:[acceptLanguagesComponents componentsJoinedByString:@", "] forHTTPHeaderField:@"Accept-Language"];
 
     NSString *userAgent = nil;
 #pragma clang diagnostic push
@@ -275,266 +208,96 @@ NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
             CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, kCFStringTransformToLatin, false);
             userAgent = mutableUserAgent;
         }
-        [self setDefaultHeader:@"User-Agent" value:userAgent];
+        [self setValue:userAgent forHTTPHeaderField:@"User-Agent"];
     }
 
-#ifdef _SYSTEMCONFIGURATION_H
-    self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown;
-    [self startMonitoringNetworkReachability];
-#endif
-
-    self.operationQueue = [[NSOperationQueue alloc] init];
-	[self.operationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
+    // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
+    self.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil];
 
-    // #ifdef included for backwards-compatibility
-#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
-    self.allowsInvalidSSLCertificate = YES;
-#endif
-    
     return self;
 }
 
-- (void)dealloc {
-#ifdef _SYSTEMCONFIGURATION_H
-    [self stopMonitoringNetworkReachability];
-#endif
-}
-
-- (NSString *)description {
-    return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, defaultHeaders: %@, registeredOperationClasses: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.defaultHeaders, self.registeredHTTPOperationClassNames, self.operationQueue];
-}
-
 #pragma mark -
 
-#ifdef _SYSTEMCONFIGURATION_H
-static BOOL AFURLHostIsIPAddress(NSURL *url) {
-    struct sockaddr_in sa_in;
-    struct sockaddr_in6 sa_in6;
-
-    return [url host] && (inet_pton(AF_INET, [[url host] UTF8String], &sa_in) == 1 || inet_pton(AF_INET6, [[url host] UTF8String], &sa_in6) == 1);
+- (NSDictionary *)HTTPRequestHeaders {
+    return [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders];
 }
 
-static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) {
-    BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
-    BOOL canConnectionAutomatically = ((flags & kSCNetworkReachabilityFlagsTransientConnection) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0);
-    BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0);
-    BOOL isNetworkReachable = (isReachable && canConnectWithoutUserInteraction);
-
-    AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown;
-    if (isNetworkReachable == NO) {
-        status = AFNetworkReachabilityStatusNotReachable;
-    }
-#if	TARGET_OS_IPHONE
-    else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) {
-        status = AFNetworkReachabilityStatusReachableViaWWAN;
-    }
-#endif
-    else {
-        status = AFNetworkReachabilityStatusReachableViaWiFi;
-    }
-
-    return status;
+- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field {
+	[self.mutableHTTPRequestHeaders setValue:value forKey:field];
 }
 
-static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
-    AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
-    AFNetworkReachabilityStatusBlock block = (__bridge AFNetworkReachabilityStatusBlock)info;
-    if (block) {
-        block(status);
-    }
-
-    dispatch_async(dispatch_get_main_queue(), ^{
-        NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
-        [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:status] forKey:AFNetworkingReachabilityNotificationStatusItem]];
-    });
-}
-
-static const void * AFNetworkReachabilityRetainCallback(const void *info) {
-    return Block_copy(info);
-}
-
-static void AFNetworkReachabilityReleaseCallback(const void *info) {
-    if (info) {
-        Block_release(info);
-    }
-}
-
-- (void)startMonitoringNetworkReachability {
-    [self stopMonitoringNetworkReachability];
-
-    if (!self.baseURL) {
-        return;
-    }
-
-    self.networkReachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [[self.baseURL host] UTF8String]);
-
-    if (!self.networkReachability) {
-        return;
-    }
-
-    __weak __typeof(&*self)weakSelf = self;
-    AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) {
-        __strong __typeof(&*weakSelf)strongSelf = weakSelf;
-        if (!strongSelf) {
-            return;
-        }
-
-        strongSelf.networkReachabilityStatus = status;
-        if (strongSelf.networkReachabilityStatusBlock) {
-            strongSelf.networkReachabilityStatusBlock(status);
-        }
-    };
-
-    SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
-    SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
-
-    /* Network reachability monitoring does not establish a baseline for IP addresses as it does for hostnames, so if the base URL host is an IP address, the initial reachability callback is manually triggered.
-     */
-    if (AFURLHostIsIPAddress(self.baseURL)) {
-        SCNetworkReachabilityFlags flags;
-        SCNetworkReachabilityGetFlags(self.networkReachability, &flags);
-        dispatch_async(dispatch_get_main_queue(), ^{
-            AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
-            callback(status);
-        });
-    }
-
-    SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
-}
-
-- (void)stopMonitoringNetworkReachability {
-    if (self.networkReachability) {
-        SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
-
-        CFRelease(_networkReachability);
-        _networkReachability = NULL;
-    }
+- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username password:(NSString *)password {
+	NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password];
+    [self setValue:[NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)] forHTTPHeaderField:@"Authorization"];
 }
 
-- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block {
-    self.networkReachabilityStatusBlock = block;
+- (void)setAuthorizationHeaderFieldWithToken:(NSString *)token {
+    [self setValue:[NSString stringWithFormat:@"Token token=\"%@\"", token] forHTTPHeaderField:@"Authorization"];
 }
-#endif
-
-#pragma mark -
 
-- (BOOL)registerHTTPOperationClass:(Class)operationClass {
-    if (![operationClass isSubclassOfClass:[AFHTTPRequestOperation class]]) {
-        return NO;
-    }
-
-    NSString *className = NSStringFromClass(operationClass);
-    [self.registeredHTTPOperationClassNames removeObject:className];
-    [self.registeredHTTPOperationClassNames insertObject:className atIndex:0];
-
-    return YES;
-}
-
-- (void)unregisterHTTPOperationClass:(Class)operationClass {
-    NSString *className = NSStringFromClass(operationClass);
-    [self.registeredHTTPOperationClassNames removeObject:className];
+- (void)clearAuthorizationHeader {
+	[self.mutableHTTPRequestHeaders removeObjectForKey:@"Authorization"];
 }
 
 #pragma mark -
 
-- (NSString *)defaultValueForHeader:(NSString *)header {
-	return [self.defaultHeaders valueForKey:header];
+- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style {
+    self.queryStringSerializationStyle = style;
+    self.queryStringSerialization = nil;
 }
 
-- (void)setDefaultHeader:(NSString *)header value:(NSString *)value {
-	[self.defaultHeaders setValue:value forKey:header];
-}
-
-- (void)setAuthorizationHeaderWithUsername:(NSString *)username password:(NSString *)password {
-	NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password];
-    [self setDefaultHeader:@"Authorization" value:[NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)]];
-}
-
-- (void)setAuthorizationHeaderWithToken:(NSString *)token {
-    [self setDefaultHeader:@"Authorization" value:[NSString stringWithFormat:@"Token token=\"%@\"", token]];
-}
-
-- (void)clearAuthorizationHeader {
-	[self.defaultHeaders removeObjectForKey:@"Authorization"];
+- (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, NSDictionary *, NSError *__autoreleasing *))block {
+    self.queryStringSerialization = block;
 }
 
 #pragma mark -
 
 - (NSMutableURLRequest *)requestWithMethod:(NSString *)method
-                                      path:(NSString *)path
+                                 URLString:(NSString *)URLString
                                 parameters:(NSDictionary *)parameters
 {
     NSParameterAssert(method);
+    NSParameterAssert(URLString);
 
-    if (!path) {
-        path = @"";
-    }
+    NSURL *url = [NSURL URLWithString:URLString];
 
-    NSURL *url = [NSURL URLWithString:path relativeToURL:self.baseURL];
-	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
-    [request setHTTPMethod:method];
-    [request setAllHTTPHeaderFields:self.defaultHeaders];
+    NSParameterAssert(url);
 
-    if (parameters) {
-        if ([method isEqualToString:@"GET"] || [method isEqualToString:@"HEAD"] || [method isEqualToString:@"DELETE"]) {
-            url = [NSURL URLWithString:[[url absoluteString] stringByAppendingFormat:[path rangeOfString:@"?"].location == NSNotFound ? @"?%@" : @"&%@", AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding)]];
-            [request setURL:url];
-        } else {
-            NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
-            NSError *error = nil;
-
-            switch (self.parameterEncoding) {
-                case AFFormURLParameterEncoding:;
-                    [request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
-                    [request setHTTPBody:[AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding) dataUsingEncoding:self.stringEncoding]];
-                    break;
-                case AFJSONParameterEncoding:;
-                    [request setValue:[NSString stringWithFormat:@"application/json; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
-                    [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:(NSJSONWritingOptions)0 error:&error]];
-                    break;
-                case AFPropertyListParameterEncoding:;
-                    [request setValue:[NSString stringWithFormat:@"application/x-plist; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
-                    [request setHTTPBody:[NSPropertyListSerialization dataWithPropertyList:parameters format:NSPropertyListXMLFormat_v1_0 options:0 error:&error]];
-                    break;
-            }
+    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
+    [request setHTTPMethod:method];
 
-            if (error) {
-                NSLog(@"%@ %@: %@", [self class], NSStringFromSelector(_cmd), error);
-            }
-        }
-    }
+    request = [[self requestBySerializingRequest:request withParameters:parameters error:nil] mutableCopy];
 
 	return request;
 }
 
 - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
-                                                   path:(NSString *)path
+                                              URLString:(NSString *)URLString
                                              parameters:(NSDictionary *)parameters
                               constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
 {
     NSParameterAssert(method);
     NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]);
 
-    NSMutableURLRequest *request = [self requestWithMethod:method path:path parameters:nil];
+    NSMutableURLRequest *request = [self requestWithMethod:method URLString:URLString parameters:nil];
 
-    __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:request stringEncoding:self.stringEncoding];
+    __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:request stringEncoding:NSUTF8StringEncoding];
 
-    if (parameters) {
-        for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
-            NSData *data = nil;
-            if ([pair.value isKindOfClass:[NSData class]]) {
-                data = pair.value;
-            } else if ([pair.value isEqual:[NSNull null]]) {
-                data = [NSData data];
-            } else {
-                data = [[pair.value description] dataUsingEncoding:self.stringEncoding];
-            }
+    [parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
+        NSData *data = nil;
+        if ([obj isKindOfClass:[NSData class]]) {
+            data = obj;
+        } else if ([obj isEqual:[NSNull null]]) {
+            data = [NSData data];
+        } else {
+            data = [[obj description] dataUsingEncoding:NSUTF8StringEncoding];
+        }
 
-            if (data) {
-                [formData appendPartWithFormData:data name:[pair.field description]];
-            }
+        if (data) {
+            [formData appendPartWithFormData:data name:[key description]];
         }
-    }
+    }];
 
     if (block) {
         block(formData);
@@ -543,214 +306,78 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
     return [formData requestByFinalizingMultipartFormData];
 }
 
-- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
-                                                    success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
-                                                    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
-    AFHTTPRequestOperation *operation = nil;
-    
-    for (NSString *className in self.registeredHTTPOperationClassNames) {
-        Class operationClass = NSClassFromString(className);
-        if (operationClass && [operationClass canProcessRequest:urlRequest]) {
-            operation = [(AFHTTPRequestOperation *)[operationClass alloc] initWithRequest:urlRequest];
-            break;
-        }
-    }
-
-    if (!operation) {
-        operation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
-    }
-
-    [operation setCompletionBlockWithSuccess:success failure:failure];
-
-    operation.credential = self.defaultCredential;
-    operation.SSLPinningMode = self.defaultSSLPinningMode;
-    operation.allowsInvalidSSLCertificate = self.allowsInvalidSSLCertificate;
-
-    return operation;
-}
-
-#pragma mark -
-
-- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation {
-    [self.operationQueue addOperation:operation];
-}
+#pragma mark - AFURLRequestSerialization
 
-- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method
-                                     path:(NSString *)path
+- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
+                               withParameters:(NSDictionary *)parameters
+                                        error:(NSError *__autoreleasing *)error
 {
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wgnu"
-    NSString *pathToBeMatched = [[[self requestWithMethod:(method ?: @"GET") path:path parameters:nil] URL] path];
-#pragma clang diagnostic pop
-
-    for (NSOperation *operation in [self.operationQueue operations]) {
-        if (![operation isKindOfClass:[AFHTTPRequestOperation class]]) {
-            continue;
-        }
-
-        BOOL hasMatchingMethod = !method || [method isEqualToString:[[(AFHTTPRequestOperation *)operation request] HTTPMethod]];
-        BOOL hasMatchingPath = [[[[(AFHTTPRequestOperation *)operation request] URL] path] isEqual:pathToBeMatched];
-
-        if (hasMatchingMethod && hasMatchingPath) {
-            [operation cancel];
-        }
-    }
-}
+    NSParameterAssert(request);
 
-- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)urlRequests
-                                          progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
-                                        completionBlock:(void (^)(NSArray *operations))completionBlock
-{
-    NSMutableArray *mutableOperations = [NSMutableArray array];
-    for (NSURLRequest *request in urlRequests) {
-        AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:nil failure:nil];
-        [mutableOperations addObject:operation];
-    }
 
-    [self enqueueBatchOfHTTPRequestOperations:mutableOperations progressBlock:progressBlock completionBlock:completionBlock];
-}
+    NSMutableURLRequest *mutableRequest = [request mutableCopy];
 
-- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
-                              progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
-                            completionBlock:(void (^)(NSArray *operations))completionBlock
-{
-    __block dispatch_group_t dispatchGroup = dispatch_group_create();
-    NSBlockOperation *batchedOperation = [NSBlockOperation blockOperationWithBlock:^{
-        dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^{
-            if (completionBlock) {
-                completionBlock(operations);
-            }
-        });
-#if !OS_OBJECT_USE_OBJC
-        dispatch_release(dispatchGroup);
-#endif
+    [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL *stop) {
+        [mutableRequest setValue:value forHTTPHeaderField:field];
     }];
 
-    for (AFHTTPRequestOperation *operation in operations) {
-        AFCompletionBlock originalCompletionBlock = [operation.completionBlock copy];
-        __weak __typeof(&*operation)weakOperation = operation;
-        operation.completionBlock = ^{
-            __strong __typeof(&*weakOperation)strongOperation = weakOperation;
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wgnu"
-            dispatch_queue_t queue = strongOperation.successCallbackQueue ?: dispatch_get_main_queue();
-#pragma clang diagnostic pop
-            dispatch_group_async(dispatchGroup, queue, ^{
-                if (originalCompletionBlock) {
-                    originalCompletionBlock();
-                }
-
-                NSUInteger numberOfFinishedOperations = [[operations indexesOfObjectsPassingTest:^BOOL(id op, NSUInteger __unused idx,  BOOL __unused *stop) {
-                    return [op isFinished];
-                }] count];
-
-                if (progressBlock) {
-                    progressBlock(numberOfFinishedOperations, [operations count]);
-                }
-
-                dispatch_group_leave(dispatchGroup);
-            });
-        };
 
-        dispatch_group_enter(dispatchGroup);
-        [batchedOperation addDependency:operation];
+    if (!parameters) {
+        return mutableRequest;
     }
-    [self.operationQueue addOperations:operations waitUntilFinished:NO];
-    [self.operationQueue addOperation:batchedOperation];
-}
-
-#pragma mark -
-
-- (void)getPath:(NSString *)path
-     parameters:(NSDictionary *)parameters
-        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
-        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
-	NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:parameters];
-    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
-    [self enqueueHTTPRequestOperation:operation];
-}
 
-- (void)postPath:(NSString *)path
-      parameters:(NSDictionary *)parameters
-         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
-         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
-	NSURLRequest *request = [self requestWithMethod:@"POST" path:path parameters:parameters];
-	AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
-    [self enqueueHTTPRequestOperation:operation];
-}
-
-- (void)putPath:(NSString *)path
-     parameters:(NSDictionary *)parameters
-        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
-        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
-	NSURLRequest *request = [self requestWithMethod:@"PUT" path:path parameters:parameters];
-	AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
-    [self enqueueHTTPRequestOperation:operation];
-}
+    NSString *query = nil;
+    if (self.queryStringSerialization) {
+        query = self.queryStringSerialization(request, parameters, error);
+    } else {
+        switch (self.queryStringSerializationStyle) {
+            case AFHTTPRequestQueryStringDefaultStyle:
+                query = AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding);
+                break;
+            default:
+                break;
+        }
+    }
 
-- (void)deletePath:(NSString *)path
-        parameters:(NSDictionary *)parameters
-           success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
-           failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
-	NSURLRequest *request = [self requestWithMethod:@"DELETE" path:path parameters:parameters];
-	AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
-    [self enqueueHTTPRequestOperation:operation];
-}
+    if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
+        mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding)]];
+    } else {
+        NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
+        [mutableRequest setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
+        [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]];
+    }
 
-- (void)patchPath:(NSString *)path
-       parameters:(NSDictionary *)parameters
-          success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
-          failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
-    NSURLRequest *request = [self requestWithMethod:@"PATCH" path:path parameters:parameters];
-	AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
-    [self enqueueHTTPRequestOperation:operation];
+    return mutableRequest;
 }
 
 #pragma mark - NSCoding
 
 - (id)initWithCoder:(NSCoder *)aDecoder {
-    NSURL *baseURL = [aDecoder decodeObjectForKey:@"baseURL"];
-
-    self = [self initWithBaseURL:baseURL];
+    self = [self init];
     if (!self) {
         return nil;
     }
 
-    self.stringEncoding = [aDecoder decodeIntegerForKey:@"stringEncoding"];
-    self.parameterEncoding = (AFHTTPClientParameterEncoding) [aDecoder decodeIntegerForKey:@"parameterEncoding"];
-    self.registeredHTTPOperationClassNames = [aDecoder decodeObjectForKey:@"registeredHTTPOperationClassNames"];
-    self.defaultHeaders = [aDecoder decodeObjectForKey:@"defaultHeaders"];
+    self.mutableHTTPRequestHeaders = [aDecoder decodeObjectForKey:@"mutableHTTPRequestHeaders"];
+    self.queryStringSerializationStyle = (AFHTTPRequestQueryStringSerializationStyle)[aDecoder decodeIntegerForKey:@"queryStringSerializationStyle"];
 
     return self;
 }
 
 - (void)encodeWithCoder:(NSCoder *)aCoder {
-    [aCoder encodeObject:self.baseURL forKey:@"baseURL"];
-    [aCoder encodeInteger:(NSInteger)self.stringEncoding forKey:@"stringEncoding"];
-    [aCoder encodeInteger:self.parameterEncoding forKey:@"parameterEncoding"];
-    [aCoder encodeObject:self.registeredHTTPOperationClassNames forKey:@"registeredHTTPOperationClassNames"];
-    [aCoder encodeObject:self.defaultHeaders forKey:@"defaultHeaders"];
+    [aCoder encodeObject:self.mutableHTTPRequestHeaders forKey:@"mutableHTTPRequestHeaders"];
+    [aCoder encodeInteger:self.queryStringSerializationStyle forKey:@"queryStringSerializationStyle"];
 }
 
 #pragma mark - NSCopying
 
 - (id)copyWithZone:(NSZone *)zone {
-    AFHTTPClient *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL];
-
-    HTTPClient.stringEncoding = self.stringEncoding;
-    HTTPClient.parameterEncoding = self.parameterEncoding;
-    HTTPClient.registeredHTTPOperationClassNames = [self.registeredHTTPOperationClassNames mutableCopyWithZone:zone];
-    HTTPClient.defaultHeaders = [self.defaultHeaders mutableCopyWithZone:zone];
-#ifdef _SYSTEMCONFIGURATION_H
-    HTTPClient.networkReachabilityStatusBlock = self.networkReachabilityStatusBlock;
-#endif
-    return HTTPClient;
+    AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init];
+    serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone];
+    serializer.queryStringSerializationStyle = self.queryStringSerializationStyle;
+    serializer.queryStringSerialization = self.queryStringSerialization;
+    
+    return serializer;
 }
 
 @end
@@ -830,9 +457,6 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
 @end
 
 @implementation AFStreamingMultipartFormData
-@synthesize request = _request;
-@synthesize bodyStream = _bodyStream;
-@synthesize stringEncoding = _stringEncoding;
 
 - (id)initWithURLRequest:(NSMutableURLRequest *)urlRequest
           stringEncoding:(NSStringEncoding)encoding
@@ -858,7 +482,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
 
     NSString *fileName = [fileURL lastPathComponent];
     NSString *mimeType = AFContentTypeForPathExtension([fileURL pathExtension]);
-    
+
     return [self appendPartWithFileURL:fileURL name:name fileName:fileName mimeType:mimeType error:error];
 }
 
@@ -910,7 +534,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
 - (void)appendPartWithInputStream:(NSInputStream *)inputStream
                              name:(NSString *)name
                          fileName:(NSString *)fileName
-                           length:(unsigned long long)length
+                           length:(int64_t)length
                          mimeType:(NSString *)mimeType
 {
     NSParameterAssert(name);
@@ -1011,17 +635,6 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
 @end
 
 @implementation AFMultipartBodyStream
-@synthesize streamStatus = _streamStatus;
-@synthesize streamError = _streamError;
-@synthesize stringEncoding = _stringEncoding;
-@synthesize HTTPBodyParts = _HTTPBodyParts;
-@synthesize HTTPBodyPartEnumerator = _HTTPBodyPartEnumerator;
-@synthesize currentHTTPBodyPart = _currentHTTPBodyPart;
-@synthesize inputStream = _inputStream;
-@synthesize outputStream = _outputStream;
-@synthesize buffer = _buffer;
-@synthesize numberOfBytesInPacket = _numberOfBytesInPacket;
-@synthesize delay = _delay;
 
 - (id)initWithStringEncoding:(NSStringEncoding)encoding {
     self = [super init];
@@ -1087,7 +700,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
             }
         }
     }
-    
+
     return totalNumberOfBytesRead;
 }
 
@@ -1199,13 +812,6 @@ typedef enum {
 @end
 
 @implementation AFHTTPBodyPart
-@synthesize stringEncoding = _stringEncoding;
-@synthesize headers = _headers;
-@synthesize body = _body;
-@synthesize bodyContentLength = _bodyContentLength;
-@synthesize inputStream = _inputStream;
-@synthesize hasInitialBoundary = _hasInitialBoundary;
-@synthesize hasFinalBoundary = _hasFinalBoundary;
 
 - (id)init {
     self = [super init];
@@ -1383,13 +989,138 @@ typedef enum {
 
 - (id)copyWithZone:(NSZone *)zone {
     AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init];
-
+    
     bodyPart.stringEncoding = self.stringEncoding;
     bodyPart.headers = self.headers;
     bodyPart.bodyContentLength = self.bodyContentLength;
     bodyPart.body = self.body;
-
+    
     return bodyPart;
 }
 
 @end
+
+#pragma mark -
+
+@implementation AFJSONRequestSerializer
+
++ (instancetype)serializer {
+    return [self serializerWithWritingOptions:0];
+}
+
++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions
+{
+    AFJSONRequestSerializer *serializer = [[self alloc] init];
+    serializer.writingOptions = writingOptions;
+
+    return serializer;
+}
+
+#pragma mark - AFURLRequestSerialization
+
+- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
+                               withParameters:(NSDictionary *)parameters
+                                        error:(NSError *__autoreleasing *)error
+{
+    NSParameterAssert(request);
+
+    if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
+        return [super requestBySerializingRequest:request withParameters:parameters error:error];
+    }
+
+    NSMutableURLRequest *mutableRequest = [request mutableCopy];
+
+    [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL *stop) {
+        [mutableRequest setValue:value forHTTPHeaderField:field];
+    }];
+    
+    if (!parameters) {
+        return mutableRequest;
+    }
+
+    NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
+
+    [mutableRequest setValue:[NSString stringWithFormat:@"application/json; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
+    [mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]];
+
+    return mutableRequest;
+}
+
+@end
+
+#pragma mark -
+
+@implementation AFPropertyListRequestSerializer
+
++ (instancetype)serializer {
+    return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 writeOptions:0];
+}
+
++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
+                        writeOptions:(NSPropertyListWriteOptions)writeOptions
+{
+    AFPropertyListRequestSerializer *serializer = [[self alloc] init];
+    serializer.format = format;
+    serializer.writeOptions = writeOptions;
+
+    return serializer;
+}
+
+#pragma mark - AFURLRequestSerializer
+
+- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
+                               withParameters:(NSDictionary *)parameters
+                                        error:(NSError *__autoreleasing *)error
+{
+    NSParameterAssert(request);
+
+    if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
+        return [super requestBySerializingRequest:request withParameters:parameters error:error];
+    }
+
+    NSMutableURLRequest *mutableRequest = [request mutableCopy];
+
+    [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL *stop) {
+        [mutableRequest setValue:value forHTTPHeaderField:field];
+    }];
+
+    NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
+
+    [mutableRequest setValue:[NSString stringWithFormat:@"application/x-plist; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
+    [mutableRequest setHTTPBody:[NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error]];
+
+    return mutableRequest;
+}
+
+#pragma mark - NSCoding
+
+- (id)initWithCoder:(NSCoder *)aDecoder {
+    self = [super initWithCoder:aDecoder];
+    if (!self) {
+        return nil;
+    }
+
+    self.format = (NSPropertyListFormat)[aDecoder decodeIntegerForKey:@"format"];
+    self.writeOptions = [aDecoder decodeIntegerForKey:@"writeOptions"];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)aCoder {
+    [super encodeWithCoder:aCoder];
+
+    [aCoder encodeInteger:self.format forKey:@"format"];
+    [aCoder encodeInteger:self.writeOptions forKey:@"writeOptions"];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    AFPropertyListRequestSerializer *serializer = [[[self class] allocWithZone:zone] init];
+    serializer.format = self.format;
+    serializer.writeOptions = self.writeOptions;
+
+    return serializer;
+}
+
+@end

+ 258 - 0
AFNetworking/AFURLResponseSerialization.h

@@ -0,0 +1,258 @@
+// AFSerialization.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 <CoreGraphics/CoreGraphics.h>
+
+/**
+ The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data.
+
+ For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object.
+ */
+@protocol AFURLResponseSerialization <NSCoding, NSCopying>
+
+/**
+ The response object decoded from the data associated with a specified response.
+
+ @param response The response to be processed.
+ @param data The response data to be decoded.
+ @param error The error that occurred while attempting to decode the response data.
+
+ @return The object decoded from the specified response data.
+ */
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error;
+
+@end
+
+#pragma mark -
+
+/**
+ `AFHTTPSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.
+
+ Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPSerializer` in order to ensure consistent default behavior.
+ */
+@interface AFHTTPResponseSerializer : NSObject <AFURLResponseSerialization>
+
+/**
+ The string encoding used to serialize parameters.
+ */
+@property (nonatomic, assign) NSStringEncoding stringEncoding;
+
+/**
+ Creates and returns a serializer with default configuration.
+ */
++ (instancetype)serializer;
+
+///-----------------------------------------
+/// @name Configuring Response Serialization
+///-----------------------------------------
+
+/**
+ The acceptable HTTP status codes for responses. When non-`nil`, responses with status codes not contained by the set will result in an error during validation.
+
+ See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
+ */
+@property (nonatomic, strong) NSIndexSet *acceptableStatusCodes;
+
+/**
+ The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation.
+ */
+@property (nonatomic, strong) NSSet *acceptableContentTypes;
+
+/**
+ Validates the specified response and data.
+
+ In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks.
+
+ @param response The response to be validated.
+ @param data The data associated with the response.
+ @param error The error that occurred while attempting to validate the response.
+
+ @return `YES` if the response is valid, otherwise `NO`.
+ */
+- (BOOL)validateResponse:(NSHTTPURLResponse *)response
+                    data:(NSData *)data
+                   error:(NSError *__autoreleasing *)error;
+
+@end
+
+#pragma mark -
+
+
+/**
+ `AFJSONSerializer` is a subclass of `AFHTTPSerializer` that validates and decodes JSON responses.
+
+ By default, `AFJSONSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types:
+
+ - `application/json`
+ - `text/json`
+ */
+@interface AFJSONResponseSerializer : AFHTTPResponseSerializer
+
+/**
+ Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default.
+ */
+@property (nonatomic, assign) NSJSONReadingOptions readingOptions;
+
+/**
+ Creates and returns a JSON serializer with specified reading and writing options.
+
+ @param readingOptions The specified JSON reading options.
+ @param writingOptions The specified JSON writing options.
+ */
++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions;
+
+@end
+
+#pragma mark -
+
+/**
+ `AFXMLParserSerializer` is a subclass of `AFHTTPSerializer` that validates and decodes XML responses as an `NSXMLParser` objects.
+
+ By default, `AFXMLParserSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
+
+ - `application/xml`
+ - `text/xml`
+ */
+@interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer
+
+@end
+
+#pragma mark -
+
+#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
+
+/**
+ `AFXMLDocumentSerializer` is a subclass of `AFHTTPSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
+
+ By default, `AFXMLDocumentSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
+
+ - `application/xml`
+ - `text/xml`
+ */
+@interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer
+
+/**
+ Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default.
+ */
+@property (nonatomic, assign) NSUInteger options;
+
+/**
+ Creates and returns an XML document serializer with the specified options.
+
+ @param mask The XML document options.
+ */
++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask;
+
+@end
+
+#endif
+
+#pragma mark -
+
+/**
+ `AFPropertyListSerializer` is a subclass of `AFHTTPSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
+
+ By default, `AFPropertyListSerializer` accepts the following MIME types:
+
+ - `application/x-plist`
+ */
+@interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer
+
+/**
+ The property list format. Possible values are described in "NSPropertyListFormat".
+ */
+@property (nonatomic, assign) NSPropertyListFormat format;
+
+/**
+ The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions."
+ */
+@property (nonatomic, assign) NSPropertyListReadOptions readOptions;
+
+/**
+ Creates and returns a property list serializer with a specified format, read options, and write options.
+
+ @param format The property list format.
+ @param readOptions The property list reading options.
+ @param writeOptions The property list write options.
+ */
++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
+                         readOptions:(NSPropertyListReadOptions)readOptions;
+
+@end
+
+#pragma mark -
+
+/**
+ `AFImageSerializer` is a subclass of `AFHTTPSerializer` that validates and decodes image responses.
+
+ By default, `AFImageSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
+
+ - `image/tiff`
+ - `image/jpeg`
+ - `image/gif`
+ - `image/png`
+ - `image/ico`
+ - `image/x-icon`
+ - `image/bmp`
+ - `image/x-bmp`
+ - `image/x-xbitmap`
+ - `image/x-win-bitmap`
+ */
+@interface AFImageResponseSerializer : AFHTTPResponseSerializer
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+/**
+ The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance.
+ */
+@property (nonatomic, assign) CGFloat imageScale;
+
+/**
+ Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default.
+ */
+@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage;
+#endif
+
+@end
+
+#pragma mark -
+
+/**
+ `AFCompoundSerializer` is a subclass of `AFHTTPSerializer` that delegates the response serialization to the first `AFHTTPSerializer` object that returns `YES` to `validateResponse:data:error:`, falling back on the default behavior of `AFHTTPSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer.
+ */
+@interface AFCompoundResponseSerializer : AFHTTPResponseSerializer
+
+/**
+ The component response serializers.
+ */
+@property (readonly, nonatomic, strong) NSArray *responseSerializers;
+
+/**
+ Creates and returns a compound serializer comprised of the specified response serializers.
+
+ @warning Each response serializer specified must be a subclass of `AFHTTPSerializer`, and response to `-validateResponse:data:error:`.
+ */
++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers;
+
+@end

+ 713 - 0
AFNetworking/AFURLResponseSerialization.m

@@ -0,0 +1,713 @@
+// AFSerialization.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 "AFURLResponseSerialization.h"
+
+extern NSString * const AFNetworkingErrorDomain;
+extern NSString * const AFNetworkingOperationFailingURLResponseErrorKey;
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+#import <UIKit/UIKit.h>
+#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
+#import <Cocoa/Cocoa.h>
+#endif
+
+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;
+}
+
+@implementation AFHTTPResponseSerializer
+
++ (instancetype)serializer {
+    return [[self alloc] init];
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.stringEncoding = NSUTF8StringEncoding;
+
+    self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
+    self.acceptableContentTypes = nil;
+
+    return self;
+}
+
+#pragma mark -
+
+- (BOOL)validateResponse:(NSHTTPURLResponse *)response
+                    data:(NSData *)data
+                   error:(NSError *__autoreleasing *)error
+{
+    if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) {
+        if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:response.statusCode]) {
+            NSDictionary *userInfo = @{
+                                       NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected HTTP response status code in (%@), got %d", @"AFNetworking", nil), AFStringFromIndexSet(self.acceptableStatusCodes), response.statusCode],
+                                       NSURLErrorFailingURLErrorKey:[response URL],
+                                       AFNetworkingOperationFailingURLResponseErrorKey: response
+                                       };
+            if (error) {
+                *error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo];
+            }
+
+            return NO;
+        } else if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]]) {
+            // Don't invalidate content type if there is no content
+            if ([data length] > 0) {
+                NSDictionary *userInfo = @{
+                                           NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected HTTP response content-type %@, got %@", @"AFNetworking", nil), self.acceptableContentTypes, [response MIMEType]],
+                                           NSURLErrorFailingURLErrorKey:[response URL],
+                                           AFNetworkingOperationFailingURLResponseErrorKey: response
+                                           };
+                if (error) {
+                    *error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
+                }
+
+                return NO;
+            }
+        }
+    }
+
+    return YES;
+}
+
+#pragma mark - AFURLResponseSerialization
+
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    [self validateResponse:(NSHTTPURLResponse *)response data:data error:error];
+
+    return data;
+}
+
+#pragma mark - NSCoding
+
+- (id)initWithCoder:(NSCoder *)aDecoder {
+    self = [self init];
+    if (!self) {
+        return nil;
+    }
+
+    self.acceptableStatusCodes = [aDecoder decodeObjectForKey:@"acceptableStatusCodes"];
+    self.acceptableContentTypes = [aDecoder decodeObjectForKey:@"acceptableContentTypes"];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)aCoder {
+    [aCoder encodeObject:self.acceptableStatusCodes forKey:@"acceptableStatusCodes"];
+    [aCoder encodeObject:self.acceptableContentTypes forKey:@"acceptableContentTypes"];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
+    serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone];
+    serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone];
+
+    return serializer;
+}
+
+@end
+
+#pragma mark -
+
+@implementation AFJSONResponseSerializer
+
++ (instancetype)serializer {
+    return [self serializerWithReadingOptions:0];
+}
+
++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions {
+    AFJSONResponseSerializer *serializer = [[self alloc] init];
+    serializer.readingOptions = readingOptions;
+
+    return serializer;
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
+
+    return self;
+}
+
+
+
+#pragma mark - AFURLRequestSerialization
+
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
+        if ([(NSError *)(*error) code] == NSURLErrorCannotDecodeContentData) {
+            return nil;
+        }
+    }
+
+    // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization.
+    // See https://github.com/rails/rails/issues/1742
+    NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
+    if (responseString && ![responseString isEqualToString:@" "]) {
+        // Workaround for a bug in NSJSONSerialization when Unicode character escape codes are used instead of the actual character
+        // See http://stackoverflow.com/a/12843465/157142
+        data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
+
+        if (data) {
+            if ([data length] > 0) {
+                return [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:error];
+            } else {
+                return nil;
+            }
+        } else {
+            NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
+            [userInfo setValue:NSLocalizedStringFromTable(@"Data failed decoding as a UTF-8 string", nil, @"AFNetworking") forKey:NSLocalizedDescriptionKey];
+            [userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Could not decode string: %@", nil, @"AFNetworking"), responseString] forKey:NSLocalizedFailureReasonErrorKey];
+            if (error) {
+                *error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
+            }
+        }
+    }
+
+    return nil;
+}
+
+#pragma mark - NSCoding
+
+- (id)initWithCoder:(NSCoder *)aDecoder {
+    self = [super initWithCoder:aDecoder];
+    if (!self) {
+        return nil;
+    }
+
+    self.readingOptions = [aDecoder decodeIntegerForKey:@"readingOptions"];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)aCoder {
+    [super encodeWithCoder:aCoder];
+
+    [aCoder encodeInteger:self.readingOptions forKey:@"readingOptions"];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    AFJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
+    serializer.readingOptions = self.readingOptions;
+
+    return serializer;
+}
+
+@end
+
+#pragma mark -
+
+@implementation AFXMLParserResponseSerializer
+
++ (instancetype)serializer {
+    AFXMLParserResponseSerializer *serializer = [[self alloc] init];
+
+    return serializer;
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
+
+    return self;
+}
+
+#pragma mark - AFURLResponseSerialization
+
+- (id)responseObjectForResponse:(NSHTTPURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
+        if ([(NSError *)(*error) code] == NSURLErrorCannotDecodeContentData) {
+            return nil;
+        }
+    }
+
+    return [[NSXMLParser alloc] initWithData:data];
+}
+
+@end
+
+#pragma mark -
+
+#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
+
+@implementation AFXMLDocumentResponseSerializer
+
++ (instancetype)serializer {
+    return [self serializerWithXMLDocumentOptions:0];
+}
+
++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask {
+    AFXMLDocumentResponseSerializer *serializer = [[self alloc] init];
+    serializer.options = mask;
+
+    return serializer;
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
+
+    return self;
+}
+
+#pragma mark - AFURLResponseSerialization
+
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
+        if ([(NSError *)(*error) code] == NSURLErrorCannotDecodeContentData) {
+            return nil;
+        }
+    }
+
+    return [[NSXMLDocument alloc] initWithData:data options:self.options error:error];
+}
+
+#pragma mark - NSCoding
+
+- (id)initWithCoder:(NSCoder *)aDecoder {
+    self = [super initWithCoder:aDecoder];
+    if (!self) {
+        return nil;
+    }
+
+    self.options = [aDecoder decodeIntegerForKey:@"options"];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)aCoder {
+    [super encodeWithCoder:aCoder];
+
+    [aCoder encodeInteger:self.options forKey:@"options"];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    AFXMLDocumentResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
+    serializer.options = self.options;
+
+    return serializer;
+}
+
+@end
+
+#endif
+
+#pragma mark -
+
+@implementation AFPropertyListResponseSerializer
+
++ (instancetype)serializer {
+    return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0];
+}
+
++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
+                         readOptions:(NSPropertyListReadOptions)readOptions
+{
+    AFPropertyListResponseSerializer *serializer = [[self alloc] init];
+    serializer.format = format;
+    serializer.readOptions = readOptions;
+
+    return serializer;
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil];
+
+    return self;
+}
+
++ (NSSet *)acceptablePathExtensions {
+    static NSSet * _acceptablePathExtension = nil;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        _acceptablePathExtension = [[NSSet alloc] initWithObjects:@"plist", nil];
+    });
+
+    return _acceptablePathExtension;
+}
+
+#pragma mark - AFURLResponseSerialization
+
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
+        if ([(NSError *)(*error) code] == NSURLErrorCannotDecodeContentData) {
+            return nil;
+        }
+    }
+
+    return [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:nil error:error];
+}
+
+#pragma mark - NSCoding
+
+- (id)initWithCoder:(NSCoder *)aDecoder {
+    self = [super initWithCoder:aDecoder];
+    if (!self) {
+        return nil;
+    }
+
+    self.format = (NSPropertyListFormat)[aDecoder decodeIntegerForKey:@"format"];
+    self.readOptions = [aDecoder decodeIntegerForKey:@"readOptions"];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)aCoder {
+    [super encodeWithCoder:aCoder];
+
+    [aCoder encodeInteger:self.format forKey:@"format"];
+    [aCoder encodeInteger:self.readOptions forKey:@"readOptions"];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    AFPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
+    serializer.format = self.format;
+    serializer.readOptions = self.readOptions;
+
+    return serializer;
+}
+
+@end
+
+#pragma mark -
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+#import <CoreGraphics/CoreGraphics.h>
+
+static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) {
+    UIImage *image = [[UIImage alloc] initWithData:data];
+
+    return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation];
+}
+
+static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) {
+    if (!data || [data length] == 0) {
+        return nil;
+    }
+
+    CGImageRef imageRef = nil;
+    CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
+
+    if ([response.MIMEType isEqualToString:@"image/png"]) {
+        imageRef = CGImageCreateWithPNGDataProvider(dataProvider,  NULL, true, kCGRenderingIntentDefault);
+    } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) {
+        imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
+    }
+
+    if (!imageRef) {
+        UIImage *image = AFImageWithDataAtScale(data, scale);
+        if (image.images) {
+            CGDataProviderRelease(dataProvider);
+
+            return image;
+        }
+
+        imageRef = CGImageCreateCopy([image CGImage]);
+    }
+
+    CGDataProviderRelease(dataProvider);
+
+    if (!imageRef) {
+        return nil;
+    }
+
+    size_t width = CGImageGetWidth(imageRef);
+    size_t height = CGImageGetHeight(imageRef);
+
+    if (width * height > 1024 * 1024) {
+        CGImageRelease(imageRef);
+
+        return AFImageWithDataAtScale(data, scale);
+    }
+
+    size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
+    size_t bytesPerRow = 0; // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate()
+    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
+    CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
+
+    if (CGColorSpaceGetNumberOfComponents(colorSpace) == 3) {
+        uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask);
+        if (alpha == kCGImageAlphaNone) {
+            bitmapInfo &= ~kCGBitmapAlphaInfoMask;
+            bitmapInfo |= kCGImageAlphaNoneSkipFirst;
+        } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) {
+            bitmapInfo &= ~kCGBitmapAlphaInfoMask;
+            bitmapInfo |= kCGImageAlphaPremultipliedFirst;
+        }
+    }
+
+    CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
+
+    CGColorSpaceRelease(colorSpace);
+
+    if (!context) {
+        CGImageRelease(imageRef);
+
+        return AFImageWithDataAtScale(data, scale);
+    }
+
+    CGRect rect = CGRectMake(0.0f, 0.0f, width, height);
+    CGContextDrawImage(context, rect, imageRef);
+    CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context);
+    CGContextRelease(context);
+
+    UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:UIImageOrientationUp];
+    CGImageRelease(inflatedImageRef);
+    CGImageRelease(imageRef);
+
+    return inflatedImage;
+}
+#endif
+
+
+@implementation AFImageResponseSerializer
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+    self.imageScale = [[UIScreen mainScreen] scale];
+    self.automaticallyInflatesResponseImage = YES;
+#endif
+
+    return self;
+}
+
++ (NSSet *)acceptablePathExtensions {
+    static NSSet * _acceptablePathExtension = nil;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        _acceptablePathExtension = [[NSSet alloc] initWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil];
+    });
+
+    return _acceptablePathExtension;
+}
+
+#pragma mark - AFURLResponseSerializer
+
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
+        if ([(NSError *)(*error) code] == NSURLErrorCannotDecodeContentData) {
+            return nil;
+        }
+    }
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+    if (self.automaticallyInflatesResponseImage) {
+        return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale);
+    } else {
+        return AFImageWithDataAtScale(data, self.imageScale);
+    }
+#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
+    // Ensure that the image is set to it's correct pixel width and height
+    NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data];
+    NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
+    [image addRepresentation:bitimage];
+
+    return image;
+#endif
+
+    return nil;
+}
+
+#pragma mark - NSCoding
+
+- (id)initWithCoder:(NSCoder *)aDecoder {
+    self = [super initWithCoder:aDecoder];
+    if (!self) {
+        return nil;
+    }
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+    self.imageScale = [aDecoder decodeFloatForKey:@"imageScale"];
+    self.automaticallyInflatesResponseImage = [aDecoder decodeBoolForKey:@"automaticallyInflatesResponseImage"];
+#endif
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)aCoder {
+    [super encodeWithCoder:aCoder];
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+    [aCoder encodeFloat:self.imageScale forKey:@"imageScale"];
+    [aCoder encodeBool:self.automaticallyInflatesResponseImage forKey:@"automaticallyInflatesResponseImage"];
+#endif
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    AFImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+    serializer.imageScale = self.imageScale;
+    serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage;
+#endif
+
+    return serializer;
+}
+
+@end
+
+#pragma mark -
+
+@interface AFCompoundResponseSerializer ()
+@property (readwrite, nonatomic, strong) NSArray *responseSerializers;
+@end
+
+@implementation AFCompoundResponseSerializer
+
++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers {
+    AFCompoundResponseSerializer *serializer = [[self alloc] init];
+    serializer.responseSerializers = responseSerializers;
+
+    return serializer;
+}
+
+#pragma mark - AFURLResponseSerialization
+
+- (id)responseObjectForResponse:(NSURLResponse *)response
+                           data:(NSData *)data
+                          error:(NSError *__autoreleasing *)error
+{
+    for (id serializer in self.responseSerializers) {
+        if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) {
+            continue;
+        }
+
+        id responseObject = [serializer responseObjectForResponse:response data:data error:error];
+        if (responseObject) {
+            return responseObject;
+        }
+    }
+    
+    return [super responseObjectForResponse:response data:data error:error];
+}
+
+#pragma mark - NSCoding
+
+- (id)initWithCoder:(NSCoder *)aDecoder {
+    self = [super initWithCoder:aDecoder];
+    if (!self) {
+        return nil;
+    }
+
+    self.responseSerializers = [aDecoder decodeObjectForKey:@"responseSerializers"];
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)aCoder {
+    [super encodeWithCoder:aCoder];
+
+    [aCoder encodeObject:self.responseSerializers forKey:@"responseSerializers"];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    AFCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
+    serializer.responseSerializers = self.responseSerializers;
+
+    return serializer;
+}
+
+@end

+ 429 - 0
AFNetworking/AFURLSessionManager.h

@@ -0,0 +1,429 @@
+// AFURLSessionManager.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 "AFURLResponseSerialization.h"
+#import "AFURLRequestSerialization.h"
+#import "AFSecurityPolicy.h"
+#import "AFNetworkReachabilityManager.h"
+
+/**
+ `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
+ 
+ ## Subclassing Notes
+ 
+ This is the base class for `AFHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `AFURLSessionManager` specifically for HTTP, consider subclassing `AFHTTPSessionManager` instead.
+ 
+ ## NSURLSession & NSURLSessionTask Delegate Methods
+ 
+ `AFURLSessionManager` implements the following delegate methods:
+ 
+ ### `NSURLSessionDelegate`
+ 
+ - `URLSession:didBecomeInvalidWithError:`
+ - `URLSession:didReceiveChallenge:completionHandler:`
+
+ ### `NSURLSessionTaskDelegate`
+ 
+ - `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`
+ - `URLSession:task:didReceiveChallenge:completionHandler:`
+ - `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`
+ - `URLSession:task:didCompleteWithError:`
+
+ ### `NSURLSessionDataDelegate`
+ 
+ - `URLSession:dataTask:didReceiveResponse:completionHandler:`
+ - `URLSession:dataTask:didBecomeDownloadTask:`
+ - `URLSession:dataTask:didReceiveData:`
+ - `URLSession:dataTask:willCacheResponse:completionHandler:`
+ - `URLSessionDidFinishEventsForBackgroundURLSession:`
+
+ ### `NSURLSessionDownloadDelegate`
+
+ - `URLSession:downloadTask:didFinishDownloadingToURL:`
+ - `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`
+ - `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`
+ 
+ If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
+ 
+ ## 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 Caveats
+ 
+ - Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`.
+
+ ## NSCopying Caveats
+
+ - `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original.
+ - Operation copies do not include any delegate callback blocks, as they often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ session manager when copied.
+ */
+@interface AFURLSessionManager : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSCoding, NSCopying>
+
+/**
+ The managed session.
+ */
+@property (readonly, nonatomic, strong) NSURLSession *session;
+
+/**
+ The operation queue on which delegate callbacks are run.
+ */
+@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;
+
+/**
+ 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) id <AFURLResponseSerialization> responseSerializer;
+
+///-------------------------------
+/// @name Managing Security Policy
+///-------------------------------
+
+/**
+ The security policy used by created request operations to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified.
+ */
+@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
+
+///--------------------------------------
+/// @name Monitoring Network Reachability
+///--------------------------------------
+
+/**
+ The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default.
+ */
+@property (readonly, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
+
+///----------------------------
+/// @name Getting Session Tasks
+///----------------------------
+
+/**
+ The data, upload, and download tasks currently run by the managed session.
+ */
+@property (readonly, nonatomic, strong) NSArray *tasks;
+
+/**
+ The data tasks currently run by the managed session.
+ */
+@property (readonly, nonatomic, strong) NSArray *dataTasks;
+
+/**
+ The upload tasks currently run by the managed session.
+ */
+@property (readonly, nonatomic, strong) NSArray *uploadTasks;
+
+/**
+ The download tasks currently run by the managed session.
+ */
+@property (readonly, nonatomic, strong) NSArray *downloadTasks;
+
+///---------------------------------
+/// @name Managing Callback Queues
+///---------------------------------
+
+/**
+ The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
+ */
+@property (nonatomic, strong) dispatch_queue_t completionQueue;
+
+/**
+ The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
+ */
+@property (nonatomic, strong) dispatch_group_t completionGroup;
+
+///---------------------
+/// @name Initialization
+///---------------------
+
+/**
+ Creates and returns a manager for a session created with the specified configuration. This is the designated initializer.
+ 
+ @param configuration The configuration used to create the managed session.
+ 
+ @return A manager for a newly-created session.
+ */
+- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration;
+
+/**
+ Invalidates the managed session, optionally canceling pending tasks.
+ 
+ @param cancelPendingTasks Whether or not to cancel pending tasks.
+ */
+- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks;
+
+///-------------------------
+/// @name Running Data Tasks
+///-------------------------
+
+/**
+ Creates an `NSURLSessionDataTask` with the specified request.
+
+ @param request The HTTP request for the request.
+ @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occured, if any.
+ */
+- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
+                            completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler;
+
+///---------------------------
+/// @name Running Upload Tasks
+///---------------------------
+
+/**
+ Creates an `NSURLSessionUploadTask` with the specified request for a local file.
+
+ @param request The HTTP request for the request.
+ @param fileURL A URL to the local file to be uploaded.
+ @param progress A block object to be executed multiple times as data is uploaded. This block has no return value and takes three arguments: the number of bytes written since the last time the progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body.
+ @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occured, if any.
+ */
+- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
+                                         fromFile:(NSURL *)fileURL
+                                         progress:(NSProgress * __autoreleasing *)progress
+                                completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler;
+
+/**
+ Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body.
+
+ @param request The HTTP request for the request.
+ @param bodyData A data object containing the HTTP body to be uploaded.
+ @param progress A block object to be executed multiple times as data is uploaded. This block has no return value and takes three arguments: the number of bytes written since the last time the progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body.
+ @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occured, if any.
+ */
+- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
+                                         fromData:(NSData *)bodyData
+                                         progress:(NSProgress * __autoreleasing *)progress
+                                completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler;
+
+/**
+ Creates an `NSURLSessionUploadTask` with the specified streaming request.
+
+ @param request The HTTP request for the request.
+ @param progress A block object to be executed multiple times as data is uploaded. This block has no return value and takes three arguments: the number of bytes written since the last time the progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body.
+ @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occured, if any.
+ */
+- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
+                                                 progress:(NSProgress * __autoreleasing *)progress
+                                        completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler;
+
+///-----------------------------
+/// @name Running Download Tasks
+///-----------------------------
+
+/**
+ Creates an `NSURLSessionDownloadTask` with the specified request.
+
+ @param request The HTTP request for the request.
+ @param progress A block object to be executed multiple times as data is downloaded. This block has no return value and takes three arguments: the number of bytes read since the last time the progress block was called, the total bytes read, and the total bytes expected to be read from the server, as initially determined by the expected content size of the response object.
+ @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL.
+ @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any.
+ */
+- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
+                                             progress:(NSProgress * __autoreleasing *)progress
+                                          destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
+                                    completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler;
+
+/**
+ Creates an `NSURLSessionDownloadTask` with the specified resume data.
+
+ @param resumeData The data used to resume downloading.
+ @param progress A block object to be executed multiple times as data is downloaded. This block has no return value and takes three arguments: the number of bytes read since the last time the progress block was called, the total bytes read, and the total bytes expected to be read from the server, as initially determined by the expected content size of the response object.
+ @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL.
+ @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any.
+ */
+- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
+                                                progress:(NSProgress * __autoreleasing *)progress
+                                             destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
+                                       completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler;
+
+///-----------------------------------------
+/// @name Setting Session Delegate Callbacks
+///-----------------------------------------
+
+/**
+ Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`.
+ 
+ @param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation.
+ */
+- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block;
+
+/**
+ Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`.
+
+ @param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge.
+ */
+- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block;
+
+///--------------------------------------
+/// @name Setting Task Delegate Callbacks
+///--------------------------------------
+
+/**
+ Sets a block to be executed when an HTTP request is attempting to perform a redirection to a different URL, as handled by the `NSURLSessionTaskDelegate` method `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`.
+ 
+ @param block A block object to be executed when an HTTP rquest is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response.
+ */
+- (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block;
+
+/**
+ Sets a block to be executed when a session task has received a request specific authentication challenge, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didReceiveChallenge:completionHandler:`.
+ 
+ @param block A block object to be executed when a session task has received a request specific authentication challenge. The block returns the disposition of the authentication challenge, and takes four arguments: the session, the task, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge.
+ */
+- (void)setTaskDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block;
+
+/**
+ Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
+ 
+ @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes five arguments: the session, the task, the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread.
+ */
+- (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block;
+
+/**
+ Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`.
+ 
+ @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task.
+ */
+- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block;
+
+///-------------------------------------------
+/// @name Setting Data Task Delegate Callbacks
+///-------------------------------------------
+
+/**
+ Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
+
+ @param block A block object to be executed when a data task has received a response. The block returns the disposition of the session response, and takes three arguments: the session, the data task, and the received response.
+ */
+- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block;
+
+/**
+ Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`.
+ 
+ @param block A block object to be executed when a data task has become a download task. The block has no return value, and takes three arguments: the session, the data task, and the download task it has become.
+ */
+- (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block;
+
+/**
+ Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`.
+ 
+ @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the session, the data task, and the data received. This block may be called multiple times, and will execute on the session manager operation queue.
+ */
+- (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block;
+
+/**
+ Sets a block to be executed to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:willCacheResponse:completionHandler:`.
+ 
+ @param block A block object to be executed to determine the caching behavior of a data task. The block returns the response to cache, and takes three arguments: the session, the data task, and the proposed cached URL response.
+ */
+- (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block;
+
+/**
+ Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`.
+ 
+ @param block A block object to be executed once all messages enqueued for a session have been delivered. The block has no return value and takes a single argument: the session.
+ */
+- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block;
+
+///-----------------------------------------------
+/// @name Setting Download Task Delegate Callbacks
+///-----------------------------------------------
+
+/**
+ Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`.
+ 
+ @param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error.
+ */
+- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block;
+
+/**
+ Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`.
+ 
+ @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes five arguments: the session, the download task, the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the session manager operation queue.
+ */
+- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block;
+
+/**
+ Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
+ 
+ @param block A block object to be executed when a download task has been resumed. The block has no return value and takes four arguments: the session, the download task, the file offset of the resumed download, and the total number of bytes expected to be downloaded.
+ */
+- (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block;
+
+@end
+
+///--------------------
+/// @name Notifications
+///--------------------
+
+/**
+ Posted when a task begins executing.
+ */
+extern NSString * const AFNetworkingTaskDidStartNotification;
+
+/**
+ Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task.
+ */
+extern NSString * const AFNetworkingTaskDidFinishNotification;
+
+/**
+ Posted when a task suspends its execution.
+ */
+extern NSString * const AFNetworkingTaskDidSuspendNotification;
+
+/**
+ Posted when a session is invalidated.
+ */
+extern NSString * const AFURLSessionDidInvalidateNotification;
+
+/**
+ Posted when a session download task encountered an error when moving the temporary download file to a specified destination.
+ */
+extern NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification;
+
+/**
+ The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if response data exists for the task.
+ */
+extern NSString * const AFNetworkingTaskDidFinishResponseDataKey;
+
+/**
+ The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the response was serialized.
+ */
+extern NSString * const AFNetworkingTaskDidFinishSerializedResponseKey;
+
+/**
+ The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the task has an associated response serializer.
+ */
+extern NSString * const AFNetworkingTaskDidFinishResponseSerializerKey;
+
+/**
+ The file path assoicated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an the response data has been stored directly to disk.
+ */
+extern NSString * const AFNetworkingTaskDidFinishAssetPathKey;
+
+/**
+ Any error assoicated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an error exists.
+ */
+extern NSString * const AFNetworkingTaskDidFinishErrorKey;

+ 839 - 0
AFNetworking/AFURLSessionManager.m

@@ -0,0 +1,839 @@
+// AFURLSessionManager.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 "AFURLSessionManager.h"
+
+static dispatch_queue_t url_session_manager_processing_queue() {
+    static dispatch_queue_t af_url_session_manager_processing_queue;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        af_url_session_manager_processing_queue = dispatch_queue_create("com.alamofire.networking.session.manager.processing", DISPATCH_QUEUE_CONCURRENT);
+    });
+
+    return af_url_session_manager_processing_queue;
+}
+
+static dispatch_group_t url_session_manager_completion_group() {
+    static dispatch_group_t af_url_session_manager_completion_group;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        af_url_session_manager_completion_group = dispatch_group_create();
+    });
+
+    return af_url_session_manager_completion_group;
+}
+
+NSString * const AFNetworkingTaskDidStartNotification = @"com.alamofire.networking.task.start";
+NSString * const AFNetworkingTaskDidFinishNotification = @"com.alamofire.networking.task.finish";
+NSString * const AFNetworkingTaskDidFinishResponseDataKey = @"com.alamofire.networking.task.finish.responsedata";
+NSString * const AFNetworkingTaskDidSuspendNotification = @"com.alamofire.networking.task.suspend";
+NSString * const AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate";
+NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error";
+
+NSString * const AFNetworkingTaskDidFinishSerializedResponseKey = @"com.alamofire.networking.task.finish.serializedresponse";
+NSString * const AFNetworkingTaskDidFinishResponseSerializerKey = @"com.alamofire.networking.task.finish.responseserializer";
+NSString * const AFNetworkingTaskDidFinishErrorKey = @"com.alamofire.networking.task.finish.error";
+NSString * const AFNetworkingTaskDidFinishAssetPathKey = @"com.alamofire.networking.task.finish.assetpath";
+
+static void * AFTaskStateChangedContext = &AFTaskStateChangedContext;
+
+typedef void (^AFURLSessionDidBecomeInvalidBlock)(NSURLSession *session, NSError *error);
+typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential);
+
+typedef NSURLRequest * (^AFURLSessionTaskWillPerformHTTPRedirectionBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request);
+typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionTaskDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential);
+
+typedef NSInputStream * (^AFURLSessionTaskNeedNewBodyStreamBlock)(NSURLSession *session, NSURLSessionTask *task);
+typedef void (^AFURLSessionTaskDidSendBodyDataBlock)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend);
+typedef void (^AFURLSessionTaskDidCompleteBlock)(NSURLSession *session, NSURLSessionTask *task, NSError *error);
+
+typedef NSURLSessionResponseDisposition (^AFURLSessionDataTaskDidReceiveResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response);
+typedef void (^AFURLSessionDataTaskDidBecomeDownloadTaskBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask);
+typedef void (^AFURLSessionDataTaskDidReceiveDataBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data);
+typedef NSCachedURLResponse * (^AFURLSessionDataTaskWillCacheResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse);
+typedef void (^AFURLSessionDidFinishEventsForBackgroundURLSessionBlock)(NSURLSession *session);
+
+typedef NSURL * (^AFURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location);
+typedef void (^AFURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite);
+typedef void (^AFURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes);
+
+typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error);
+
+#pragma mark -
+
+@interface AFURLSessionManagerTaskDelegate : NSObject <NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>
+@property (nonatomic, weak) AFURLSessionManager *manager;
+@property (nonatomic, strong) NSMutableData *mutableData;
+@property (nonatomic, strong) NSProgress *uploadProgress;
+@property (nonatomic, strong) NSProgress *downloadProgress;
+@property (nonatomic, copy) NSURL *downloadFileURL;
+@property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading;
+@property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler;
+
++ (instancetype)delegateForManager:(AFURLSessionManager *)manager
+                 completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler;
+
+@end
+
+@implementation AFURLSessionManagerTaskDelegate
+
++ (instancetype)delegateForManager:(AFURLSessionManager *)manager
+                 completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
+{
+    AFURLSessionManagerTaskDelegate *delegate = [[self alloc] init];
+    delegate.manager = manager;
+    delegate.completionHandler = completionHandler;
+
+    return delegate;
+}
+
+- (instancetype)init {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    self.mutableData = [NSMutableData data];
+
+    return self;
+}
+
+#pragma mark - NSURLSessionTaskDelegate
+
+- (void)URLSession:(NSURLSession *)session
+              task:(NSURLSessionTask *)task
+   didSendBodyData:(int64_t)bytesSent
+    totalBytesSent:(int64_t)totalBytesSent
+totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
+{
+    self.uploadProgress.completedUnitCount = totalBytesSent;
+    self.uploadProgress.totalUnitCount = totalBytesExpectedToSend;
+}
+
+- (void)URLSession:(NSURLSession *)session
+              task:(NSURLSessionTask *)task
+didCompleteWithError:(NSError *)error
+{
+    if (self.completionHandler) {
+        __block id responseObject = nil;
+
+        __block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
+        userInfo[AFNetworkingTaskDidFinishResponseSerializerKey] = self.manager.responseSerializer;
+
+        if (self.downloadFileURL) {
+            userInfo[AFNetworkingTaskDidFinishAssetPathKey] = self.downloadFileURL;
+        } else if (self.mutableData) {
+            userInfo[AFNetworkingTaskDidFinishResponseDataKey] = [NSData dataWithData:self.mutableData];
+        }
+
+        if (error) {
+            userInfo[AFNetworkingTaskDidFinishErrorKey] = error;
+
+            dispatch_group_async(self.manager.completionGroup ?: url_session_manager_completion_group(), self.manager.completionQueue ?: dispatch_get_main_queue(), ^{
+                if (self.completionHandler) {
+                    self.completionHandler(task.response, responseObject, error);
+                }
+
+                [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidFinishNotification object:task userInfo:userInfo];
+            });
+        } else {
+            dispatch_async(url_session_manager_processing_queue(), ^{
+                NSError *serializationError = nil;
+                if (self.downloadFileURL) {
+                    responseObject = self.downloadFileURL;
+                } else {
+                    responseObject = [self.manager.responseSerializer responseObjectForResponse:task.response data:[NSData dataWithData:self.mutableData] error:&serializationError];
+                }
+
+                if (responseObject) {
+                    userInfo[AFNetworkingTaskDidFinishSerializedResponseKey] = responseObject;
+                }
+
+                if (serializationError) {
+                    userInfo[AFNetworkingTaskDidFinishErrorKey] = serializationError;
+                }
+
+                dispatch_group_async(self.manager.completionGroup ?: url_session_manager_completion_group(), self.manager.completionQueue ?: dispatch_get_main_queue(), ^{
+                    if (self.completionHandler) {
+                        self.completionHandler(task.response, responseObject, serializationError);
+                    }
+                    
+                    [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidFinishNotification object:task userInfo:userInfo];
+                });
+            });
+        }
+    }
+}
+
+#pragma mark - NSURLSessionDataTaskDelegate
+
+- (void)URLSession:(NSURLSession *)session
+          dataTask:(NSURLSessionDataTask *)dataTask
+    didReceiveData:(NSData *)data
+{
+    [self.mutableData appendData:data];
+
+    self.downloadProgress.totalUnitCount += [data length];
+}
+
+#pragma mark - NSURLSessionDownloadTaskDelegate
+
+- (void)URLSession:(NSURLSession *)session
+      downloadTask:(NSURLSessionDownloadTask *)downloadTask
+didFinishDownloadingToURL:(NSURL *)location
+{
+    NSError *fileManagerError = nil;
+    self.downloadFileURL = nil;
+
+    if (self.downloadTaskDidFinishDownloading) {
+        self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
+        if (self.downloadFileURL) {
+            [[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError];
+
+            if (fileManagerError) {
+                [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo];
+            }
+        }
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session
+      downloadTask:(NSURLSessionDownloadTask *)downloadTask
+      didWriteData:(int64_t)bytesWritten
+ totalBytesWritten:(int64_t)totalBytesWritten
+totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
+{
+    self.downloadProgress.completedUnitCount = totalBytesWritten;
+    self.downloadProgress.totalUnitCount = totalBytesExpectedToWrite;
+}
+
+- (void)URLSession:(NSURLSession *)session
+      downloadTask:(NSURLSessionDownloadTask *)downloadTask
+ didResumeAtOffset:(int64_t)fileOffset
+expectedTotalBytes:(int64_t)expectedTotalBytes {}
+
+@end
+
+#pragma mark -
+
+@interface AFURLSessionManager ()
+@property (readwrite, nonatomic, strong) NSURLSessionConfiguration *sessionConfiguration;
+@property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue;
+@property (readwrite, nonatomic, strong) NSURLSession *session;
+@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableTaskDelegatesKeyedByTaskIdentifier;
+@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
+@property (readwrite, nonatomic, copy) AFURLSessionDidBecomeInvalidBlock sessionDidBecomeInvalid;
+@property (readwrite, nonatomic, copy) AFURLSessionDidReceiveAuthenticationChallengeBlock sessionDidReceiveAuthenticationChallenge;
+@property (readwrite, nonatomic, copy) AFURLSessionTaskWillPerformHTTPRedirectionBlock taskWillPerformHTTPRedirection;
+@property (readwrite, nonatomic, copy) AFURLSessionTaskDidReceiveAuthenticationChallengeBlock taskDidReceiveAuthenticationChallenge;
+@property (readwrite, nonatomic, copy) AFURLSessionTaskNeedNewBodyStreamBlock taskNeedNewBodyStream;
+@property (readwrite, nonatomic, copy) AFURLSessionTaskDidSendBodyDataBlock taskDidSendBodyData;
+@property (readwrite, nonatomic, copy) AFURLSessionTaskDidCompleteBlock taskDidComplete;
+@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveResponseBlock dataTaskDidReceiveResponse;
+@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidBecomeDownloadTaskBlock dataTaskDidBecomeDownloadTask;
+@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveDataBlock dataTaskDidReceiveData;
+@property (readwrite, nonatomic, copy) AFURLSessionDataTaskWillCacheResponseBlock dataTaskWillCacheResponse;
+@property (readwrite, nonatomic, copy) AFURLSessionDidFinishEventsForBackgroundURLSessionBlock didFinishEventsForBackgroundURLSession;
+@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading;
+@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidWriteDataBlock downloadTaskDidWriteData;
+@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidResumeBlock downloadTaskDidResume;
+@end
+
+@implementation AFURLSessionManager
+
+- (instancetype)init {
+    return [self initWithSessionConfiguration:nil];
+}
+
+- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
+    self = [super init];
+    if (!self) {
+        return nil;
+    }
+
+    if (!configuration) {
+        configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
+    }
+
+    self.operationQueue = [[NSOperationQueue alloc] init];
+    self.operationQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount;
+
+    self.responseSerializer = [AFJSONResponseSerializer serializer];
+
+    self.sessionConfiguration = configuration;
+    self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue];
+
+    self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init];
+
+    self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
+
+    return self;
+}
+
+- (NSString *)description {
+    return [NSString stringWithFormat:@"<%@: %p, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, self.session, self.operationQueue];
+}
+
+#pragma mark -
+
+- (NSArray *)tasksForKeyPath:(NSString *)keyPath {
+    __block NSArray *tasks = nil;
+    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
+    [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
+        if ([keyPath isEqualToString:@"dataTasks"]) {
+            tasks = dataTasks;
+        } else if ([keyPath isEqualToString:@"uploadTasks"]) {
+            tasks = uploadTasks;
+        } else if ([keyPath isEqualToString:@"downloadTasks"]) {
+            tasks = downloadTasks;
+        } else if ([keyPath isEqualToString:@"tasks"]) {
+            tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"];
+        }
+
+        dispatch_semaphore_signal(semaphore);
+    }];
+
+    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
+
+    return tasks;
+}
+
+- (NSArray *)tasks {
+    return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
+}
+
+- (NSArray *)dataTasks {
+    return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
+}
+
+- (NSArray *)uploadTasks {
+    return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
+}
+
+- (NSArray *)downloadTasks {
+    return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
+}
+
+#pragma mark -
+
+- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks {
+    if (cancelPendingTasks) {
+        [self.session invalidateAndCancel];
+    } else {
+        [self.session finishTasksAndInvalidate];
+    }
+}
+
+#pragma mark -
+
+- (void)setResponseSerializer:(id <AFURLResponseSerialization>)responseSerializer {
+    NSParameterAssert(responseSerializer);
+
+    _responseSerializer = responseSerializer;
+}
+
+#pragma mark -
+
+- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
+                            completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
+{
+    NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:request];
+
+    AFURLSessionManagerTaskDelegate *delegate = [AFURLSessionManagerTaskDelegate delegateForManager:self completionHandler:completionHandler];
+
+    self.mutableTaskDelegatesKeyedByTaskIdentifier[@(dataTask.taskIdentifier)] = delegate;
+
+    [dataTask addObserver:self forKeyPath:@"state" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:AFTaskStateChangedContext];
+
+    return dataTask;
+}
+
+#pragma mark -
+
+- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
+                                         fromFile:(NSURL *)fileURL
+                                         progress:(NSProgress * __autoreleasing *)progress
+                                completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
+{
+    NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL];
+
+    return [self uploadTaskWithTask:uploadTask progress:progress completionHandler:completionHandler];
+}
+
+- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
+                                         fromData:(NSData *)bodyData
+                                         progress:(NSProgress * __autoreleasing *)progress
+                                completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
+{
+    NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithRequest:request fromData:bodyData];
+
+    return [self uploadTaskWithTask:uploadTask progress:progress completionHandler:completionHandler];
+}
+
+- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
+                                                 progress:(NSProgress * __autoreleasing *)progress
+                                        completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
+{
+    NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithStreamedRequest:request];
+
+    return [self uploadTaskWithTask:uploadTask progress:progress completionHandler:completionHandler];
+}
+
+- (NSURLSessionUploadTask *)uploadTaskWithTask:(NSURLSessionUploadTask *)uploadTask
+                                      progress:(NSProgress * __autoreleasing *)progress
+                             completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
+{
+    AFURLSessionManagerTaskDelegate *delegate = [AFURLSessionManagerTaskDelegate delegateForManager:self completionHandler:completionHandler];
+
+    delegate.uploadProgress = [NSProgress progressWithTotalUnitCount:uploadTask.countOfBytesExpectedToSend];
+    delegate.uploadProgress.pausingHandler = ^{
+        [uploadTask suspend];
+    };
+    delegate.uploadProgress.cancellationHandler = ^{
+        [uploadTask cancel];
+    };
+
+    if (progress) {
+        *progress = delegate.uploadProgress;
+    }
+
+    self.mutableTaskDelegatesKeyedByTaskIdentifier[@(uploadTask.taskIdentifier)] = delegate;
+
+    [uploadTask addObserver:self forKeyPath:@"state" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:AFTaskStateChangedContext];
+    
+    return uploadTask;
+}
+
+#pragma mark -
+
+- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
+                                             progress:(NSProgress * __autoreleasing *)progress
+                                          destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
+                                    completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
+{
+    NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithRequest:request];
+
+    return [self downloadTaskWithTask:downloadTask progress:progress destination:destination completionHandler:completionHandler];
+}
+
+- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
+                                                progress:(NSProgress * __autoreleasing *)progress
+                                             destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
+                                       completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
+{
+    NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithResumeData:resumeData];
+
+    return [self downloadTaskWithTask:downloadTask progress:progress destination:destination completionHandler:completionHandler];
+}
+
+- (NSURLSessionDownloadTask *)downloadTaskWithTask:(NSURLSessionDownloadTask *)downloadTask
+                                          progress:(NSProgress * __autoreleasing *)progress
+                                       destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
+                                 completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
+{
+    AFURLSessionManagerTaskDelegate *delegate = [AFURLSessionManagerTaskDelegate delegateForManager:self completionHandler:completionHandler];
+    delegate.downloadTaskDidFinishDownloading = ^ NSURL * (NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location) {
+        if (destination) {
+            return destination(location, task.response);
+        }
+
+        return location;
+    };
+
+    if (progress) {
+        *progress = delegate.downloadProgress;
+    }
+
+    self.mutableTaskDelegatesKeyedByTaskIdentifier[@(downloadTask.taskIdentifier)] = delegate;
+
+    [downloadTask addObserver:self forKeyPath:@"state" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:AFTaskStateChangedContext];
+
+    return downloadTask;
+}
+
+#pragma mark -
+
+- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block {
+    self.sessionDidBecomeInvalid = block;
+}
+
+- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block {
+    self.sessionDidReceiveAuthenticationChallenge = block;
+}
+
+#pragma mark -
+
+- (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block {
+    self.taskWillPerformHTTPRedirection = block;
+}
+
+- (void)setTaskDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block {
+    self.taskDidReceiveAuthenticationChallenge = block;
+}
+
+- (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block {
+    self.taskDidSendBodyData = block;
+}
+
+- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block {
+    self.taskDidComplete = block;
+}
+
+#pragma mark -
+
+- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block {
+    self.dataTaskDidReceiveResponse = block;
+}
+
+- (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block {
+    self.dataTaskDidBecomeDownloadTask = block;
+}
+
+- (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block {
+    self.dataTaskDidReceiveData = block;
+}
+
+- (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block {
+    self.dataTaskWillCacheResponse = block;
+}
+
+- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block {
+    self.didFinishEventsForBackgroundURLSession = block;
+}
+
+#pragma mark -
+
+- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block {
+    self.downloadTaskDidFinishDownloading = block;
+}
+
+- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block {
+    self.downloadTaskDidWriteData = block;
+}
+
+- (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block {
+    self.downloadTaskDidResume = block;
+}
+
+#pragma mark - NSURLSessionDelegate
+
+- (void)URLSession:(NSURLSession *)session
+didBecomeInvalidWithError:(NSError *)error
+{
+    if (self.sessionDidBecomeInvalid) {
+        self.sessionDidBecomeInvalid(session, error);
+    }
+   
+   [self.mutableTaskDelegatesKeyedByTaskIdentifier removeAllObjects];
+
+    [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDidInvalidateNotification object:session];
+}
+
+- (void)URLSession:(NSURLSession *)session
+didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
+ completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
+{
+    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
+    __block NSURLCredential *credential = nil;
+
+    if (self.sessionDidReceiveAuthenticationChallenge) {
+        disposition = self.sessionDidReceiveAuthenticationChallenge(session, challenge, &credential);
+    } else {
+        if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
+            if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
+                if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust]) {
+                    disposition = NSURLSessionAuthChallengeUseCredential;
+                    credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
+                } else {
+                    disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
+                }
+            } else {
+                disposition = NSURLSessionAuthChallengePerformDefaultHandling;
+            }
+        }
+    }
+
+    if (completionHandler) {
+        completionHandler(disposition, credential);
+    }
+}
+
+#pragma mark - NSURLSessionTaskDelegate
+
+- (void)URLSession:(NSURLSession *)session
+              task:(NSURLSessionTask *)task
+willPerformHTTPRedirection:(NSHTTPURLResponse *)response
+        newRequest:(NSURLRequest *)request
+ completionHandler:(void (^)(NSURLRequest *))completionHandler
+{
+    NSURLRequest *redirectRequest = request;
+
+    if (self.taskWillPerformHTTPRedirection) {
+        redirectRequest = self.taskWillPerformHTTPRedirection(session, task, response, request);
+    }
+
+    if (completionHandler) {
+        completionHandler(redirectRequest);
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session
+              task:(NSURLSessionTask *)task
+didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
+ completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
+{
+    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
+    __block NSURLCredential *credential = nil;
+
+    if (self.taskDidReceiveAuthenticationChallenge) {
+        disposition = self.taskDidReceiveAuthenticationChallenge(session, task, challenge, &credential);
+    } else {
+        if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
+            if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust]) {
+                disposition = NSURLSessionAuthChallengeUseCredential;
+                credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
+            } else {
+                disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
+            }
+        } else {
+            disposition = NSURLSessionAuthChallengePerformDefaultHandling;
+        }
+    }
+
+    if (completionHandler) {
+        completionHandler(disposition, credential);
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session
+              task:(NSURLSessionTask *)task
+ needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler
+{
+    NSInputStream *inputStream = nil;
+    
+    if (self.taskNeedNewBodyStream) {
+        inputStream = self.taskNeedNewBodyStream(session, task);
+    } else if (task.originalRequest.HTTPBodyStream && [task.originalRequest.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) {
+        inputStream = [task.originalRequest.HTTPBodyStream copy];
+    }
+
+    if (completionHandler) {
+        completionHandler(inputStream);
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session
+              task:(NSURLSessionTask *)task
+   didSendBodyData:(int64_t)bytesSent
+    totalBytesSent:(int64_t)totalBytesSent
+totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
+{
+    AFURLSessionManagerTaskDelegate *delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)];
+    [delegate URLSession:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalBytesExpectedToSend];
+
+    if (self.taskDidSendBodyData) {
+        self.taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend);
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session
+              task:(NSURLSessionTask *)task
+didCompleteWithError:(NSError *)error
+{
+    AFURLSessionManagerTaskDelegate *delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)];
+    [delegate URLSession:session task:task didCompleteWithError:error];
+
+    if (self.taskDidComplete) {
+        self.taskDidComplete(session, task, error);
+    }
+
+    [self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)];
+}
+
+#pragma mark - NSURLSessionDataDelegate
+
+- (void)URLSession:(NSURLSession *)session
+          dataTask:(NSURLSessionDataTask *)dataTask
+didReceiveResponse:(NSURLResponse *)response
+ completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
+{
+    NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow;
+
+    if (self.dataTaskDidReceiveResponse) {
+        disposition = self.dataTaskDidReceiveResponse(session, dataTask, response);
+    }
+
+    if (completionHandler) {
+        completionHandler(disposition);
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session
+          dataTask:(NSURLSessionDataTask *)dataTask
+didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
+{
+    if (self.dataTaskDidBecomeDownloadTask) {
+        self.dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask);
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session
+          dataTask:(NSURLSessionDataTask *)dataTask
+    didReceiveData:(NSData *)data
+{
+    AFURLSessionManagerTaskDelegate *delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(dataTask.taskIdentifier)];
+    [delegate URLSession:session dataTask:dataTask didReceiveData:data];
+
+    if (self.dataTaskDidReceiveData) {
+        self.dataTaskDidReceiveData(session, dataTask, data);
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session
+          dataTask:(NSURLSessionDataTask *)dataTask
+ willCacheResponse:(NSCachedURLResponse *)proposedResponse
+ completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler
+{
+    NSCachedURLResponse *cachedResponse = proposedResponse;
+
+    if (self.dataTaskWillCacheResponse) {
+       cachedResponse = self.dataTaskWillCacheResponse(session, dataTask, proposedResponse);
+    }
+
+    if (completionHandler) {
+        completionHandler(cachedResponse);
+    }
+}
+
+- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
+    if (self.didFinishEventsForBackgroundURLSession) {
+        self.didFinishEventsForBackgroundURLSession(session);
+    }
+   
+   [self.mutableTaskDelegatesKeyedByTaskIdentifier removeAllObjects];
+}
+
+#pragma mark - NSURLSessionDownloadDelegate
+
+- (void)URLSession:(NSURLSession *)session
+      downloadTask:(NSURLSessionDownloadTask *)downloadTask
+didFinishDownloadingToURL:(NSURL *)location
+{
+    AFURLSessionManagerTaskDelegate *delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(downloadTask.taskIdentifier)];
+    if (delegate) {
+        [delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location];
+    } else if (self.downloadTaskDidFinishDownloading) {
+        NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
+        if (fileURL) {
+            NSError *error = nil;
+            [[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error];
+            if (error) {
+                [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo];
+            }
+        }
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session
+      downloadTask:(NSURLSessionDownloadTask *)downloadTask
+      didWriteData:(int64_t)bytesWritten
+ totalBytesWritten:(int64_t)totalBytesWritten
+totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
+{
+    AFURLSessionManagerTaskDelegate *delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(downloadTask.taskIdentifier)];
+    [delegate URLSession:session downloadTask:downloadTask didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite];
+
+    if (self.downloadTaskDidWriteData) {
+        self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
+    }
+}
+
+- (void)URLSession:(NSURLSession *)session
+      downloadTask:(NSURLSessionDownloadTask *)downloadTask
+ didResumeAtOffset:(int64_t)fileOffset
+expectedTotalBytes:(int64_t)expectedTotalBytes
+{
+    if (self.downloadTaskDidResume) {
+        self.downloadTaskDidResume(session, downloadTask, fileOffset, expectedTotalBytes);
+    }
+}
+
+#pragma mark - NSKeyValueObserving
+
+- (void)observeValueForKeyPath:(NSString *)keyPath
+                      ofObject:(id)object
+                        change:(NSDictionary *)change
+                       context:(void *)context
+{
+    if (context == AFTaskStateChangedContext && [keyPath isEqualToString:@"state"]) {
+        NSString *notificationName = nil;
+        switch ([(NSURLSessionTask *)object state]) {
+            case NSURLSessionTaskStateRunning:
+                notificationName = AFNetworkingTaskDidStartNotification;
+                break;
+            case NSURLSessionTaskStateSuspended:
+                notificationName = AFNetworkingTaskDidSuspendNotification;
+                break;
+            case NSURLSessionTaskStateCompleted:
+                // AFNetworkingTaskDidFinishNotification posted by task completion handlers
+                @try {
+                    [object removeObserver:self forKeyPath:@"state" context:AFTaskStateChangedContext];
+                } @catch (NSException *exception) {}
+                break;
+            default:
+                break;
+        }
+
+        if (notificationName) {
+            dispatch_async(dispatch_get_main_queue(), ^{
+                [[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:object];
+            });
+        }
+    } else {
+        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
+    }
+}
+
+#pragma mark - NSCoding
+
+- (id)initWithCoder:(NSCoder *)aDecoder {
+    NSURLSessionConfiguration *configuration = [aDecoder decodeObjectForKey:@"sessionConfiguration"];
+
+    self = [self initWithSessionConfiguration:configuration];
+    if (!self) {
+        return nil;
+    }
+
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)aCoder {
+    [aCoder encodeObject:self.session.configuration forKey:@"sessionConfiguration"];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+    return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration];
+}
+
+@end

+ 0 - 89
AFNetworking/AFXMLRequestOperation.h

@@ -1,89 +0,0 @@
-// AFXMLRequestOperation.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 "AFHTTPRequestOperation.h"
-
-#import <Availability.h>
-
-/**
- `AFXMLRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with XML response data.
-
- ## Acceptable Content Types
-
- By default, `AFXMLRequestOperation` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
-
- - `application/xml`
- - `text/xml`
-
- ## Use With AFHTTPClient
-
- When `AFXMLRequestOperation` is registered with `AFHTTPClient`, the response object in the success callback of `HTTPRequestOperationWithRequest:success:failure:` will be an instance of `NSXMLParser`. On platforms that support `NSXMLDocument`, you have the option to ignore the response object, and simply use the `responseXMLDocument` property of the operation argument of the callback.
- */
-@interface AFXMLRequestOperation : AFHTTPRequestOperation
-
-///----------------------------
-/// @name Getting Response Data
-///----------------------------
-
-/**
- An `NSXMLParser` object constructed from the response data.
- */
-@property (readonly, nonatomic, strong) NSXMLParser *responseXMLParser;
-
-#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
-/**
- An `NSXMLDocument` object constructed from the response data. If an error occurs while parsing, `nil` will be returned, and the `error` property will be set to the error.
- */
-@property (readonly, nonatomic, strong) NSXMLDocument *responseXMLDocument;
-#endif
-
-/**
- Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks.
-
- @param urlRequest The request object to be loaded asynchronously during execution of the operation
- @param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the XML parser constructed with the response data of request.
- @param failure A block object to be executed when the operation finishes unsuccessfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network error that occurred.
-
- @return A new XML request operation
- */
-+ (instancetype)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest
-											 success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success
-											 failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser))failure;
-
-
-#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
-/**
- Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks.
-
- @param urlRequest The request object to be loaded asynchronously during execution of the operation
- @param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the XML document created from the response data of request.
- @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data as XML. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred.
-
- @return A new XML request operation
- */
-+ (instancetype)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest
-											   success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success
-											   failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLDocument *document))failure;
-#endif
-
-@end

+ 0 - 167
AFNetworking/AFXMLRequestOperation.m

@@ -1,167 +0,0 @@
-// AFXMLRequestOperation.m
-//
-// 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 "AFXMLRequestOperation.h"
-
-#include <Availability.h>
-
-static dispatch_queue_t xml_request_operation_processing_queue() {
-    static dispatch_queue_t af_xml_request_operation_processing_queue;
-    static dispatch_once_t onceToken;
-    dispatch_once(&onceToken, ^{
-        af_xml_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.xml-request.processing", DISPATCH_QUEUE_CONCURRENT);
-    });
-
-    return af_xml_request_operation_processing_queue;
-}
-
-@interface AFXMLRequestOperation ()
-@property (readwrite, nonatomic, strong) NSXMLParser *responseXMLParser;
-#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
-@property (readwrite, nonatomic, strong) NSXMLDocument *responseXMLDocument;
-#endif
-@property (readwrite, nonatomic, strong) NSError *XMLError;
-@end
-
-@implementation AFXMLRequestOperation
-@synthesize responseXMLParser = _responseXMLParser;
-#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
-@synthesize responseXMLDocument = _responseXMLDocument;
-#endif
-@synthesize XMLError = _XMLError;
-
-+ (instancetype)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest
-											 success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success
-											 failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser))failure
-{
-    AFXMLRequestOperation *requestOperation = [(AFXMLRequestOperation *)[self alloc] initWithRequest:urlRequest];
-    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
-        if (success) {
-            success(operation.request, operation.response, responseObject);
-        }
-    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
-        if (failure) {
-            failure(operation.request, operation.response, error, [(AFXMLRequestOperation *)operation responseXMLParser]);
-        }
-    }];
-
-    return requestOperation;
-}
-
-#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
-+ (instancetype)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest
-											   success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success
-											   failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLDocument *document))failure
-{
-    AFXMLRequestOperation *requestOperation = [[self alloc] initWithRequest:urlRequest];
-    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, __unused id responseObject) {
-        if (success) {
-            NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument];
-            success(operation.request, operation.response, XMLDocument);
-        }
-    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
-        if (failure) {
-            NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument];
-            failure(operation.request, operation.response, error, XMLDocument);
-        }
-    }];
-
-    return requestOperation;
-}
-#endif
-
-
-- (NSXMLParser *)responseXMLParser {
-    if (!_responseXMLParser && [self.responseData length] > 0 && [self isFinished]) {
-        self.responseXMLParser = [[NSXMLParser alloc] initWithData:self.responseData];
-    }
-
-    return _responseXMLParser;
-}
-
-#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
-- (NSXMLDocument *)responseXMLDocument {
-    if (!_responseXMLDocument && [self.responseData length] > 0 && [self isFinished]) {
-        NSError *error = nil;
-        self.responseXMLDocument = [[NSXMLDocument alloc] initWithData:self.responseData options:0 error:&error];
-        self.XMLError = error;
-    }
-
-    return _responseXMLDocument;
-}
-#endif
-
-- (NSError *)error {
-    if (_XMLError) {
-        return _XMLError;
-    } else {
-        return [super error];
-    }
-}
-
-#pragma mark - NSOperation
-
-- (void)cancel {
-    [super cancel];
-
-    self.responseXMLParser.delegate = nil;
-}
-
-#pragma mark - AFHTTPRequestOperation
-
-+ (NSSet *)acceptableContentTypes {
-    return [NSSet setWithObjects:@"application/xml", @"text/xml", nil];
-}
-
-+ (BOOL)canProcessRequest:(NSURLRequest *)request {
-    return [[[request URL] pathExtension] isEqualToString:@"xml"] || [super canProcessRequest:request];
-}
-
-- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
-                              failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Warc-retain-cycles"
-#pragma clang diagnostic ignored "-Wgnu"
-    self.completionBlock = ^ {
-        dispatch_async(xml_request_operation_processing_queue(), ^(void) {
-            NSXMLParser *XMLParser = self.responseXMLParser;
-
-            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, XMLParser);
-                    });
-                }
-            }
-        });
-    };
-#pragma clang diagnostic pop
-}
-
-@end

+ 6 - 30
Example/AFNetworking Mac Example.xcodeproj/project.pbxproj

@@ -15,13 +15,9 @@
 		F8129C6F15910B15009BFE23 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = F8129C6E15910B15009BFE23 /* main.m */; };
 		F8129C7115910B3E009BFE23 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = F8129C7015910B3E009BFE23 /* MainMenu.xib */; };
 		F8129C7715910C40009BFE23 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = F8129C7515910C40009BFE23 /* AppDelegate.m */; };
-		F82EB07C159A172000B10B56 /* AFHTTPClient.m in Sources */ = {isa = PBXBuildFile; fileRef = F82EB06E159A172000B10B56 /* AFHTTPClient.m */; };
+		F82EB07C159A172000B10B56 /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = F82EB06E159A172000B10B56 /* AFHTTPSessionManager.m */; };
 		F82EB07D159A172000B10B56 /* AFHTTPRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F82EB070159A172000B10B56 /* AFHTTPRequestOperation.m */; };
-		F82EB07E159A172000B10B56 /* AFImageRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F82EB072159A172000B10B56 /* AFImageRequestOperation.m */; };
-		F82EB07F159A172000B10B56 /* AFJSONRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F82EB074159A172000B10B56 /* AFJSONRequestOperation.m */; };
-		F82EB080159A172000B10B56 /* AFPropertyListRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F82EB077159A172000B10B56 /* AFPropertyListRequestOperation.m */; };
 		F82EB081159A172000B10B56 /* AFURLConnectionOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F82EB079159A172000B10B56 /* AFURLConnectionOperation.m */; };
-		F82EB082159A172000B10B56 /* AFXMLRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F82EB07B159A172000B10B56 /* AFXMLRequestOperation.m */; };
 		F88812F216C533E9003C8B8C /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F88812F116C533E9003C8B8C /* Security.framework */; };
 		F8A847CF161F55A500940F39 /* CoreServices.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8A847CE161F55A500940F39 /* CoreServices.framework */; };
 		F8A847D2161F55AC00940F39 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8A847D1161F55AC00940F39 /* SystemConfiguration.framework */; };
@@ -44,21 +40,13 @@
 		F8129C7015910B3E009BFE23 /* MainMenu.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = MainMenu.xib; sourceTree = SOURCE_ROOT; };
 		F8129C7515910C40009BFE23 /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = SOURCE_ROOT; };
 		F8129C7615910C40009BFE23 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = SOURCE_ROOT; };
-		F82EB06D159A172000B10B56 /* AFHTTPClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFHTTPClient.h; path = ../AFNetworking/AFHTTPClient.h; sourceTree = "<group>"; };
-		F82EB06E159A172000B10B56 /* AFHTTPClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPClient.m; path = ../AFNetworking/AFHTTPClient.m; sourceTree = "<group>"; };
+		F82EB06D159A172000B10B56 /* AFHTTPSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFHTTPSessionManager.h; path = ../AFNetworking/AFHTTPSessionManager.h; sourceTree = "<group>"; };
+		F82EB06E159A172000B10B56 /* AFHTTPSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPSessionManager.m; path = ../AFNetworking/AFHTTPSessionManager.m; sourceTree = "<group>"; };
 		F82EB06F159A172000B10B56 /* AFHTTPRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFHTTPRequestOperation.h; path = ../AFNetworking/AFHTTPRequestOperation.h; sourceTree = "<group>"; };
 		F82EB070159A172000B10B56 /* AFHTTPRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPRequestOperation.m; path = ../AFNetworking/AFHTTPRequestOperation.m; sourceTree = "<group>"; };
-		F82EB071159A172000B10B56 /* AFImageRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFImageRequestOperation.h; path = ../AFNetworking/AFImageRequestOperation.h; sourceTree = "<group>"; };
-		F82EB072159A172000B10B56 /* AFImageRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageRequestOperation.m; path = ../AFNetworking/AFImageRequestOperation.m; sourceTree = "<group>"; };
-		F82EB073159A172000B10B56 /* AFJSONRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFJSONRequestOperation.h; path = ../AFNetworking/AFJSONRequestOperation.h; sourceTree = "<group>"; };
-		F82EB074159A172000B10B56 /* AFJSONRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFJSONRequestOperation.m; path = ../AFNetworking/AFJSONRequestOperation.m; sourceTree = "<group>"; };
 		F82EB075159A172000B10B56 /* AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFNetworking.h; path = ../AFNetworking/AFNetworking.h; sourceTree = "<group>"; };
-		F82EB076159A172000B10B56 /* AFPropertyListRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFPropertyListRequestOperation.h; path = ../AFNetworking/AFPropertyListRequestOperation.h; sourceTree = "<group>"; };
-		F82EB077159A172000B10B56 /* AFPropertyListRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFPropertyListRequestOperation.m; path = ../AFNetworking/AFPropertyListRequestOperation.m; sourceTree = "<group>"; };
 		F82EB078159A172000B10B56 /* AFURLConnectionOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFURLConnectionOperation.h; path = ../AFNetworking/AFURLConnectionOperation.h; sourceTree = "<group>"; };
 		F82EB079159A172000B10B56 /* AFURLConnectionOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFURLConnectionOperation.m; path = ../AFNetworking/AFURLConnectionOperation.m; sourceTree = "<group>"; };
-		F82EB07A159A172000B10B56 /* AFXMLRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFXMLRequestOperation.h; path = ../AFNetworking/AFXMLRequestOperation.h; sourceTree = "<group>"; };
-		F82EB07B159A172000B10B56 /* AFXMLRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFXMLRequestOperation.m; path = ../AFNetworking/AFXMLRequestOperation.m; sourceTree = "<group>"; };
 		F877018B159A1CE700B45C0D /* AFNetworking Example.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = "AFNetworking Example.entitlements"; sourceTree = "<group>"; };
 		F88812F116C533E9003C8B8C /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; };
 		F8A847CE161F55A500940F39 /* CoreServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreServices.framework; path = System/Library/Frameworks/CoreServices.framework; sourceTree = SDKROOT; };
@@ -176,16 +164,8 @@
 				F82EB079159A172000B10B56 /* AFURLConnectionOperation.m */,
 				F82EB06F159A172000B10B56 /* AFHTTPRequestOperation.h */,
 				F82EB070159A172000B10B56 /* AFHTTPRequestOperation.m */,
-				F82EB073159A172000B10B56 /* AFJSONRequestOperation.h */,
-				F82EB074159A172000B10B56 /* AFJSONRequestOperation.m */,
-				F82EB07A159A172000B10B56 /* AFXMLRequestOperation.h */,
-				F82EB07B159A172000B10B56 /* AFXMLRequestOperation.m */,
-				F82EB076159A172000B10B56 /* AFPropertyListRequestOperation.h */,
-				F82EB077159A172000B10B56 /* AFPropertyListRequestOperation.m */,
-				F82EB06D159A172000B10B56 /* AFHTTPClient.h */,
-				F82EB06E159A172000B10B56 /* AFHTTPClient.m */,
-				F82EB071159A172000B10B56 /* AFImageRequestOperation.h */,
-				F82EB072159A172000B10B56 /* AFImageRequestOperation.m */,
+				F82EB06D159A172000B10B56 /* AFHTTPSessionManager.h */,
+				F82EB06E159A172000B10B56 /* AFHTTPSessionManager.m */,
 			);
 			name = AFNetworking;
 			sourceTree = "<group>";
@@ -257,13 +237,9 @@
 				F8129C321591073C009BFE23 /* AFAppDotNetAPIClient.m in Sources */,
 				F8129C6F15910B15009BFE23 /* main.m in Sources */,
 				F8129C7715910C40009BFE23 /* AppDelegate.m in Sources */,
-				F82EB07C159A172000B10B56 /* AFHTTPClient.m in Sources */,
+				F82EB07C159A172000B10B56 /* AFHTTPSessionManager.m in Sources */,
 				F82EB07D159A172000B10B56 /* AFHTTPRequestOperation.m in Sources */,
-				F82EB07E159A172000B10B56 /* AFImageRequestOperation.m in Sources */,
-				F82EB07F159A172000B10B56 /* AFJSONRequestOperation.m in Sources */,
-				F82EB080159A172000B10B56 /* AFPropertyListRequestOperation.m in Sources */,
 				F82EB081159A172000B10B56 /* AFURLConnectionOperation.m in Sources */,
-				F82EB082159A172000B10B56 /* AFXMLRequestOperation.m in Sources */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};

+ 96 - 0
Example/AFNetworking Mac Example.xcodeproj/xcshareddata/xcschemes/AFNetworking Example.xcscheme

@@ -0,0 +1,96 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Scheme
+   LastUpgradeVersion = "0500"
+   version = "1.3">
+   <BuildAction
+      parallelizeBuildables = "YES"
+      buildImplicitDependencies = "YES">
+      <BuildActionEntries>
+         <BuildActionEntry
+            buildForTesting = "YES"
+            buildForRunning = "YES"
+            buildForProfiling = "YES"
+            buildForArchiving = "YES"
+            buildForAnalyzing = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "F8129BFA1591061B009BFE23"
+               BuildableName = "AFNetworking Example.app"
+               BlueprintName = "AFNetworking Example"
+               ReferencedContainer = "container:AFNetworking Mac Example.xcodeproj">
+            </BuildableReference>
+         </BuildActionEntry>
+      </BuildActionEntries>
+   </BuildAction>
+   <TestAction
+      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+      shouldUseLaunchSchemeArgsEnv = "YES"
+      buildConfiguration = "Debug">
+      <Testables>
+         <TestableReference
+            skipped = "NO">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "2902D28B17DF4E2900C81C5A"
+               BuildableName = "OS X Tests.xctest"
+               BlueprintName = "OS X Tests"
+               ReferencedContainer = "container:../Tests/AFNetworking Tests.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+      </Testables>
+      <MacroExpansion>
+         <BuildableReference
+            BuildableIdentifier = "primary"
+            BlueprintIdentifier = "F8129BFA1591061B009BFE23"
+            BuildableName = "AFNetworking Example.app"
+            BlueprintName = "AFNetworking Example"
+            ReferencedContainer = "container:AFNetworking Mac Example.xcodeproj">
+         </BuildableReference>
+      </MacroExpansion>
+   </TestAction>
+   <LaunchAction
+      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+      launchStyle = "0"
+      useCustomWorkingDirectory = "NO"
+      buildConfiguration = "Debug"
+      ignoresPersistentStateOnLaunch = "NO"
+      debugDocumentVersioning = "YES"
+      allowLocationSimulation = "YES">
+      <BuildableProductRunnable>
+         <BuildableReference
+            BuildableIdentifier = "primary"
+            BlueprintIdentifier = "F8129BFA1591061B009BFE23"
+            BuildableName = "AFNetworking Example.app"
+            BlueprintName = "AFNetworking Example"
+            ReferencedContainer = "container:AFNetworking Mac Example.xcodeproj">
+         </BuildableReference>
+      </BuildableProductRunnable>
+      <AdditionalOptions>
+      </AdditionalOptions>
+   </LaunchAction>
+   <ProfileAction
+      shouldUseLaunchSchemeArgsEnv = "YES"
+      savedToolIdentifier = ""
+      useCustomWorkingDirectory = "NO"
+      buildConfiguration = "Release"
+      debugDocumentVersioning = "YES">
+      <BuildableProductRunnable>
+         <BuildableReference
+            BuildableIdentifier = "primary"
+            BlueprintIdentifier = "F8129BFA1591061B009BFE23"
+            BuildableName = "AFNetworking Example.app"
+            BlueprintName = "AFNetworking Example"
+            ReferencedContainer = "container:AFNetworking Mac Example.xcodeproj">
+         </BuildableReference>
+      </BuildableProductRunnable>
+   </ProfileAction>
+   <AnalyzeAction
+      buildConfiguration = "Debug">
+   </AnalyzeAction>
+   <ArchiveAction
+      buildConfiguration = "Release"
+      revealArchiveInOrganizer = "YES">
+   </ArchiveAction>
+</Scheme>

+ 150 - 50
Example/AFNetworking iOS Example.xcodeproj/project.pbxproj

@@ -7,15 +7,28 @@
 	objects = {
 
 /* Begin PBXBuildFile section */
+		297F56CA17A9B1AB0014D95C /* AFSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = 297F56C917A9B1AB0014D95C /* AFSecurityPolicy.m */; };
 		2982AD3217107C0000FFF048 /* adn.cer in Resources */ = {isa = PBXBuildFile; fileRef = 2982AD3117107C0000FFF048 /* adn.cer */; };
 		F8129C7415910C37009BFE23 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = F8129C7215910C37009BFE23 /* AppDelegate.m */; };
 		F818101615E6A0C600EF93C2 /* MobileCoreServices.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 50ABD6EC159FC2CE001BE42C /* MobileCoreServices.framework */; };
+		F86A37E0177397D900407E52 /* AFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = F86A37DF177397D900407E52 /* AFURLSessionManager.m */; };
 		F88812F016C533D6003C8B8C /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8E469E013957DF100DB05C8 /* Security.framework */; };
 		F8A847C1161F51A300940F39 /* Default-568h@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = F8A847C0161F51A300940F39 /* Default-568h@2x.png */; };
 		F8A847C3161F523E00940F39 /* Default.png in Resources */ = {isa = PBXBuildFile; fileRef = F8A847C2161F523E00940F39 /* Default.png */; };
 		F8A847C5161F524200940F39 /* Default@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = F8A847C4161F524200940F39 /* Default@2x.png */; };
+		F8B3944D17DBF9B900430F25 /* AFHTTPRequestOperationManager.m in Sources */ = {isa = PBXBuildFile; fileRef = F8B3944C17DBF9B900430F25 /* AFHTTPRequestOperationManager.m */; };
+		F8CBED2317D595320088ADC0 /* UIAlertView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F8CBED2217D595320088ADC0 /* UIAlertView+AFNetworking.m */; };
 		F8D0701B14310F4A00653FD3 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8E469E213957DF700DB05C8 /* SystemConfiguration.framework */; };
+		F8D5499A17DB0EF300BFF314 /* AFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = F8D5499917DB0EF300BFF314 /* AFURLResponseSerialization.m */; };
+		F8D5499D17DB0EFE00BFF314 /* AFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = F8D5499C17DB0EFE00BFF314 /* AFURLRequestSerialization.m */; };
+		F8D549A017DB1C9100BFF314 /* AFNetworkReachabilityManager.m in Sources */ = {isa = PBXBuildFile; fileRef = F8D5499F17DB1C9100BFF314 /* AFNetworkReachabilityManager.m */; };
 		F8DA09E41396AC040057D0CC /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = F8DA09E31396AC040057D0CC /* main.m */; };
+		F8E02CF7177A8B710087BB23 /* AFNetworkActivityIndicatorManager.m in Sources */ = {isa = PBXBuildFile; fileRef = F8E02CEC177A8B710087BB23 /* AFNetworkActivityIndicatorManager.m */; };
+		F8E02CF8177A8B710087BB23 /* UIActivityIndicatorView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F8E02CEE177A8B710087BB23 /* UIActivityIndicatorView+AFNetworking.m */; };
+		F8E02CF9177A8B710087BB23 /* UIButton+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F8E02CF0177A8B710087BB23 /* UIButton+AFNetworking.m */; };
+		F8E02CFA177A8B710087BB23 /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F8E02CF2177A8B710087BB23 /* UIImageView+AFNetworking.m */; };
+		F8E02CFB177A8B710087BB23 /* UIProgressView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F8E02CF4177A8B710087BB23 /* UIProgressView+AFNetworking.m */; };
+		F8E02CFC177A8B710087BB23 /* UIWebView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F8E02CF6177A8B710087BB23 /* UIWebView+AFNetworking.m */; };
 		F8E469651395739D00DB05C8 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8E469641395739D00DB05C8 /* UIKit.framework */; };
 		F8E469671395739D00DB05C8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8E469661395739D00DB05C8 /* Foundation.framework */; };
 		F8E469691395739D00DB05C8 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8E469681395739D00DB05C8 /* CoreGraphics.framework */; };
@@ -26,30 +39,50 @@
 		F8FA9494150EF97E00ED4EAD /* Post.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FA9493150EF97E00ED4EAD /* Post.m */; };
 		F8FA9497150EF98800ED4EAD /* User.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FA9496150EF98800ED4EAD /* User.m */; };
 		F8FA949A150EF9DA00ED4EAD /* GlobalTimelineViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FA9499150EF9DA00ED4EAD /* GlobalTimelineViewController.m */; };
-		F8FA94B1150EFEC100ED4EAD /* AFHTTPClient.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FA949D150EFEC100ED4EAD /* AFHTTPClient.m */; };
+		F8FA94B1150EFEC100ED4EAD /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FA949D150EFEC100ED4EAD /* AFHTTPSessionManager.m */; };
 		F8FA94B2150EFEC100ED4EAD /* AFHTTPRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FA949F150EFEC100ED4EAD /* AFHTTPRequestOperation.m */; };
-		F8FA94B3150EFEC100ED4EAD /* AFImageRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FA94A1150EFEC100ED4EAD /* AFImageRequestOperation.m */; };
-		F8FA94B4150EFEC100ED4EAD /* AFJSONRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FA94A3150EFEC100ED4EAD /* AFJSONRequestOperation.m */; };
-		F8FA94B6150EFEC100ED4EAD /* AFNetworkActivityIndicatorManager.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FA94A7150EFEC100ED4EAD /* AFNetworkActivityIndicatorManager.m */; };
-		F8FA94B7150EFEC100ED4EAD /* AFPropertyListRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FA94AA150EFEC100ED4EAD /* AFPropertyListRequestOperation.m */; };
 		F8FA94B8150EFEC100ED4EAD /* AFURLConnectionOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FA94AC150EFEC100ED4EAD /* AFURLConnectionOperation.m */; };
-		F8FA94B9150EFEC100ED4EAD /* AFXMLRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FA94AE150EFEC100ED4EAD /* AFXMLRequestOperation.m */; };
-		F8FA94BA150EFEC100ED4EAD /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FA94B0150EFEC100ED4EAD /* UIImageView+AFNetworking.m */; };
 		F8FA94C1150F019100ED4EAD /* PostTableViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FA94C0150F019100ED4EAD /* PostTableViewCell.m */; };
 		F8FA94D0150F094D00ED4EAD /* profile-image-placeholder.png in Resources */ = {isa = PBXBuildFile; fileRef = F8FA94CC150F094D00ED4EAD /* profile-image-placeholder.png */; };
 		F8FA94D1150F094D00ED4EAD /* profile-image-placeholder@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = F8FA94CD150F094D00ED4EAD /* profile-image-placeholder@2x.png */; };
 /* End PBXBuildFile section */
 
 /* Begin PBXFileReference section */
+		297F56C817A9B1AB0014D95C /* AFSecurityPolicy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFSecurityPolicy.h; sourceTree = "<group>"; };
+		297F56C917A9B1AB0014D95C /* AFSecurityPolicy.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFSecurityPolicy.m; sourceTree = "<group>"; };
 		2982AD3117107C0000FFF048 /* adn.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = adn.cer; sourceTree = SOURCE_ROOT; };
 		50ABD6EC159FC2CE001BE42C /* MobileCoreServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MobileCoreServices.framework; path = System/Library/Frameworks/MobileCoreServices.framework; sourceTree = SDKROOT; };
 		F8129C3815910830009BFE23 /* Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Prefix.pch; sourceTree = SOURCE_ROOT; };
 		F8129C7215910C37009BFE23 /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = SOURCE_ROOT; };
 		F8129C7315910C37009BFE23 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = SOURCE_ROOT; };
+		F86A37DE177397D900407E52 /* AFURLSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLSessionManager.h; sourceTree = "<group>"; };
+		F86A37DF177397D900407E52 /* AFURLSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLSessionManager.m; sourceTree = "<group>"; };
 		F8A847C0161F51A300940F39 /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x.png"; sourceTree = "<group>"; };
 		F8A847C2161F523E00940F39 /* Default.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Default.png; sourceTree = "<group>"; };
 		F8A847C4161F524200940F39 /* Default@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default@2x.png"; sourceTree = "<group>"; };
+		F8B3944B17DBF9B900430F25 /* AFHTTPRequestOperationManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPRequestOperationManager.h; sourceTree = "<group>"; };
+		F8B3944C17DBF9B900430F25 /* AFHTTPRequestOperationManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPRequestOperationManager.m; sourceTree = "<group>"; };
+		F8CBED2117D595320088ADC0 /* UIAlertView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIAlertView+AFNetworking.h"; sourceTree = "<group>"; };
+		F8CBED2217D595320088ADC0 /* UIAlertView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIAlertView+AFNetworking.m"; sourceTree = "<group>"; };
+		F8D5499817DB0EF300BFF314 /* AFURLResponseSerialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLResponseSerialization.h; sourceTree = "<group>"; };
+		F8D5499917DB0EF300BFF314 /* AFURLResponseSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLResponseSerialization.m; sourceTree = "<group>"; };
+		F8D5499B17DB0EFE00BFF314 /* AFURLRequestSerialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLRequestSerialization.h; sourceTree = "<group>"; };
+		F8D5499C17DB0EFE00BFF314 /* AFURLRequestSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLRequestSerialization.m; sourceTree = "<group>"; };
+		F8D5499E17DB1C9100BFF314 /* AFNetworkReachabilityManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworkReachabilityManager.h; sourceTree = "<group>"; };
+		F8D5499F17DB1C9100BFF314 /* AFNetworkReachabilityManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFNetworkReachabilityManager.m; sourceTree = "<group>"; };
 		F8DA09E31396AC040057D0CC /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = SOURCE_ROOT; };
+		F8E02CEB177A8B710087BB23 /* AFNetworkActivityIndicatorManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworkActivityIndicatorManager.h; sourceTree = "<group>"; };
+		F8E02CEC177A8B710087BB23 /* AFNetworkActivityIndicatorManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFNetworkActivityIndicatorManager.m; sourceTree = "<group>"; };
+		F8E02CED177A8B710087BB23 /* UIActivityIndicatorView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIActivityIndicatorView+AFNetworking.h"; sourceTree = "<group>"; };
+		F8E02CEE177A8B710087BB23 /* UIActivityIndicatorView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIActivityIndicatorView+AFNetworking.m"; sourceTree = "<group>"; };
+		F8E02CEF177A8B710087BB23 /* UIButton+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIButton+AFNetworking.h"; sourceTree = "<group>"; };
+		F8E02CF0177A8B710087BB23 /* UIButton+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIButton+AFNetworking.m"; sourceTree = "<group>"; };
+		F8E02CF1177A8B710087BB23 /* UIImageView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImageView+AFNetworking.h"; sourceTree = "<group>"; };
+		F8E02CF2177A8B710087BB23 /* UIImageView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImageView+AFNetworking.m"; sourceTree = "<group>"; };
+		F8E02CF3177A8B710087BB23 /* UIProgressView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIProgressView+AFNetworking.h"; sourceTree = "<group>"; };
+		F8E02CF4177A8B710087BB23 /* UIProgressView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIProgressView+AFNetworking.m"; sourceTree = "<group>"; };
+		F8E02CF5177A8B710087BB23 /* UIWebView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIWebView+AFNetworking.h"; sourceTree = "<group>"; };
+		F8E02CF6177A8B710087BB23 /* UIWebView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIWebView+AFNetworking.m"; sourceTree = "<group>"; };
 		F8E469601395739C00DB05C8 /* AFNetworking iOS Example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "AFNetworking iOS Example.app"; sourceTree = BUILT_PRODUCTS_DIR; };
 		F8E469641395739D00DB05C8 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
 		F8E469661395739D00DB05C8 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
@@ -68,25 +101,13 @@
 		F8FA9496150EF98800ED4EAD /* User.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = User.m; sourceTree = "<group>"; };
 		F8FA9498150EF9DA00ED4EAD /* GlobalTimelineViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GlobalTimelineViewController.h; sourceTree = "<group>"; };
 		F8FA9499150EF9DA00ED4EAD /* GlobalTimelineViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GlobalTimelineViewController.m; sourceTree = "<group>"; };
-		F8FA949C150EFEC100ED4EAD /* AFHTTPClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPClient.h; sourceTree = "<group>"; };
-		F8FA949D150EFEC100ED4EAD /* AFHTTPClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPClient.m; sourceTree = "<group>"; };
+		F8FA949C150EFEC100ED4EAD /* AFHTTPSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPSessionManager.h; sourceTree = "<group>"; };
+		F8FA949D150EFEC100ED4EAD /* AFHTTPSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPSessionManager.m; sourceTree = "<group>"; };
 		F8FA949E150EFEC100ED4EAD /* AFHTTPRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPRequestOperation.h; sourceTree = "<group>"; };
 		F8FA949F150EFEC100ED4EAD /* AFHTTPRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPRequestOperation.m; sourceTree = "<group>"; };
-		F8FA94A0150EFEC100ED4EAD /* AFImageRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFImageRequestOperation.h; sourceTree = "<group>"; };
-		F8FA94A1150EFEC100ED4EAD /* AFImageRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFImageRequestOperation.m; sourceTree = "<group>"; };
-		F8FA94A2150EFEC100ED4EAD /* AFJSONRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFJSONRequestOperation.h; sourceTree = "<group>"; };
-		F8FA94A3150EFEC100ED4EAD /* AFJSONRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFJSONRequestOperation.m; sourceTree = "<group>"; };
-		F8FA94A6150EFEC100ED4EAD /* AFNetworkActivityIndicatorManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworkActivityIndicatorManager.h; sourceTree = "<group>"; };
-		F8FA94A7150EFEC100ED4EAD /* AFNetworkActivityIndicatorManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFNetworkActivityIndicatorManager.m; sourceTree = "<group>"; };
 		F8FA94A8150EFEC100ED4EAD /* AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworking.h; sourceTree = "<group>"; };
-		F8FA94A9150EFEC100ED4EAD /* AFPropertyListRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFPropertyListRequestOperation.h; sourceTree = "<group>"; };
-		F8FA94AA150EFEC100ED4EAD /* AFPropertyListRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFPropertyListRequestOperation.m; sourceTree = "<group>"; };
 		F8FA94AB150EFEC100ED4EAD /* AFURLConnectionOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLConnectionOperation.h; sourceTree = "<group>"; };
 		F8FA94AC150EFEC100ED4EAD /* AFURLConnectionOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLConnectionOperation.m; sourceTree = "<group>"; };
-		F8FA94AD150EFEC100ED4EAD /* AFXMLRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFXMLRequestOperation.h; sourceTree = "<group>"; };
-		F8FA94AE150EFEC100ED4EAD /* AFXMLRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFXMLRequestOperation.m; sourceTree = "<group>"; };
-		F8FA94AF150EFEC100ED4EAD /* UIImageView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImageView+AFNetworking.h"; sourceTree = "<group>"; };
-		F8FA94B0150EFEC100ED4EAD /* UIImageView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImageView+AFNetworking.m"; sourceTree = "<group>"; };
 		F8FA94BF150F019100ED4EAD /* PostTableViewCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PostTableViewCell.h; sourceTree = "<group>"; };
 		F8FA94C0150F019100ED4EAD /* PostTableViewCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PostTableViewCell.m; sourceTree = "<group>"; };
 		F8FA94CC150F094D00ED4EAD /* profile-image-placeholder.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "profile-image-placeholder.png"; path = "Images/profile-image-placeholder.png"; sourceTree = SOURCE_ROOT; };
@@ -111,6 +132,59 @@
 /* End PBXFrameworksBuildPhase section */
 
 /* Begin PBXGroup section */
+		F8D549A117DBE52C00BFF314 /* Serialization */ = {
+			isa = PBXGroup;
+			children = (
+				F8D5499B17DB0EFE00BFF314 /* AFURLRequestSerialization.h */,
+				F8D5499C17DB0EFE00BFF314 /* AFURLRequestSerialization.m */,
+				F8D5499817DB0EF300BFF314 /* AFURLResponseSerialization.h */,
+				F8D5499917DB0EF300BFF314 /* AFURLResponseSerialization.m */,
+			);
+			name = Serialization;
+			sourceTree = "<group>";
+		};
+		F8D549A217DBE53B00BFF314 /* NSURLSession */ = {
+			isa = PBXGroup;
+			children = (
+				F86A37DE177397D900407E52 /* AFURLSessionManager.h */,
+				F86A37DF177397D900407E52 /* AFURLSessionManager.m */,
+				F8FA949C150EFEC100ED4EAD /* AFHTTPSessionManager.h */,
+				F8FA949D150EFEC100ED4EAD /* AFHTTPSessionManager.m */,
+			);
+			name = NSURLSession;
+			sourceTree = "<group>";
+		};
+		F8D549A317DBE54700BFF314 /* NSURLConnection */ = {
+			isa = PBXGroup;
+			children = (
+				F8FA94AB150EFEC100ED4EAD /* AFURLConnectionOperation.h */,
+				F8FA94AC150EFEC100ED4EAD /* AFURLConnectionOperation.m */,
+				F8FA949E150EFEC100ED4EAD /* AFHTTPRequestOperation.h */,
+				F8FA949F150EFEC100ED4EAD /* AFHTTPRequestOperation.m */,
+				F8B3944B17DBF9B900430F25 /* AFHTTPRequestOperationManager.h */,
+				F8B3944C17DBF9B900430F25 /* AFHTTPRequestOperationManager.m */,
+			);
+			name = NSURLConnection;
+			sourceTree = "<group>";
+		};
+		F8D549A417DBE54F00BFF314 /* Reachability */ = {
+			isa = PBXGroup;
+			children = (
+				F8D5499E17DB1C9100BFF314 /* AFNetworkReachabilityManager.h */,
+				F8D5499F17DB1C9100BFF314 /* AFNetworkReachabilityManager.m */,
+			);
+			name = Reachability;
+			sourceTree = "<group>";
+		};
+		F8D549A517DBE55400BFF314 /* Security */ = {
+			isa = PBXGroup;
+			children = (
+				297F56C817A9B1AB0014D95C /* AFSecurityPolicy.h */,
+				297F56C917A9B1AB0014D95C /* AFSecurityPolicy.m */,
+			);
+			name = Security;
+			sourceTree = "<group>";
+		};
 		F8DA09C61396AB690057D0CC /* Controllers */ = {
 			isa = PBXGroup;
 			children = (
@@ -143,6 +217,28 @@
 			path = Classes/Views;
 			sourceTree = SOURCE_ROOT;
 		};
+		F8E02CEA177A8B710087BB23 /* UIKit+AFNetworking */ = {
+			isa = PBXGroup;
+			children = (
+				F8E02CEB177A8B710087BB23 /* AFNetworkActivityIndicatorManager.h */,
+				F8E02CEC177A8B710087BB23 /* AFNetworkActivityIndicatorManager.m */,
+				F8E02CED177A8B710087BB23 /* UIActivityIndicatorView+AFNetworking.h */,
+				F8E02CEE177A8B710087BB23 /* UIActivityIndicatorView+AFNetworking.m */,
+				F8CBED2117D595320088ADC0 /* UIAlertView+AFNetworking.h */,
+				F8CBED2217D595320088ADC0 /* UIAlertView+AFNetworking.m */,
+				F8E02CEF177A8B710087BB23 /* UIButton+AFNetworking.h */,
+				F8E02CF0177A8B710087BB23 /* UIButton+AFNetworking.m */,
+				F8E02CF1177A8B710087BB23 /* UIImageView+AFNetworking.h */,
+				F8E02CF2177A8B710087BB23 /* UIImageView+AFNetworking.m */,
+				F8E02CF3177A8B710087BB23 /* UIProgressView+AFNetworking.h */,
+				F8E02CF4177A8B710087BB23 /* UIProgressView+AFNetworking.m */,
+				F8E02CF5177A8B710087BB23 /* UIWebView+AFNetworking.h */,
+				F8E02CF6177A8B710087BB23 /* UIWebView+AFNetworking.m */,
+			);
+			name = "UIKit+AFNetworking";
+			path = "../UIKit+AFNetworking";
+			sourceTree = "<group>";
+		};
 		F8E469551395739C00DB05C8 = {
 			isa = PBXGroup;
 			children = (
@@ -212,6 +308,7 @@
 			isa = PBXGroup;
 			children = (
 				F8FA949B150EFEC100ED4EAD /* AFNetworking */,
+				F8E02CEA177A8B710087BB23 /* UIKit+AFNetworking */,
 			);
 			name = Vendor;
 			sourceTree = "<group>";
@@ -241,24 +338,11 @@
 			isa = PBXGroup;
 			children = (
 				F8FA94A8150EFEC100ED4EAD /* AFNetworking.h */,
-				F8FA94AB150EFEC100ED4EAD /* AFURLConnectionOperation.h */,
-				F8FA94AC150EFEC100ED4EAD /* AFURLConnectionOperation.m */,
-				F8FA949E150EFEC100ED4EAD /* AFHTTPRequestOperation.h */,
-				F8FA949F150EFEC100ED4EAD /* AFHTTPRequestOperation.m */,
-				F8FA94A2150EFEC100ED4EAD /* AFJSONRequestOperation.h */,
-				F8FA94A3150EFEC100ED4EAD /* AFJSONRequestOperation.m */,
-				F8FA94AD150EFEC100ED4EAD /* AFXMLRequestOperation.h */,
-				F8FA94AE150EFEC100ED4EAD /* AFXMLRequestOperation.m */,
-				F8FA94A9150EFEC100ED4EAD /* AFPropertyListRequestOperation.h */,
-				F8FA94AA150EFEC100ED4EAD /* AFPropertyListRequestOperation.m */,
-				F8FA949C150EFEC100ED4EAD /* AFHTTPClient.h */,
-				F8FA949D150EFEC100ED4EAD /* AFHTTPClient.m */,
-				F8FA94A0150EFEC100ED4EAD /* AFImageRequestOperation.h */,
-				F8FA94A1150EFEC100ED4EAD /* AFImageRequestOperation.m */,
-				F8FA94AF150EFEC100ED4EAD /* UIImageView+AFNetworking.h */,
-				F8FA94B0150EFEC100ED4EAD /* UIImageView+AFNetworking.m */,
-				F8FA94A6150EFEC100ED4EAD /* AFNetworkActivityIndicatorManager.h */,
-				F8FA94A7150EFEC100ED4EAD /* AFNetworkActivityIndicatorManager.m */,
+				F8D549A317DBE54700BFF314 /* NSURLConnection */,
+				F8D549A217DBE53B00BFF314 /* NSURLSession */,
+				F8D549A117DBE52C00BFF314 /* Serialization */,
+				F8D549A417DBE54F00BFF314 /* Reachability */,
+				F8D549A517DBE55400BFF314 /* Security */,
 			);
 			name = AFNetworking;
 			path = ../AFNetworking;
@@ -292,6 +376,15 @@
 			attributes = {
 				LastUpgradeCheck = 0500;
 				ORGANIZATIONNAME = Gowalla;
+				TargetAttributes = {
+					F8E4695F1395739C00DB05C8 = {
+						SystemCapabilities = {
+							com.apple.BackgroundModes = {
+								enabled = 1;
+							};
+						};
+					};
+				};
 			};
 			buildConfigurationList = F8E4695A1395739C00DB05C8 /* Build configuration list for PBXProject "AFNetworking iOS Example" */;
 			compatibilityVersion = "Xcode 3.2";
@@ -333,20 +426,27 @@
 			isa = PBXSourcesBuildPhase;
 			buildActionMask = 2147483647;
 			files = (
+				F86A37E0177397D900407E52 /* AFURLSessionManager.m in Sources */,
 				F8DA09E41396AC040057D0CC /* main.m in Sources */,
+				F8B3944D17DBF9B900430F25 /* AFHTTPRequestOperationManager.m in Sources */,
+				F8CBED2317D595320088ADC0 /* UIAlertView+AFNetworking.m in Sources */,
 				F8FA9491150EF8C100ED4EAD /* AFAppDotNetAPIClient.m in Sources */,
 				F8FA9494150EF97E00ED4EAD /* Post.m in Sources */,
 				F8FA9497150EF98800ED4EAD /* User.m in Sources */,
+				F8E02CF8177A8B710087BB23 /* UIActivityIndicatorView+AFNetworking.m in Sources */,
+				F8E02CFB177A8B710087BB23 /* UIProgressView+AFNetworking.m in Sources */,
+				F8D549A017DB1C9100BFF314 /* AFNetworkReachabilityManager.m in Sources */,
+				F8E02CF7177A8B710087BB23 /* AFNetworkActivityIndicatorManager.m in Sources */,
+				297F56CA17A9B1AB0014D95C /* AFSecurityPolicy.m in Sources */,
+				F8E02CF9177A8B710087BB23 /* UIButton+AFNetworking.m in Sources */,
+				F8E02CFA177A8B710087BB23 /* UIImageView+AFNetworking.m in Sources */,
 				F8FA949A150EF9DA00ED4EAD /* GlobalTimelineViewController.m in Sources */,
-				F8FA94B1150EFEC100ED4EAD /* AFHTTPClient.m in Sources */,
+				F8FA94B1150EFEC100ED4EAD /* AFHTTPSessionManager.m in Sources */,
+				F8D5499D17DB0EFE00BFF314 /* AFURLRequestSerialization.m in Sources */,
+				F8D5499A17DB0EF300BFF314 /* AFURLResponseSerialization.m in Sources */,
+				F8E02CFC177A8B710087BB23 /* UIWebView+AFNetworking.m in Sources */,
 				F8FA94B2150EFEC100ED4EAD /* AFHTTPRequestOperation.m in Sources */,
-				F8FA94B3150EFEC100ED4EAD /* AFImageRequestOperation.m in Sources */,
-				F8FA94B4150EFEC100ED4EAD /* AFJSONRequestOperation.m in Sources */,
-				F8FA94B6150EFEC100ED4EAD /* AFNetworkActivityIndicatorManager.m in Sources */,
-				F8FA94B7150EFEC100ED4EAD /* AFPropertyListRequestOperation.m in Sources */,
 				F8FA94B8150EFEC100ED4EAD /* AFURLConnectionOperation.m in Sources */,
-				F8FA94B9150EFEC100ED4EAD /* AFXMLRequestOperation.m in Sources */,
-				F8FA94BA150EFEC100ED4EAD /* UIImageView+AFNetworking.m in Sources */,
 				F8FA94C1150F019100ED4EAD /* PostTableViewCell.m in Sources */,
 				F8129C7415910C37009BFE23 /* AppDelegate.m in Sources */,
 			);
@@ -366,7 +466,7 @@
 				GCC_VERSION = com.apple.compilers.llvmgcc42;
 				GCC_WARN_ABOUT_RETURN_TYPE = YES;
 				GCC_WARN_UNUSED_VARIABLE = YES;
-				IPHONEOS_DEPLOYMENT_TARGET = 4.3;
+				IPHONEOS_DEPLOYMENT_TARGET = 7.0;
 				ONLY_ACTIVE_ARCH = YES;
 				SDKROOT = iphoneos;
 			};
@@ -380,7 +480,7 @@
 				GCC_VERSION = com.apple.compilers.llvmgcc42;
 				GCC_WARN_ABOUT_RETURN_TYPE = YES;
 				GCC_WARN_UNUSED_VARIABLE = YES;
-				IPHONEOS_DEPLOYMENT_TARGET = 4.3;
+				IPHONEOS_DEPLOYMENT_TARGET = 7.0;
 				OTHER_CFLAGS = "-DNS_BLOCK_ASSERTIONS=1";
 				SDKROOT = iphoneos;
 			};
@@ -400,7 +500,7 @@
 				GCC_WARN_SIGN_COMPARE = YES;
 				GCC_WARN_UNUSED_PARAMETER = NO;
 				INFOPLIST_FILE = "iOS-Info.plist";
-				IPHONEOS_DEPLOYMENT_TARGET = 5.0;
+				IPHONEOS_DEPLOYMENT_TARGET = 7.0;
 				PRODUCT_NAME = "$(TARGET_NAME)";
 				WARNING_CFLAGS = "";
 				WRAPPER_EXTENSION = app;
@@ -420,7 +520,7 @@
 				GCC_WARN_SIGN_COMPARE = YES;
 				GCC_WARN_UNUSED_PARAMETER = NO;
 				INFOPLIST_FILE = "iOS-Info.plist";
-				IPHONEOS_DEPLOYMENT_TARGET = 5.0;
+				IPHONEOS_DEPLOYMENT_TARGET = 7.0;
 				PRODUCT_NAME = "$(TARGET_NAME)";
 				VALIDATE_PRODUCT = YES;
 				WARNING_CFLAGS = "";

+ 96 - 0
Example/AFNetworking iOS Example.xcodeproj/xcshareddata/xcschemes/AFNetworking iOS Example.xcscheme

@@ -0,0 +1,96 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Scheme
+   LastUpgradeVersion = "0500"
+   version = "1.3">
+   <BuildAction
+      parallelizeBuildables = "YES"
+      buildImplicitDependencies = "YES">
+      <BuildActionEntries>
+         <BuildActionEntry
+            buildForTesting = "YES"
+            buildForRunning = "YES"
+            buildForProfiling = "YES"
+            buildForArchiving = "YES"
+            buildForAnalyzing = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "F8E4695F1395739C00DB05C8"
+               BuildableName = "AFNetworking iOS Example.app"
+               BlueprintName = "AFNetworking iOS Example"
+               ReferencedContainer = "container:AFNetworking iOS Example.xcodeproj">
+            </BuildableReference>
+         </BuildActionEntry>
+      </BuildActionEntries>
+   </BuildAction>
+   <TestAction
+      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+      shouldUseLaunchSchemeArgsEnv = "YES"
+      buildConfiguration = "Debug">
+      <Testables>
+         <TestableReference
+            skipped = "NO">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "2902D27717DF4E1100C81C5A"
+               BuildableName = "iOS Tests.xctest"
+               BlueprintName = "iOS Tests"
+               ReferencedContainer = "container:../Tests/AFNetworking Tests.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+      </Testables>
+      <MacroExpansion>
+         <BuildableReference
+            BuildableIdentifier = "primary"
+            BlueprintIdentifier = "F8E4695F1395739C00DB05C8"
+            BuildableName = "AFNetworking iOS Example.app"
+            BlueprintName = "AFNetworking iOS Example"
+            ReferencedContainer = "container:AFNetworking iOS Example.xcodeproj">
+         </BuildableReference>
+      </MacroExpansion>
+   </TestAction>
+   <LaunchAction
+      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+      launchStyle = "0"
+      useCustomWorkingDirectory = "NO"
+      buildConfiguration = "Debug"
+      ignoresPersistentStateOnLaunch = "NO"
+      debugDocumentVersioning = "YES"
+      allowLocationSimulation = "YES">
+      <BuildableProductRunnable>
+         <BuildableReference
+            BuildableIdentifier = "primary"
+            BlueprintIdentifier = "F8E4695F1395739C00DB05C8"
+            BuildableName = "AFNetworking iOS Example.app"
+            BlueprintName = "AFNetworking iOS Example"
+            ReferencedContainer = "container:AFNetworking iOS Example.xcodeproj">
+         </BuildableReference>
+      </BuildableProductRunnable>
+      <AdditionalOptions>
+      </AdditionalOptions>
+   </LaunchAction>
+   <ProfileAction
+      shouldUseLaunchSchemeArgsEnv = "YES"
+      savedToolIdentifier = ""
+      useCustomWorkingDirectory = "NO"
+      buildConfiguration = "Release"
+      debugDocumentVersioning = "YES">
+      <BuildableProductRunnable>
+         <BuildableReference
+            BuildableIdentifier = "primary"
+            BlueprintIdentifier = "F8E4695F1395739C00DB05C8"
+            BuildableName = "AFNetworking iOS Example.app"
+            BlueprintName = "AFNetworking iOS Example"
+            ReferencedContainer = "container:AFNetworking iOS Example.xcodeproj">
+         </BuildableReference>
+      </BuildableProductRunnable>
+   </ProfileAction>
+   <AnalyzeAction
+      buildConfiguration = "Debug">
+   </AnalyzeAction>
+   <ArchiveAction
+      buildConfiguration = "Release"
+      revealArchiveInOrganizer = "YES">
+   </ArchiveAction>
+</Scheme>

+ 0 - 6
Example/AppDelegate.m

@@ -28,8 +28,6 @@
     #import "AFNetworkActivityIndicatorManager.h"
 
     @implementation AppDelegate
-    @synthesize window = _window;
-    @synthesize navigationController = _navigationController;
 
     - (BOOL)application:(UIApplication *)application 
     didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
@@ -58,10 +56,6 @@
 
     @implementation AppDelegate
 
-    @synthesize window = _window;
-    @synthesize tableView = _tableView;
-    @synthesize postsArrayController = _postsArrayController;
-
     - (void)applicationDidFinishLaunching:(NSNotification *)notification {
         NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil];
         [NSURLCache setSharedURLCache:URLCache];

+ 3 - 3
Example/Classes/AFAppDotNetAPIClient.h

@@ -21,10 +21,10 @@
 // THE SOFTWARE.
 
 #import <Foundation/Foundation.h>
-#import "AFHTTPClient.h"
+#import "AFHTTPSessionManager.h"
 
-@interface AFAppDotNetAPIClient : AFHTTPClient
+@interface AFAppDotNetAPIClient : AFHTTPSessionManager
 
-+ (AFAppDotNetAPIClient *)sharedClient;
++ (instancetype)sharedClient;
 
 @end

+ 3 - 26
Example/Classes/AFAppDotNetAPIClient.m

@@ -22,41 +22,18 @@
 
 #import "AFAppDotNetAPIClient.h"
 
-#import "AFJSONRequestOperation.h"
-
-static NSString * const kAFAppDotNetAPIBaseURLString = @"https://alpha-api.app.net/";
+static NSString * const AFAppDotNetAPIBaseURLString = @"https://alpha-api.app.net/";
 
 @implementation AFAppDotNetAPIClient
 
-+ (AFAppDotNetAPIClient *)sharedClient {
++ (instancetype)sharedClient {
     static AFAppDotNetAPIClient *_sharedClient = nil;
     static dispatch_once_t onceToken;
     dispatch_once(&onceToken, ^{
-        _sharedClient = [[AFAppDotNetAPIClient alloc] initWithBaseURL:[NSURL URLWithString:kAFAppDotNetAPIBaseURLString]];
+        _sharedClient = [[AFAppDotNetAPIClient alloc] initWithBaseURL:[NSURL URLWithString:AFAppDotNetAPIBaseURLString]];
     });
     
     return _sharedClient;
 }
 
-- (id)initWithBaseURL:(NSURL *)url {
-    self = [super initWithBaseURL:url];
-    if (!self) {
-        return nil;
-    }
-    
-    [self registerHTTPOperationClass:[AFJSONRequestOperation class]];
-    
-    // Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
-	[self setDefaultHeader:@"Accept" value:@"application/json"];
-
-    // By default, the example ships with SSL pinning enabled for the app.net API pinned against the public key of adn.cer file included with the example. In order to make it easier for developers who are new to AFNetworking, SSL pinning is automatically disabled if the base URL has been changed. This will allow developers to hack around with the example, without getting tripped up by SSL pinning.
-    if ([[url scheme] isEqualToString:@"https"] && [[url host] isEqualToString:@"alpha-api.app.net"]) {
-        self.defaultSSLPinningMode = AFSSLPinningModePublicKey;
-    } else {
-        self.defaultSSLPinningMode = AFSSLPinningModeNone;
-    }
-    
-    return self;
-}
-
 @end

+ 13 - 23
Example/Classes/Controllers/GlobalTimelineViewController.m

@@ -26,6 +26,9 @@
 
 #import "PostTableViewCell.h"
 
+#import "UIActivityIndicatorView+AFNetworking.h"
+#import "UIAlertView+AFNetworking.h"
+
 @interface GlobalTimelineViewController ()
 - (void)reload:(id)sender;
 @end
@@ -33,42 +36,35 @@
 @implementation GlobalTimelineViewController {
 @private
     NSArray *_posts;
-    
-    __strong UIActivityIndicatorView *_activityIndicatorView;
 }
 
 - (void)reload:(id)sender {
-    [_activityIndicatorView startAnimating];
     self.navigationItem.rightBarButtonItem.enabled = NO;
-    
-    [Post globalTimelinePostsWithBlock:^(NSArray *posts, NSError *error) {
-        if (error) {
-            [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", nil) message:[error localizedDescription] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"OK", nil), nil] show];
-        } else {
+
+    NSURLSessionTask *task = [Post globalTimelinePostsWithBlock:^(NSArray *posts, NSError *error) {
+        if (!error) {
             _posts = posts;
             [self.tableView reloadData];
         }
         
-        [_activityIndicatorView stopAnimating];
         self.navigationItem.rightBarButtonItem.enabled = YES;
     }];
-}
 
-#pragma mark - UIViewController
+    [UIAlertView showAlertViewForTaskWithErrorOnCompletion:task delegate:nil];
 
-- (void)loadView {
-    [super loadView];
-    
-    _activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
-    _activityIndicatorView.hidesWhenStopped = YES;
+    UIActivityIndicatorView *activityIndicatorView = (UIActivityIndicatorView *)self.navigationItem.leftBarButtonItem.customView;
+    [activityIndicatorView setAnimatingWithStateOfTask:task];
 }
 
+#pragma mark - UIViewController
+
 - (void)viewDidLoad {
     [super viewDidLoad];
     
     self.title = NSLocalizedString(@"AFNetworking", nil);
     
-    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_activityIndicatorView];
+    UIActivityIndicatorView *activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
+    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:activityIndicatorView];
     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reload:)];
     
     self.tableView.rowHeight = 70.0f;
@@ -76,12 +72,6 @@
     [self reload:nil];
 }
 
-- (void)viewDidUnload {
-    _activityIndicatorView = nil;
-    
-    [super viewDidUnload];
-}
-
 #pragma mark - UITableViewDataSource
 
 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

+ 5 - 5
Example/Classes/Models/Post.h

@@ -26,13 +26,13 @@
 
 @interface Post : NSObject
 
-@property (readonly) NSUInteger postID;
-@property (readonly) NSString *text;
+@property (assign) NSUInteger postID;
+@property (strong) NSString *text;
 
-@property (readonly) User *user;
+@property (strong) User *user;
 
-- (id)initWithAttributes:(NSDictionary *)attributes;
+- (instancetype)initWithAttributes:(NSDictionary *)attributes;
 
-+ (void)globalTimelinePostsWithBlock:(void (^)(NSArray *posts, NSError *error))block;
++ (NSURLSessionDataTask *)globalTimelinePostsWithBlock:(void (^)(NSArray *posts, NSError *error))block;
 
 @end

+ 8 - 11
Example/Classes/Models/Post.m

@@ -26,39 +26,36 @@
 #import "AFAppDotNetAPIClient.h"
 
 @implementation Post
-@synthesize postID = _postID;
-@synthesize text = _text;
-@synthesize user = _user;
 
-- (id)initWithAttributes:(NSDictionary *)attributes {
+- (instancetype)initWithAttributes:(NSDictionary *)attributes {
     self = [super init];
     if (!self) {
         return nil;
     }
     
-    _postID = [[attributes valueForKeyPath:@"id"] integerValue];
-    _text = [attributes valueForKeyPath:@"text"];
+    self.postID = [[attributes valueForKeyPath:@"id"] integerValue];
+    self.text = [attributes valueForKeyPath:@"text"];
     
-    _user = [[User alloc] initWithAttributes:[attributes valueForKeyPath:@"user"]];
+    self.user = [[User alloc] initWithAttributes:[attributes valueForKeyPath:@"user"]];
     
     return self;
 }
 
 #pragma mark -
 
-+ (void)globalTimelinePostsWithBlock:(void (^)(NSArray *posts, NSError *error))block {
-    [[AFAppDotNetAPIClient sharedClient] getPath:@"stream/0/posts/stream/global" parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
++ (NSURLSessionDataTask *)globalTimelinePostsWithBlock:(void (^)(NSArray *posts, NSError *error))block {
+    return [[AFAppDotNetAPIClient sharedClient] GET:@"stream/0/posts/stream/global" parameters:nil success:^(NSURLSessionDataTask *task, id JSON) {
         NSArray *postsFromResponse = [JSON valueForKeyPath:@"data"];
         NSMutableArray *mutablePosts = [NSMutableArray arrayWithCapacity:[postsFromResponse count]];
         for (NSDictionary *attributes in postsFromResponse) {
             Post *post = [[Post alloc] initWithAttributes:attributes];
             [mutablePosts addObject:post];
         }
-        
+
         if (block) {
             block([NSArray arrayWithArray:mutablePosts], nil);
         }
-    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
+    } failure:^(NSURLSessionDataTask *task, NSError *error) {
         if (block) {
             block([NSArray array], error);
         }

+ 1 - 1
Example/Classes/Models/User.h

@@ -30,7 +30,7 @@ extern NSString * const kUserProfileImageDidLoadNotification;
 @property (readonly, nonatomic) NSString *username;
 @property (readonly, nonatomic, unsafe_unretained) NSURL *avatarImageURL;
 
-- (id)initWithAttributes:(NSDictionary *)attributes;
+- (instancetype)initWithAttributes:(NSDictionary *)attributes;
 
 #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
 @property (nonatomic, strong) NSImage *profileImage;

+ 39 - 42
Example/Classes/Models/User.m

@@ -21,7 +21,7 @@
 // THE SOFTWARE.
 
 #import "User.h"
-#import "AFImageRequestOperation.h"
+#import "AFHTTPRequestOperation.h"
 
 NSString * const kUserProfileImageDidLoadNotification = @"com.alamofire.user.profile-image.loaded";
 
@@ -34,13 +34,10 @@ NSString * const kUserProfileImageDidLoadNotification = @"com.alamofire.user.pro
 @implementation User {
 @private
     NSString *_avatarImageURLString;
-    AFImageRequestOperation *_avatarImageRequestOperation;
+    AFHTTPRequestOperation *_avatarImageRequestOperation;
 }
 
-@synthesize userID = _userID;
-@synthesize username = _username;
-
-- (id)initWithAttributes:(NSDictionary *)attributes {
+- (instancetype)initWithAttributes:(NSDictionary *)attributes {
     self = [super init];
     if (!self) {
         return nil;
@@ -57,41 +54,41 @@ NSString * const kUserProfileImageDidLoadNotification = @"com.alamofire.user.pro
     return [NSURL URLWithString:_avatarImageURLString];
 }
 
-#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
-
-@synthesize profileImage = _profileImage;
-
-+ (NSOperationQueue *)sharedProfileImageRequestOperationQueue {
-    static NSOperationQueue *_sharedProfileImageRequestOperationQueue = nil;
-    static dispatch_once_t onceToken;
-    dispatch_once(&onceToken, ^{
-        _sharedProfileImageRequestOperationQueue = [[NSOperationQueue alloc] init];
-        [_sharedProfileImageRequestOperationQueue setMaxConcurrentOperationCount:8];
-    });
-    
-    return _sharedProfileImageRequestOperationQueue;
-}
-
-- (NSImage *)profileImage {
-	if (!_profileImage && !_avatarImageRequestOperation) {
-		_avatarImageRequestOperation = [AFImageRequestOperation imageRequestOperationWithRequest:[NSURLRequest requestWithURL:self.avatarImageURL] success:^(NSImage *image) {
-			self.profileImage = image;
-            
-			_avatarImageRequestOperation = nil;
-            
-            [[NSNotificationCenter defaultCenter] postNotificationName:kUserProfileImageDidLoadNotification object:self userInfo:nil];
-		}];
-        
-		[_avatarImageRequestOperation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
-			return [[NSCachedURLResponse alloc] initWithResponse:cachedResponse.response data:cachedResponse.data userInfo:cachedResponse.userInfo storagePolicy:NSURLCacheStorageAllowed];
-		}];
-		
-        [[[self class] sharedProfileImageRequestOperationQueue] addOperation:_avatarImageRequestOperation];
-	}
-	
-	return _profileImage;
-}
-
-#endif
+//#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
+//
+//@synthesize profileImage = _profileImage;
+//
+//+ (NSOperationQueue *)sharedProfileImageRequestOperationQueue {
+//    static NSOperationQueue *_sharedProfileImageRequestOperationQueue = nil;
+//    static dispatch_once_t onceToken;
+//    dispatch_once(&onceToken, ^{
+//        _sharedProfileImageRequestOperationQueue = [[NSOperationQueue alloc] init];
+//        [_sharedProfileImageRequestOperationQueue setMaxConcurrentOperationCount:8];
+//    });
+//    
+//    return _sharedProfileImageRequestOperationQueue;
+//}
+//
+//- (NSImage *)profileImage {
+//	if (!_profileImage && !_avatarImageRequestOperation) {
+//		_avatarImageRequestOperation = [AFImageRequestOperation imageRequestOperationWithRequest:[NSURLRequest requestWithURL:self.avatarImageURL] success:^(NSImage *image) {
+//			self.profileImage = image;
+//            
+//			_avatarImageRequestOperation = nil;
+//            
+//            [[NSNotificationCenter defaultCenter] postNotificationName:kUserProfileImageDidLoadNotification object:self userInfo:nil];
+//		}];
+//        
+//		[_avatarImageRequestOperation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
+//			return [[NSCachedURLResponse alloc] initWithResponse:cachedResponse.response data:cachedResponse.data userInfo:cachedResponse.userInfo storagePolicy:NSURLCacheStorageAllowed];
+//		}];
+//		
+//        [[[self class] sharedProfileImageRequestOperationQueue] addOperation:_avatarImageRequestOperation];
+//	}
+//	
+//	return _profileImage;
+//}
+//
+//#endif
 
 @end

+ 7 - 7
Example/Classes/Views/PostTableViewCell.m

@@ -27,14 +27,11 @@
 
 #import "UIImageView+AFNetworking.h"
 
-@implementation PostTableViewCell {
-@private
-    __strong Post *_post;
-}
-
-@synthesize post = _post;
+@implementation PostTableViewCell
 
-- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
+- (id)initWithStyle:(UITableViewCellStyle)style
+              reuseIdentifier:(NSString *)reuseIdentifier
+{
     self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
     if (!self) {
         return nil;
@@ -60,7 +57,10 @@
 }
 
 + (CGFloat)heightForCellWithPost:(Post *)post {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
     CGSize sizeToFit = [post.text sizeWithFont:[UIFont systemFontOfSize:12.0f] constrainedToSize:CGSizeMake(220.0f, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
+#pragma clang diagnostic pop
     
     return fmaxf(70.0f, sizeToFit.height + 45.0f);
 }

BIN
Example/adn.cer


+ 4 - 0
Example/iOS-Info.plist

@@ -44,6 +44,10 @@
 	<string>1.0.0</string>
 	<key>LSRequiresIPhoneOS</key>
 	<true/>
+	<key>UIBackgroundModes</key>
+	<array>
+		<string>fetch</string>
+	</array>
 	<key>UIPrerenderedIcon</key>
 	<true/>
 	<key>UIStatusBarHidden</key>

+ 1 - 1
LICENSE

@@ -1,4 +1,4 @@
-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

+ 24 - 131
README.md

@@ -2,18 +2,7 @@
   <img src="https://raw.github.com/AFNetworking/AFNetworking/assets/afnetworking-logo.png" alt="AFNetworking" title="AFNetworking">
 </p>
 
-[![Build Status](https://travis-ci.org/AFNetworking/AFNetworking.png?branch=master)](https://travis-ci.org/AFNetworking/AFNetworking)
-
-AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of [NSURLConnection](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html), [NSOperation](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html), and other familiar Foundation technologies. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use. For example, here's how easy it is to get JSON from a URL:
-
-```objective-c
-NSURL *url = [NSURL URLWithString:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
-NSURLRequest *request = [NSURLRequest requestWithURL:url];
-AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
-    NSLog(@"App.net Global Stream: %@", JSON);
-} failure:nil];
-[operation start];
-```
+AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of [Foundation URL Loading System](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html), extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use.
 
 Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac.
 
@@ -21,142 +10,46 @@ Choose AFNetworking for your next project, or migrate over your existing project
 
 ## How To Get Started
 
-- [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/zipball/master) and try out the included Mac and iPhone example apps
+- [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/zipball/2.0) and try out the included Mac and iPhone example apps
 - Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles in the wiki](https://github.com/AFNetworking/AFNetworking/wiki)
-- Check out the [complete documentation](http://cocoadocs.org/docsets/AFNetworking/) for a comprehensive look at the APIs available in AFNetworking
+- Check out the [complete documentation](http://afnetworking.github.com/AFNetworking/) for a comprehensive look at the APIs available in AFNetworking
 - Watch the [NSScreencast episode about AFNetworking](http://nsscreencast.com/episodes/6-afnetworking) for a quick introduction to how to use it in your application
 - Questions? [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking) is the best place to find answers
 
-## Overview
-
-AFNetworking is architected to be as small and modular as possible, in order to make it simple to use and extend.
-
-<table>
-  <tr><th colspan="2" style="text-align:center;">Core</th></tr>
-  <tr>
-    <td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFURLConnectionOperation.html">AFURLConnectionOperation</a></td>
-    <td>An <tt>NSOperation</tt> that implements the <tt>NSURLConnection</tt> delegate methods.</td>
-  </tr>
-
-  <tr><th colspan="2" style="text-align:center;">HTTP Requests</th></tr>
-
-  <tr>
-    <td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFHTTPRequestOperation.html">AFHTTPRequestOperation</a></td>
-    <td>A subclass of <tt>AFURLConnectionOperation</tt> 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.</td>
-  </tr>
-  <tr>
-    <td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFJSONRequestOperation.html">AFJSONRequestOperation</a></td>
-    <td>A subclass of <tt>AFHTTPRequestOperation</tt> for downloading and working with JSON response data.</td>
-  </tr>
-  <tr>
-    <td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFXMLRequestOperation.html">AFXMLRequestOperation</a></td>
-    <td>A subclass of <tt>AFHTTPRequestOperation</tt> for downloading and working with XML response data.</td>
-  </tr>
-  <tr>
-    <td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFPropertyListRequestOperation.html">AFPropertyListRequestOperation</a></td>
-    <td>A subclass of <tt>AFHTTPRequestOperation</tt> for downloading and deserializing objects with <a href="http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/index.html">property list</a> response data.</td>
-  </tr>
-
-  <tr><th colspan="2" style="text-align:center;">HTTP Client</th></tr>
-  <tr>
-    <td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFHTTPClient.html">AFHTTPClient</a></td>
-    <td>
-      Captures the common patterns of communicating with an web application over HTTP, including:
-
-      <ul>
-        <li>Making requests from relative paths of a base URL</li>
-        <li>Setting HTTP headers to be added automatically to requests</li>
-        <li>Authenticating requests with HTTP Basic credentials or an OAuth token</li>
-        <li>Managing an <tt>NSOperationQueue</tt> for requests made by the client</li>
-        <li>Generating query strings or HTTP bodies from an <tt>NSDictionary</tt></li>
-        <li>Constructing multipart form requests</li>
-        <li>Automatically parsing HTTP response data into its corresponding object representation</li>
-        <li>Monitoring and responding to changes in network reachability</li>
-      </ul>
-    </td>
-  </tr>
-
-  <tr><th colspan="2" style="text-align:center;">Images</th></tr>
-  <tr>
-    <td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Classes/AFImageRequestOperation.html">AFImageRequestOperation</a></td>
-    <td>A subclass of <tt>AFHTTPRequestOperation</tt> for downloading and processing images.</td>
-  </tr>
-  <tr>
-    <td><a href="http://cocoadocs.org/docsets/AFNetworking/1.3.1/Categories/UIImageView+AFNetworking.html">UIImageView+AFNetworking</a></td>
-    <td>Adds methods to <tt>UIImageView</tt> for loading remote images asynchronously from a URL.</td>
-  </tr>
-</table>
-
-## Example Usage
-
-### XML Request
-
-```objective-c
-NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.flickr.com/services/rest/?method=flickr.groups.browse&api_key=b6300e17ad3c506e706cb0072175d047&cat_id=34427469792%40N01&format=rest"]];
-AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
-  XMLParser.delegate = self;
-  [XMLParser parse];
-} failure:nil];
-[operation start];
-```
-
-### Image Request
-
-```objective-c
-UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
-[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];
-```
-
-### API Client Request
+### Installation with CocoaPods
 
-```objective-c
-// AFAppDotNetAPIClient is a subclass of AFHTTPClient, which defines the base URL and default HTTP headers for NSURLRequests it creates
-[[AFAppDotNetAPIClient sharedClient] getPath:@"stream/0/posts/stream/global" parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
-    NSLog(@"App.net Global Stream: %@", JSON);
-} failure:nil];
+```ruby
+platform :ios, '7.0'
+pod "AFNetworking", "2.0.0-RC2"
 ```
 
-### File Upload with Progress Callback
-
-```objective-c
-NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
-AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
-NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
-NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
-    [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
-}];
-
-AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
-[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
-    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
-}];
-[httpClient enqueueHTTPRequestOperation:operation];
-```
+## 2.0
 
-### Streaming Request
+AFNetworking 2.0 is a major update to the framework. Building on 2 years of development, this new version introduces powerful new features, while providing an easy upgrade path for existing users.
 
-```objective-c
-NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/encode"]];
+**Read the [AFNetworking 2.0 Migration Guide](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-2.0-Migration-Guide) for an overview of the architectural and API changes.**
 
-AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
-operation.inputStream = [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]];
-operation.outputStream = [NSOutputStream outputStreamToMemory];
-[operation start];
-```
+### What's New
 
-## Requirements
+- Support for NSURLSession
+- Serialization Modules
+- Expanded UIKit Extensions
+- Real-time functionality with [Rocket](http://rocket.github.io)
 
-AFNetworking 1.0 and higher requires either [iOS 5.0](http://developer.apple.com/library/ios/#releasenotes/General/WhatsNewIniPhoneOS/Articles/iPhoneOS4.html) and above, or [Mac OS 10.7](http://developer.apple.com/library/mac/#releasenotes/MacOSX/WhatsNewInOSX/Articles/MacOSX10_6.html#//apple_ref/doc/uid/TP40008898-SW7) ([64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)) and above.
+### Coming Soon
 
-For compatibility with iOS 4.3, use the latest 0.10.x release.
+- Unit Tests Ported to 2.0
+- AFSecurity Extension
+- Core Image Serializer Extension
+- MsgPack Serializer Extension
 
-### ARC
+## Requirements
 
-AFNetworking uses ARC as of its 1.0 release.
+AFNetworking 2.0 and higher requires either iOS 7.0 and above, or Mac OS 10.9 Mavericks ([64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)) and above.
 
-If you are using AFNetworking 1.0 in your non-arc project, you will need to set a `-fobjc-arc` compiler flag on all of the AFNetworking source files. Conversely, if you are adding a pre-1.0 version of AFNetworking, you will need to set a `-fno-objc-arc` compiler flag.
+For compatibility with iOS 5 & 6, use the latest 1.x release.
 
-To set a compiler flag in Xcode, go to your active target and select the "Build Phases" tab. Now select all AFNetworking source files, press Enter, insert `-fobjc-arc` or `-fno-objc-arc` and then "Done" to enable or disable ARC for AFNetworking.
+For compatibility with iOS 4.3, use the latest 0.10.x release.
 
 ## Unit Tests
 

+ 343 - 177
Tests/AFNetworking Tests.xcodeproj/project.pbxproj

@@ -7,56 +7,42 @@
 	objects = {
 
 /* Begin PBXBuildFile section */
-		0BAD1A5426FC47BF8790D245 /* libPods-ios.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 55E73C267F33406A9F92476C /* libPods-ios.a */; };
-		2544EC45173BE382004117E8 /* SenTestingKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2544EC44173BE382004117E8 /* SenTestingKit.framework */; };
-		2544EC47173BE382004117E8 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2544EC46173BE382004117E8 /* UIKit.framework */; };
-		2544EC48173BE382004117E8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2544EC35173BE382004117E8 /* Foundation.framework */; };
-		2544EC96173BFAA8004117E8 /* SenTestingKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2544EC44173BE382004117E8 /* SenTestingKit.framework */; };
-		2544EC97173BFAA8004117E8 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2544EC80173BFAA8004117E8 /* Cocoa.framework */; };
-		25801540173EB3A70026AA6E /* AFHTTPClientTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 2580153A173EB3A70026AA6E /* AFHTTPClientTests.m */; };
-		25801541173EB3A70026AA6E /* AFHTTPClientTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 2580153A173EB3A70026AA6E /* AFHTTPClientTests.m */; };
-		25801542173EB3A70026AA6E /* AFHTTPRequestOperationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 2580153B173EB3A70026AA6E /* AFHTTPRequestOperationTests.m */; };
-		25801543173EB3A70026AA6E /* AFHTTPRequestOperationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 2580153B173EB3A70026AA6E /* AFHTTPRequestOperationTests.m */; };
-		25801546173EB3A70026AA6E /* AFNetworkingTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 2580153F173EB3A70026AA6E /* AFNetworkingTests.m */; };
-		25801547173EB3A70026AA6E /* AFNetworkingTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 2580153F173EB3A70026AA6E /* AFNetworkingTests.m */; };
-		2580154B173EB62E0026AA6E /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 25C4EC2A173D7DB30083E116 /* SystemConfiguration.framework */; };
-		2580154C173EB6340026AA6E /* CoreServices.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 25C4EC2C173D7DBA0083E116 /* CoreServices.framework */; };
-		25C4EC41173D86AE0083E116 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 25C4EC32173D7DD20083E116 /* SystemConfiguration.framework */; };
-		25C4EC42173D86B60083E116 /* MobileCoreServices.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 25C4EC30173D7DCA0083E116 /* MobileCoreServices.framework */; };
-		29A9CE2117456336002360C8 /* AFJSONRequestOperationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 29A9CE2017456336002360C8 /* AFJSONRequestOperationTests.m */; };
-		29A9CE2217456336002360C8 /* AFJSONRequestOperationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 29A9CE2017456336002360C8 /* AFJSONRequestOperationTests.m */; };
-		667B268117599C5800764906 /* AFImageRequestOperationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 667B268017599C5800764906 /* AFImageRequestOperationTests.m */; };
-		A7DC62A917592E4800EBEC2F /* AFURLConnectionOperationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = A7DC62A817592E4800EBEC2F /* AFURLConnectionOperationTests.m */; };
-		A7DC62AA17592E4800EBEC2F /* AFURLConnectionOperationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = A7DC62A817592E4800EBEC2F /* AFURLConnectionOperationTests.m */; };
-		AC11A74923B64A3096ACADFC /* libPods-osx.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 96A923755B00464187DEDBAF /* libPods-osx.a */; };
-		F8C6F282174D2C6200B154D5 /* Icon.png in Resources */ = {isa = PBXBuildFile; fileRef = F8C6F281174D2C6200B154D5 /* Icon.png */; };
-		F8C6F283174D2C6200B154D5 /* Icon.png in Resources */ = {isa = PBXBuildFile; fileRef = F8C6F281174D2C6200B154D5 /* Icon.png */; };
-		F8D62D3B175ABF5E00C717C3 /* AFMockURLProtocol.m in Sources */ = {isa = PBXBuildFile; fileRef = F8D62D3A175ABF5E00C717C3 /* AFMockURLProtocol.m */; };
-		F8D62D3C175ABF5E00C717C3 /* AFMockURLProtocol.m in Sources */ = {isa = PBXBuildFile; fileRef = F8D62D3A175ABF5E00C717C3 /* AFMockURLProtocol.m */; };
-		F8E801E1175AC349008D3886 /* ca.cer in Resources */ = {isa = PBXBuildFile; fileRef = F8E801DD175AC349008D3886 /* ca.cer */; };
-		F8E801E2175AC349008D3886 /* ca.cer in Resources */ = {isa = PBXBuildFile; fileRef = F8E801DD175AC349008D3886 /* ca.cer */; };
-		F8E801E3175AC349008D3886 /* derived.cert in Resources */ = {isa = PBXBuildFile; fileRef = F8E801DE175AC349008D3886 /* derived.cert */; };
-		F8E801E4175AC349008D3886 /* derived.cert in Resources */ = {isa = PBXBuildFile; fileRef = F8E801DE175AC349008D3886 /* derived.cert */; };
-		F8E801E5175AC349008D3886 /* root_certificate.cer in Resources */ = {isa = PBXBuildFile; fileRef = F8E801DF175AC349008D3886 /* root_certificate.cer */; };
-		F8E801E6175AC349008D3886 /* root_certificate.cer in Resources */ = {isa = PBXBuildFile; fileRef = F8E801DF175AC349008D3886 /* root_certificate.cer */; };
-		F8E801E7175AC349008D3886 /* root_certificate.key in Resources */ = {isa = PBXBuildFile; fileRef = F8E801E0175AC349008D3886 /* root_certificate.key */; };
-		F8E801E8175AC349008D3886 /* root_certificate.key in Resources */ = {isa = PBXBuildFile; fileRef = F8E801E0175AC349008D3886 /* root_certificate.key */; };
+		2902D27917DF4E1100C81C5A /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 29B9ED5C17DF4D350021E4D5 /* XCTest.framework */; };
+		2902D27A17DF4E1200C81C5A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2544EC35173BE382004117E8 /* Foundation.framework */; };
+		2902D27B17DF4E1200C81C5A /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 29133DD617DE77ED006E0493 /* UIKit.framework */; };
+		2902D28117DF4E1200C81C5A /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 2902D27F17DF4E1200C81C5A /* InfoPlist.strings */; };
+		2902D28D17DF4E2900C81C5A /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 29B9ED5C17DF4D350021E4D5 /* XCTest.framework */; };
+		2902D28E17DF4E2A00C81C5A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2544EC35173BE382004117E8 /* Foundation.framework */; };
+		2902D28F17DF4E2A00C81C5A /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 29133DD617DE77ED006E0493 /* UIKit.framework */; };
+		2902D29517DF4E2A00C81C5A /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 2902D29317DF4E2A00C81C5A /* InfoPlist.strings */; };
+		2902D29C17DF4E3700C81C5A /* AFTestCase.m in Sources */ = {isa = PBXBuildFile; fileRef = 29B9ED7617DF4D790021E4D5 /* AFTestCase.m */; };
+		2902D29D17DF4E3800C81C5A /* AFTestCase.m in Sources */ = {isa = PBXBuildFile; fileRef = 29B9ED7617DF4D790021E4D5 /* AFTestCase.m */; };
+		29CBFC3917DF4F120021AB75 /* AFHTTPRequestOperationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 29CBFC3817DF4F120021AB75 /* AFHTTPRequestOperationTests.m */; };
+		29CBFC3A17DF4F120021AB75 /* AFHTTPRequestOperationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 29CBFC3817DF4F120021AB75 /* AFHTTPRequestOperationTests.m */; };
+		29CBFC3C17DF541F0021AB75 /* AFJSONSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 29CBFC3B17DF541F0021AB75 /* AFJSONSerializationTests.m */; };
+		29CBFC3D17DF541F0021AB75 /* AFJSONSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 29CBFC3B17DF541F0021AB75 /* AFJSONSerializationTests.m */; };
+		29CBFC3F17DF58000021AB75 /* AFHTTPSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 29CBFC3E17DF58000021AB75 /* AFHTTPSerializationTests.m */; };
+		29CBFC4017DF58000021AB75 /* AFHTTPSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 29CBFC3E17DF58000021AB75 /* AFHTTPSerializationTests.m */; };
+		29CBFC5A17DF61B30021AB75 /* AFSecurityPolicyTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 29CBFC5917DF61B30021AB75 /* AFSecurityPolicyTests.m */; };
+		29CBFC5B17DF61B30021AB75 /* AFSecurityPolicyTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 29CBFC5917DF61B30021AB75 /* AFSecurityPolicyTests.m */; };
+		29CBFC7617DF697C0021AB75 /* HTTPBinOrgServerTrustChain in Resources */ = {isa = PBXBuildFile; fileRef = 29CBFC7517DF697C0021AB75 /* HTTPBinOrgServerTrustChain */; };
+		29CBFC7717DF697C0021AB75 /* HTTPBinOrgServerTrustChain in Resources */ = {isa = PBXBuildFile; fileRef = 29CBFC7517DF697C0021AB75 /* HTTPBinOrgServerTrustChain */; };
+		29CBFC7917DF6B200021AB75 /* httpbinorg_10242013.cer in Resources */ = {isa = PBXBuildFile; fileRef = 29CBFC7817DF6B200021AB75 /* httpbinorg_10242013.cer */; };
+		29CBFC7A17DF6B200021AB75 /* httpbinorg_10242013.cer in Resources */ = {isa = PBXBuildFile; fileRef = 29CBFC7817DF6B200021AB75 /* httpbinorg_10242013.cer */; };
+		29CBFC8717DF74C60021AB75 /* ADNNetServerTrustChain in Resources */ = {isa = PBXBuildFile; fileRef = 29CBFC8617DF74C60021AB75 /* ADNNetServerTrustChain */; };
+		29CBFC8817DF74C60021AB75 /* ADNNetServerTrustChain in Resources */ = {isa = PBXBuildFile; fileRef = 29CBFC8617DF74C60021AB75 /* ADNNetServerTrustChain */; };
+		3D56634E3A564CEE86172413 /* libPods-osx.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 96A923755B00464187DEDBAF /* libPods-osx.a */; };
+		6D86BAA5C6174E98AE719CE9 /* libPods-ios.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 55E73C267F33406A9F92476C /* libPods-ios.a */; };
 /* End PBXBuildFile section */
 
 /* Begin PBXFileReference section */
 		2544EC35173BE382004117E8 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
-		2544EC43173BE382004117E8 /* iOS Tests.octest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "iOS Tests.octest"; sourceTree = BUILT_PRODUCTS_DIR; };
 		2544EC44173BE382004117E8 /* SenTestingKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SenTestingKit.framework; path = Library/Frameworks/SenTestingKit.framework; sourceTree = DEVELOPER_DIR; };
 		2544EC46173BE382004117E8 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; };
 		2544EC80173BFAA8004117E8 /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = Library/Frameworks/Cocoa.framework; sourceTree = DEVELOPER_DIR; };
 		2544EC83173BFAA8004117E8 /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = Library/Frameworks/AppKit.framework; sourceTree = SDKROOT; };
 		2544EC84173BFAA8004117E8 /* CoreData.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreData.framework; path = Library/Frameworks/CoreData.framework; sourceTree = SDKROOT; };
 		2544EC85173BFAA8004117E8 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
-		2544EC95173BFAA8004117E8 /* OS X Tests.octest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "OS X Tests.octest"; sourceTree = BUILT_PRODUCTS_DIR; };
-		2580153A173EB3A70026AA6E /* AFHTTPClientTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPClientTests.m; sourceTree = "<group>"; };
-		2580153B173EB3A70026AA6E /* AFHTTPRequestOperationTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPRequestOperationTests.m; sourceTree = "<group>"; };
-		2580153E173EB3A70026AA6E /* AFNetworkingTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworkingTests.h; sourceTree = "<group>"; };
-		2580153F173EB3A70026AA6E /* AFNetworkingTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFNetworkingTests.m; sourceTree = "<group>"; };
 		25801549173EB4B40026AA6E /* Pods-ios.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Pods-ios.xcconfig"; path = "Pods/Pods-ios.xcconfig"; sourceTree = "<group>"; };
 		2580154A173EB4B40026AA6E /* Pods-osx.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Pods-osx.xcconfig"; path = "Pods/Pods-osx.xcconfig"; sourceTree = "<group>"; };
 		25C4EC2A173D7DB30083E116 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk/System/Library/Frameworks/SystemConfiguration.framework; sourceTree = DEVELOPER_DIR; };
@@ -64,44 +50,62 @@
 		25C4EC2E173D7DC40083E116 /* CFNetwork.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = System/Library/Frameworks/CFNetwork.framework; sourceTree = SDKROOT; };
 		25C4EC30173D7DCA0083E116 /* MobileCoreServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MobileCoreServices.framework; path = System/Library/Frameworks/MobileCoreServices.framework; sourceTree = SDKROOT; };
 		25C4EC32173D7DD20083E116 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; };
-		29A9CE2017456336002360C8 /* AFJSONRequestOperationTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFJSONRequestOperationTests.m; sourceTree = "<group>"; };
+		2902D27817DF4E1100C81C5A /* iOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "iOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
+		2902D27E17DF4E1200C81C5A /* iOS Tests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "iOS Tests-Info.plist"; sourceTree = "<group>"; };
+		2902D28017DF4E1200C81C5A /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = "<group>"; };
+		2902D28417DF4E1200C81C5A /* iOS Tests-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "iOS Tests-Prefix.pch"; sourceTree = "<group>"; };
+		2902D28C17DF4E2900C81C5A /* OS X Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "OS X Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
+		2902D29217DF4E2A00C81C5A /* OS X Tests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "OS X Tests-Info.plist"; sourceTree = "<group>"; };
+		2902D29417DF4E2A00C81C5A /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = "<group>"; };
+		2902D29817DF4E2A00C81C5A /* OS X Tests-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "OS X Tests-Prefix.pch"; sourceTree = "<group>"; };
+		29133DD417DE77A5006E0493 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; };
+		29133DD617DE77ED006E0493 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
+		29133DD817DE7829006E0493 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; };
+		29B9ED5C17DF4D350021E4D5 /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = XCTest.framework; path = Library/Frameworks/XCTest.framework; sourceTree = DEVELOPER_DIR; };
+		29B9ED6D17DF4D670021E4D5 /* AFHTTPClientTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFHTTPClientTests.m; sourceTree = "<group>"; };
+		29B9ED6E17DF4D670021E4D5 /* AFHTTPRequestOperationTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFHTTPRequestOperationTests.m; sourceTree = "<group>"; };
+		29B9ED6F17DF4D670021E4D5 /* AFImageRequestOperationTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFImageRequestOperationTests.m; sourceTree = "<group>"; };
+		29B9ED7017DF4D670021E4D5 /* AFJSONRequestOperationTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFJSONRequestOperationTests.m; sourceTree = "<group>"; };
+		29B9ED7117DF4D670021E4D5 /* AFMockURLProtocol.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AFMockURLProtocol.h; sourceTree = "<group>"; };
+		29B9ED7217DF4D670021E4D5 /* AFMockURLProtocol.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFMockURLProtocol.m; sourceTree = "<group>"; };
+		29B9ED7317DF4D670021E4D5 /* AFNetworkingTests.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AFNetworkingTests.h; sourceTree = "<group>"; };
+		29B9ED7417DF4D670021E4D5 /* AFNetworkingTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFNetworkingTests.m; sourceTree = "<group>"; };
+		29B9ED7517DF4D670021E4D5 /* AFURLConnectionOperationTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFURLConnectionOperationTests.m; sourceTree = "<group>"; };
+		29B9ED7617DF4D790021E4D5 /* AFTestCase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFTestCase.m; sourceTree = "<group>"; };
+		29B9ED7817DF4D830021E4D5 /* AFTestCase.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AFTestCase.h; sourceTree = "<group>"; };
+		29CBFC3817DF4F120021AB75 /* AFHTTPRequestOperationTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPRequestOperationTests.m; sourceTree = "<group>"; };
+		29CBFC3B17DF541F0021AB75 /* AFJSONSerializationTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFJSONSerializationTests.m; sourceTree = "<group>"; };
+		29CBFC3E17DF58000021AB75 /* AFHTTPSerializationTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPSerializationTests.m; sourceTree = "<group>"; };
+		29CBFC5917DF61B30021AB75 /* AFSecurityPolicyTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFSecurityPolicyTests.m; sourceTree = "<group>"; };
+		29CBFC7517DF697C0021AB75 /* HTTPBinOrgServerTrustChain */ = {isa = PBXFileReference; lastKnownFileType = folder; path = HTTPBinOrgServerTrustChain; sourceTree = "<group>"; };
+		29CBFC7817DF6B200021AB75 /* httpbinorg_10242013.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = httpbinorg_10242013.cer; sourceTree = "<group>"; };
+		29CBFC8617DF74C60021AB75 /* ADNNetServerTrustChain */ = {isa = PBXFileReference; lastKnownFileType = folder; path = ADNNetServerTrustChain; sourceTree = "<group>"; };
 		2B6D24F8E1B74E10A269E8B3 /* libPods.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPods.a; sourceTree = BUILT_PRODUCTS_DIR; };
 		55E73C267F33406A9F92476C /* libPods-ios.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-ios.a"; sourceTree = BUILT_PRODUCTS_DIR; };
-		667B268017599C5800764906 /* AFImageRequestOperationTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFImageRequestOperationTests.m; sourceTree = "<group>"; };
 		96A923755B00464187DEDBAF /* libPods-osx.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-osx.a"; sourceTree = BUILT_PRODUCTS_DIR; };
-		A7DC62A817592E4800EBEC2F /* AFURLConnectionOperationTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLConnectionOperationTests.m; sourceTree = "<group>"; };
 		F8C6F281174D2C6200B154D5 /* Icon.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = Icon.png; path = ../Example/Icon.png; sourceTree = "<group>"; };
-		F8D62D39175ABF5E00C717C3 /* AFMockURLProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFMockURLProtocol.h; sourceTree = "<group>"; };
-		F8D62D3A175ABF5E00C717C3 /* AFMockURLProtocol.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFMockURLProtocol.m; sourceTree = "<group>"; };
-		F8E801DD175AC349008D3886 /* ca.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = ca.cer; path = Resources/ca.cer; sourceTree = "<group>"; };
-		F8E801DE175AC349008D3886 /* derived.cert */ = {isa = PBXFileReference; lastKnownFileType = file; name = derived.cert; path = Resources/derived.cert; sourceTree = "<group>"; };
-		F8E801DF175AC349008D3886 /* root_certificate.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = root_certificate.cer; path = Resources/root_certificate.cer; sourceTree = "<group>"; };
-		F8E801E0175AC349008D3886 /* root_certificate.key */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = root_certificate.key; path = Resources/root_certificate.key; sourceTree = "<group>"; };
 /* End PBXFileReference section */
 
 /* Begin PBXFrameworksBuildPhase section */
-		2544EC3F173BE382004117E8 /* Frameworks */ = {
+		2902D27517DF4E1100C81C5A /* Frameworks */ = {
 			isa = PBXFrameworksBuildPhase;
 			buildActionMask = 2147483647;
 			files = (
-				25C4EC42173D86B60083E116 /* MobileCoreServices.framework in Frameworks */,
-				25C4EC41173D86AE0083E116 /* SystemConfiguration.framework in Frameworks */,
-				2544EC45173BE382004117E8 /* SenTestingKit.framework in Frameworks */,
-				2544EC47173BE382004117E8 /* UIKit.framework in Frameworks */,
-				2544EC48173BE382004117E8 /* Foundation.framework in Frameworks */,
-				0BAD1A5426FC47BF8790D245 /* libPods-ios.a in Frameworks */,
+				2902D27917DF4E1100C81C5A /* XCTest.framework in Frameworks */,
+				2902D27B17DF4E1200C81C5A /* UIKit.framework in Frameworks */,
+				2902D27A17DF4E1200C81C5A /* Foundation.framework in Frameworks */,
+				6D86BAA5C6174E98AE719CE9 /* libPods-ios.a in Frameworks */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
-		2544EC91173BFAA8004117E8 /* Frameworks */ = {
+		2902D28917DF4E2900C81C5A /* Frameworks */ = {
 			isa = PBXFrameworksBuildPhase;
 			buildActionMask = 2147483647;
 			files = (
-				2580154C173EB6340026AA6E /* CoreServices.framework in Frameworks */,
-				2580154B173EB62E0026AA6E /* SystemConfiguration.framework in Frameworks */,
-				2544EC96173BFAA8004117E8 /* SenTestingKit.framework in Frameworks */,
-				2544EC97173BFAA8004117E8 /* Cocoa.framework in Frameworks */,
-				AC11A74923B64A3096ACADFC /* libPods-osx.a in Frameworks */,
+				2902D28D17DF4E2900C81C5A /* XCTest.framework in Frameworks */,
+				2902D28F17DF4E2A00C81C5A /* UIKit.framework in Frameworks */,
+				2902D28E17DF4E2A00C81C5A /* Foundation.framework in Frameworks */,
+				3D56634E3A564CEE86172413 /* libPods-osx.a in Frameworks */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
@@ -113,8 +117,10 @@
 			children = (
 				25801549173EB4B40026AA6E /* Pods-ios.xcconfig */,
 				2580154A173EB4B40026AA6E /* Pods-osx.xcconfig */,
-				25801548173EB3B00026AA6E /* Tests */,
 				25A753091747FC7E00F04F2F /* Resources */,
+				29B9ED6017DF4D350021E4D5 /* Tests */,
+				2902D27C17DF4E1200C81C5A /* iOS Tests */,
+				2902D29017DF4E2A00C81C5A /* OS X Tests */,
 				2544EC34173BE382004117E8 /* Frameworks */,
 				2544EC33173BE382004117E8 /* Products */,
 			);
@@ -123,8 +129,8 @@
 		2544EC33173BE382004117E8 /* Products */ = {
 			isa = PBXGroup;
 			children = (
-				2544EC43173BE382004117E8 /* iOS Tests.octest */,
-				2544EC95173BFAA8004117E8 /* OS X Tests.octest */,
+				2902D27817DF4E1100C81C5A /* iOS Tests.xctest */,
+				2902D28C17DF4E2900C81C5A /* OS X Tests.xctest */,
 			);
 			name = Products;
 			sourceTree = "<group>";
@@ -132,6 +138,9 @@
 		2544EC34173BE382004117E8 /* Frameworks */ = {
 			isa = PBXGroup;
 			children = (
+				29133DD817DE7829006E0493 /* Security.framework */,
+				29133DD617DE77ED006E0493 /* UIKit.framework */,
+				29133DD417DE77A5006E0493 /* CoreGraphics.framework */,
 				25C4EC32173D7DD20083E116 /* SystemConfiguration.framework */,
 				25C4EC30173D7DCA0083E116 /* MobileCoreServices.framework */,
 				25C4EC2E173D7DC40083E116 /* CFNetwork.framework */,
@@ -141,6 +150,7 @@
 				2544EC44173BE382004117E8 /* SenTestingKit.framework */,
 				2544EC46173BE382004117E8 /* UIKit.framework */,
 				2544EC80173BFAA8004117E8 /* Cocoa.framework */,
+				29B9ED5C17DF4D350021E4D5 /* XCTest.framework */,
 				2544EC82173BFAA8004117E8 /* Other Frameworks */,
 				55E73C267F33406A9F92476C /* libPods-ios.a */,
 				96A923755B00464187DEDBAF /* libPods-osx.a */,
@@ -159,22 +169,6 @@
 			name = "Other Frameworks";
 			sourceTree = "<group>";
 		};
-		25801548173EB3B00026AA6E /* Tests */ = {
-			isa = PBXGroup;
-			children = (
-				2580153E173EB3A70026AA6E /* AFNetworkingTests.h */,
-				F8D62D39175ABF5E00C717C3 /* AFMockURLProtocol.h */,
-				F8D62D3A175ABF5E00C717C3 /* AFMockURLProtocol.m */,
-				2580153F173EB3A70026AA6E /* AFNetworkingTests.m */,
-				A7DC62A817592E4800EBEC2F /* AFURLConnectionOperationTests.m */,
-				2580153B173EB3A70026AA6E /* AFHTTPRequestOperationTests.m */,
-				29A9CE2017456336002360C8 /* AFJSONRequestOperationTests.m */,
-				667B268017599C5800764906 /* AFImageRequestOperationTests.m */,
-				2580153A173EB3A70026AA6E /* AFHTTPClientTests.m */,
-			);
-			name = Tests;
-			sourceTree = "<group>";
-		};
 		25A753091747FC7E00F04F2F /* Resources */ = {
 			isa = PBXGroup;
 			children = (
@@ -184,13 +178,96 @@
 			name = Resources;
 			sourceTree = "<group>";
 		};
+		2902D27C17DF4E1200C81C5A /* iOS Tests */ = {
+			isa = PBXGroup;
+			children = (
+				2902D27D17DF4E1200C81C5A /* Supporting Files */,
+			);
+			path = "iOS Tests";
+			sourceTree = "<group>";
+		};
+		2902D27D17DF4E1200C81C5A /* Supporting Files */ = {
+			isa = PBXGroup;
+			children = (
+				2902D27E17DF4E1200C81C5A /* iOS Tests-Info.plist */,
+				2902D27F17DF4E1200C81C5A /* InfoPlist.strings */,
+				2902D28417DF4E1200C81C5A /* iOS Tests-Prefix.pch */,
+			);
+			name = "Supporting Files";
+			sourceTree = "<group>";
+		};
+		2902D29017DF4E2A00C81C5A /* OS X Tests */ = {
+			isa = PBXGroup;
+			children = (
+				2902D29117DF4E2A00C81C5A /* Supporting Files */,
+			);
+			path = "OS X Tests";
+			sourceTree = "<group>";
+		};
+		2902D29117DF4E2A00C81C5A /* Supporting Files */ = {
+			isa = PBXGroup;
+			children = (
+				2902D29217DF4E2A00C81C5A /* OS X Tests-Info.plist */,
+				2902D29317DF4E2A00C81C5A /* InfoPlist.strings */,
+				2902D29817DF4E2A00C81C5A /* OS X Tests-Prefix.pch */,
+			);
+			name = "Supporting Files";
+			sourceTree = "<group>";
+		};
+		29B9ED6017DF4D350021E4D5 /* Tests */ = {
+			isa = PBXGroup;
+			children = (
+				29B9ED6C17DF4D670021E4D5 /* 1.0 Tests */,
+				29B9ED7817DF4D830021E4D5 /* AFTestCase.h */,
+				29B9ED7617DF4D790021E4D5 /* AFTestCase.m */,
+				29CBFC3817DF4F120021AB75 /* AFHTTPRequestOperationTests.m */,
+				29CBFC3E17DF58000021AB75 /* AFHTTPSerializationTests.m */,
+				29CBFC3B17DF541F0021AB75 /* AFJSONSerializationTests.m */,
+				29CBFC5917DF61B30021AB75 /* AFSecurityPolicyTests.m */,
+			);
+			path = Tests;
+			sourceTree = "<group>";
+		};
+		29B9ED6C17DF4D670021E4D5 /* 1.0 Tests */ = {
+			isa = PBXGroup;
+			children = (
+				29B9ED6D17DF4D670021E4D5 /* AFHTTPClientTests.m */,
+				29B9ED6E17DF4D670021E4D5 /* AFHTTPRequestOperationTests.m */,
+				29B9ED6F17DF4D670021E4D5 /* AFImageRequestOperationTests.m */,
+				29B9ED7017DF4D670021E4D5 /* AFJSONRequestOperationTests.m */,
+				29B9ED7117DF4D670021E4D5 /* AFMockURLProtocol.h */,
+				29B9ED7217DF4D670021E4D5 /* AFMockURLProtocol.m */,
+				29B9ED7317DF4D670021E4D5 /* AFNetworkingTests.h */,
+				29B9ED7417DF4D670021E4D5 /* AFNetworkingTests.m */,
+				29B9ED7517DF4D670021E4D5 /* AFURLConnectionOperationTests.m */,
+			);
+			path = "1.0 Tests";
+			sourceTree = "<group>";
+		};
+		29CBFC4E17DF61920021AB75 /* HTTPBin.org */ = {
+			isa = PBXGroup;
+			children = (
+				29CBFC7817DF6B200021AB75 /* httpbinorg_10242013.cer */,
+				29CBFC7517DF697C0021AB75 /* HTTPBinOrgServerTrustChain */,
+			);
+			name = HTTPBin.org;
+			path = Resources/HTTPBin.org;
+			sourceTree = "<group>";
+		};
+		29CBFC7B17DF74A80021AB75 /* ADN.net */ = {
+			isa = PBXGroup;
+			children = (
+				29CBFC8617DF74C60021AB75 /* ADNNetServerTrustChain */,
+			);
+			name = ADN.net;
+			path = Resources/ADN.net;
+			sourceTree = "<group>";
+		};
 		F8E801E9175AC34D008D3886 /* Certificates */ = {
 			isa = PBXGroup;
 			children = (
-				F8E801DD175AC349008D3886 /* ca.cer */,
-				F8E801DE175AC349008D3886 /* derived.cert */,
-				F8E801DF175AC349008D3886 /* root_certificate.cer */,
-				F8E801E0175AC349008D3886 /* root_certificate.key */,
+				29CBFC7B17DF74A80021AB75 /* ADN.net */,
+				29CBFC4E17DF61920021AB75 /* HTTPBin.org */,
 			);
 			name = Certificates;
 			sourceTree = "<group>";
@@ -198,41 +275,43 @@
 /* End PBXGroup section */
 
 /* Begin PBXNativeTarget section */
-		2544EC42173BE382004117E8 /* iOS Tests */ = {
+		2902D27717DF4E1100C81C5A /* iOS Tests */ = {
 			isa = PBXNativeTarget;
-			buildConfigurationList = 2544EC5A173BE382004117E8 /* Build configuration list for PBXNativeTarget "iOS Tests" */;
+			buildConfigurationList = 2902D28717DF4E1200C81C5A /* Build configuration list for PBXNativeTarget "iOS Tests" */;
 			buildPhases = (
-				2544EC3E173BE382004117E8 /* Sources */,
-				2544EC3F173BE382004117E8 /* Frameworks */,
-				2544EC40173BE382004117E8 /* Resources */,
-				2544EC41173BE382004117E8 /* ShellScript */,
+				54CD36584E3B40719F14C3C9 /* Check Pods Manifest.lock */,
+				2902D27417DF4E1100C81C5A /* Sources */,
+				2902D27517DF4E1100C81C5A /* Frameworks */,
+				2902D27617DF4E1100C81C5A /* Resources */,
+				DFF6BB8B6C8D4F8ABC235667 /* Copy Pods Resources */,
 			);
 			buildRules = (
 			);
 			dependencies = (
 			);
 			name = "iOS Tests";
-			productName = AFNetworkingTests;
-			productReference = 2544EC43173BE382004117E8 /* iOS Tests.octest */;
-			productType = "com.apple.product-type.bundle";
+			productName = "iOS Tests";
+			productReference = 2902D27817DF4E1100C81C5A /* iOS Tests.xctest */;
+			productType = "com.apple.product-type.bundle.unit-test";
 		};
-		2544EC94173BFAA8004117E8 /* OS X Tests */ = {
+		2902D28B17DF4E2900C81C5A /* OS X Tests */ = {
 			isa = PBXNativeTarget;
-			buildConfigurationList = 2544ECA7173BFAA8004117E8 /* Build configuration list for PBXNativeTarget "OS X Tests" */;
+			buildConfigurationList = 2902D29917DF4E2A00C81C5A /* Build configuration list for PBXNativeTarget "OS X Tests" */;
 			buildPhases = (
-				2544EC90173BFAA8004117E8 /* Sources */,
-				2544EC91173BFAA8004117E8 /* Frameworks */,
-				2544EC92173BFAA8004117E8 /* Resources */,
-				2544EC93173BFAA8004117E8 /* ShellScript */,
+				6949C05DBEB94BC2BAE81768 /* Check Pods Manifest.lock */,
+				2902D28817DF4E2900C81C5A /* Sources */,
+				2902D28917DF4E2900C81C5A /* Frameworks */,
+				2902D28A17DF4E2900C81C5A /* Resources */,
+				D728EB5862164B87922C9B80 /* Copy Pods Resources */,
 			);
 			buildRules = (
 			);
 			dependencies = (
 			);
 			name = "OS X Tests";
-			productName = AFNetworkingFrameworkTests;
-			productReference = 2544EC95173BFAA8004117E8 /* OS X Tests.octest */;
-			productType = "com.apple.product-type.bundle";
+			productName = "OS X Tests";
+			productReference = 2902D28C17DF4E2900C81C5A /* OS X Tests.xctest */;
+			productType = "com.apple.product-type.bundle.unit-test";
 		};
 /* End PBXNativeTarget section */
 
@@ -255,98 +334,146 @@
 			projectDirPath = "";
 			projectRoot = "";
 			targets = (
-				2544EC42173BE382004117E8 /* iOS Tests */,
-				2544EC94173BFAA8004117E8 /* OS X Tests */,
+				2902D27717DF4E1100C81C5A /* iOS Tests */,
+				2902D28B17DF4E2900C81C5A /* OS X Tests */,
 			);
 		};
 /* End PBXProject section */
 
 /* Begin PBXResourcesBuildPhase section */
-		2544EC40173BE382004117E8 /* Resources */ = {
+		2902D27617DF4E1100C81C5A /* Resources */ = {
 			isa = PBXResourcesBuildPhase;
 			buildActionMask = 2147483647;
 			files = (
-				F8C6F282174D2C6200B154D5 /* Icon.png in Resources */,
-				F8E801E1175AC349008D3886 /* ca.cer in Resources */,
-				F8E801E3175AC349008D3886 /* derived.cert in Resources */,
-				F8E801E5175AC349008D3886 /* root_certificate.cer in Resources */,
-				F8E801E7175AC349008D3886 /* root_certificate.key in Resources */,
+				29CBFC8717DF74C60021AB75 /* ADNNetServerTrustChain in Resources */,
+				2902D28117DF4E1200C81C5A /* InfoPlist.strings in Resources */,
+				29CBFC7917DF6B200021AB75 /* httpbinorg_10242013.cer in Resources */,
+				29CBFC7617DF697C0021AB75 /* HTTPBinOrgServerTrustChain in Resources */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
-		2544EC92173BFAA8004117E8 /* Resources */ = {
+		2902D28A17DF4E2900C81C5A /* Resources */ = {
 			isa = PBXResourcesBuildPhase;
 			buildActionMask = 2147483647;
 			files = (
-				F8C6F283174D2C6200B154D5 /* Icon.png in Resources */,
-				F8E801E2175AC349008D3886 /* ca.cer in Resources */,
-				F8E801E4175AC349008D3886 /* derived.cert in Resources */,
-				F8E801E6175AC349008D3886 /* root_certificate.cer in Resources */,
-				F8E801E8175AC349008D3886 /* root_certificate.key in Resources */,
+				29CBFC8817DF74C60021AB75 /* ADNNetServerTrustChain in Resources */,
+				2902D29517DF4E2A00C81C5A /* InfoPlist.strings in Resources */,
+				29CBFC7A17DF6B200021AB75 /* httpbinorg_10242013.cer in Resources */,
+				29CBFC7717DF697C0021AB75 /* HTTPBinOrgServerTrustChain in Resources */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
 /* End PBXResourcesBuildPhase section */
 
 /* Begin PBXShellScriptBuildPhase section */
-		2544EC41173BE382004117E8 /* ShellScript */ = {
+		54CD36584E3B40719F14C3C9 /* Check Pods Manifest.lock */ = {
 			isa = PBXShellScriptBuildPhase;
 			buildActionMask = 2147483647;
 			files = (
 			);
 			inputPaths = (
 			);
+			name = "Check Pods Manifest.lock";
 			outputPaths = (
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 			shellPath = /bin/sh;
-			shellScript = "# Run the unit tests in this test bundle.\n\"${SYSTEM_DEVELOPER_DIR}/Tools/RunUnitTests\"\n";
+			shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n    cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n    exit 1\nfi\n";
+			showEnvVarsInLog = 0;
 		};
-		2544EC93173BFAA8004117E8 /* ShellScript */ = {
+		6949C05DBEB94BC2BAE81768 /* Check Pods Manifest.lock */ = {
 			isa = PBXShellScriptBuildPhase;
 			buildActionMask = 2147483647;
 			files = (
 			);
 			inputPaths = (
 			);
+			name = "Check Pods Manifest.lock";
 			outputPaths = (
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 			shellPath = /bin/sh;
-			shellScript = "# Run the unit tests in this test bundle.\n\"${SYSTEM_DEVELOPER_DIR}/Tools/RunUnitTests\"\n";
+			shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n    cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n    exit 1\nfi\n";
+			showEnvVarsInLog = 0;
+		};
+		D728EB5862164B87922C9B80 /* Copy Pods Resources */ = {
+			isa = PBXShellScriptBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			inputPaths = (
+			);
+			name = "Copy Pods Resources";
+			outputPaths = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+			shellPath = /bin/sh;
+			shellScript = "\"${SRCROOT}/Pods/Pods-osx-resources.sh\"\n";
+			showEnvVarsInLog = 0;
+		};
+		DFF6BB8B6C8D4F8ABC235667 /* Copy Pods Resources */ = {
+			isa = PBXShellScriptBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			inputPaths = (
+			);
+			name = "Copy Pods Resources";
+			outputPaths = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+			shellPath = /bin/sh;
+			shellScript = "\"${SRCROOT}/Pods/Pods-ios-resources.sh\"\n";
+			showEnvVarsInLog = 0;
 		};
 /* End PBXShellScriptBuildPhase section */
 
 /* Begin PBXSourcesBuildPhase section */
-		2544EC3E173BE382004117E8 /* Sources */ = {
+		2902D27417DF4E1100C81C5A /* Sources */ = {
 			isa = PBXSourcesBuildPhase;
 			buildActionMask = 2147483647;
 			files = (
-				25801540173EB3A70026AA6E /* AFHTTPClientTests.m in Sources */,
-				25801542173EB3A70026AA6E /* AFHTTPRequestOperationTests.m in Sources */,
-				25801546173EB3A70026AA6E /* AFNetworkingTests.m in Sources */,
-				29A9CE2117456336002360C8 /* AFJSONRequestOperationTests.m in Sources */,
-				A7DC62A917592E4800EBEC2F /* AFURLConnectionOperationTests.m in Sources */,
-				667B268117599C5800764906 /* AFImageRequestOperationTests.m in Sources */,
-				F8D62D3B175ABF5E00C717C3 /* AFMockURLProtocol.m in Sources */,
+				29CBFC3917DF4F120021AB75 /* AFHTTPRequestOperationTests.m in Sources */,
+				29CBFC5A17DF61B30021AB75 /* AFSecurityPolicyTests.m in Sources */,
+				29CBFC3F17DF58000021AB75 /* AFHTTPSerializationTests.m in Sources */,
+				29CBFC3C17DF541F0021AB75 /* AFJSONSerializationTests.m in Sources */,
+				2902D29C17DF4E3700C81C5A /* AFTestCase.m in Sources */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
-		2544EC90173BFAA8004117E8 /* Sources */ = {
+		2902D28817DF4E2900C81C5A /* Sources */ = {
 			isa = PBXSourcesBuildPhase;
 			buildActionMask = 2147483647;
 			files = (
-				25801541173EB3A70026AA6E /* AFHTTPClientTests.m in Sources */,
-				25801543173EB3A70026AA6E /* AFHTTPRequestOperationTests.m in Sources */,
-				25801547173EB3A70026AA6E /* AFNetworkingTests.m in Sources */,
-				29A9CE2217456336002360C8 /* AFJSONRequestOperationTests.m in Sources */,
-				A7DC62AA17592E4800EBEC2F /* AFURLConnectionOperationTests.m in Sources */,
-				F8D62D3C175ABF5E00C717C3 /* AFMockURLProtocol.m in Sources */,
+				29CBFC3A17DF4F120021AB75 /* AFHTTPRequestOperationTests.m in Sources */,
+				29CBFC5B17DF61B30021AB75 /* AFSecurityPolicyTests.m in Sources */,
+				29CBFC4017DF58000021AB75 /* AFHTTPSerializationTests.m in Sources */,
+				29CBFC3D17DF541F0021AB75 /* AFJSONSerializationTests.m in Sources */,
+				2902D29D17DF4E3800C81C5A /* AFTestCase.m in Sources */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
 /* End PBXSourcesBuildPhase section */
 
+/* Begin PBXVariantGroup section */
+		2902D27F17DF4E1200C81C5A /* InfoPlist.strings */ = {
+			isa = PBXVariantGroup;
+			children = (
+				2902D28017DF4E1200C81C5A /* en */,
+			);
+			name = InfoPlist.strings;
+			sourceTree = "<group>";
+		};
+		2902D29317DF4E2A00C81C5A /* InfoPlist.strings */ = {
+			isa = PBXVariantGroup;
+			children = (
+				2902D29417DF4E2A00C81C5A /* en */,
+			);
+			name = InfoPlist.strings;
+			sourceTree = "<group>";
+		};
+/* End PBXVariantGroup section */
+
 /* Begin XCBuildConfiguration section */
 		2544EC55173BE382004117E8 /* Debug */ = {
 			isa = XCBuildConfiguration;
@@ -401,74 +528,113 @@
 			};
 			name = Release;
 		};
-		2544EC5B173BE382004117E8 /* Debug */ = {
+		2902D28517DF4E1200C81C5A /* Debug */ = {
 			isa = XCBuildConfiguration;
 			baseConfigurationReference = 25801549173EB4B40026AA6E /* Pods-ios.xcconfig */;
 			buildSettings = {
+				CLANG_ENABLE_MODULES = YES;
+				CLANG_WARN_BOOL_CONVERSION = YES;
+				CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+				CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
 				FRAMEWORK_SEARCH_PATHS = (
-					"\"$(SDKROOT)/Developer/Library/Frameworks\"",
-					"\"$(DEVELOPER_LIBRARY_DIR)/Frameworks\"",
+					"$(SDKROOT)/Developer/Library/Frameworks",
+					"$(inherited)",
+					"$(DEVELOPER_FRAMEWORKS_DIR)",
 				);
 				GCC_PRECOMPILE_PREFIX_HEADER = YES;
-				GCC_PREFIX_HEADER = "AFNetworking-Prefix.pch";
-				INFOPLIST_FILE = "AFNetworkingTests-Info.plist";
+				GCC_PREFIX_HEADER = "iOS Tests/iOS Tests-Prefix.pch";
+				GCC_PREPROCESSOR_DEFINITIONS = (
+					"DEBUG=1",
+					"$(inherited)",
+				);
+				GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+				GCC_WARN_UNDECLARED_SELECTOR = YES;
+				GCC_WARN_UNUSED_FUNCTION = YES;
+				INFOPLIST_FILE = "iOS Tests/iOS Tests-Info.plist";
+				IPHONEOS_DEPLOYMENT_TARGET = 7.0;
 				PRODUCT_NAME = "$(TARGET_NAME)";
-				WRAPPER_EXTENSION = octest;
+				WRAPPER_EXTENSION = xctest;
 			};
 			name = Debug;
 		};
-		2544EC5C173BE382004117E8 /* Release */ = {
+		2902D28617DF4E1200C81C5A /* Release */ = {
 			isa = XCBuildConfiguration;
 			baseConfigurationReference = 25801549173EB4B40026AA6E /* Pods-ios.xcconfig */;
 			buildSettings = {
+				CLANG_ENABLE_MODULES = YES;
+				CLANG_WARN_BOOL_CONVERSION = YES;
+				CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+				CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+				ENABLE_NS_ASSERTIONS = NO;
 				FRAMEWORK_SEARCH_PATHS = (
-					"\"$(SDKROOT)/Developer/Library/Frameworks\"",
-					"\"$(DEVELOPER_LIBRARY_DIR)/Frameworks\"",
+					"$(SDKROOT)/Developer/Library/Frameworks",
+					"$(inherited)",
+					"$(DEVELOPER_FRAMEWORKS_DIR)",
 				);
 				GCC_PRECOMPILE_PREFIX_HEADER = YES;
-				GCC_PREFIX_HEADER = "AFNetworking-Prefix.pch";
-				INFOPLIST_FILE = "AFNetworkingTests-Info.plist";
+				GCC_PREFIX_HEADER = "iOS Tests/iOS Tests-Prefix.pch";
+				GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+				GCC_WARN_UNDECLARED_SELECTOR = YES;
+				GCC_WARN_UNUSED_FUNCTION = YES;
+				INFOPLIST_FILE = "iOS Tests/iOS Tests-Info.plist";
+				IPHONEOS_DEPLOYMENT_TARGET = 7.0;
 				PRODUCT_NAME = "$(TARGET_NAME)";
-				WRAPPER_EXTENSION = octest;
+				WRAPPER_EXTENSION = xctest;
 			};
 			name = Release;
 		};
-		2544ECA8173BFAA8004117E8 /* Debug */ = {
+		2902D29A17DF4E2A00C81C5A /* Debug */ = {
 			isa = XCBuildConfiguration;
 			baseConfigurationReference = 2580154A173EB4B40026AA6E /* Pods-osx.xcconfig */;
 			buildSettings = {
-				ARCHS = "$(ARCHS_STANDARD_64_BIT)";
-				COMBINE_HIDPI_IMAGES = YES;
-				FRAMEWORK_SEARCH_PATHS = "\"$(DEVELOPER_LIBRARY_DIR)/Frameworks\"";
-				GCC_ENABLE_OBJC_EXCEPTIONS = YES;
+				CLANG_ENABLE_MODULES = YES;
+				CLANG_WARN_BOOL_CONVERSION = YES;
+				CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+				CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+				FRAMEWORK_SEARCH_PATHS = (
+					"$(SDKROOT)/Developer/Library/Frameworks",
+					"$(inherited)",
+					"$(DEVELOPER_FRAMEWORKS_DIR)",
+				);
 				GCC_PRECOMPILE_PREFIX_HEADER = YES;
-				GCC_PREFIX_HEADER = "AFNetworking-Prefix.pch";
-				GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
-				INFOPLIST_FILE = "AFNetworkingTests-Info.plist";
-				MACOSX_DEPLOYMENT_TARGET = 10.8;
+				GCC_PREFIX_HEADER = "OS X Tests/OS X Tests-Prefix.pch";
+				GCC_PREPROCESSOR_DEFINITIONS = (
+					"DEBUG=1",
+					"$(inherited)",
+				);
+				GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+				GCC_WARN_UNDECLARED_SELECTOR = YES;
+				GCC_WARN_UNUSED_FUNCTION = YES;
+				INFOPLIST_FILE = "OS X Tests/OS X Tests-Info.plist";
+				IPHONEOS_DEPLOYMENT_TARGET = 7.0;
 				PRODUCT_NAME = "$(TARGET_NAME)";
-				SDKROOT = macosx;
-				WRAPPER_EXTENSION = octest;
+				WRAPPER_EXTENSION = xctest;
 			};
 			name = Debug;
 		};
-		2544ECA9173BFAA8004117E8 /* Release */ = {
+		2902D29B17DF4E2A00C81C5A /* Release */ = {
 			isa = XCBuildConfiguration;
 			baseConfigurationReference = 2580154A173EB4B40026AA6E /* Pods-osx.xcconfig */;
 			buildSettings = {
-				ARCHS = "$(ARCHS_STANDARD_64_BIT)";
-				COMBINE_HIDPI_IMAGES = YES;
-				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
-				FRAMEWORK_SEARCH_PATHS = "\"$(DEVELOPER_LIBRARY_DIR)/Frameworks\"";
-				GCC_ENABLE_OBJC_EXCEPTIONS = YES;
+				CLANG_ENABLE_MODULES = YES;
+				CLANG_WARN_BOOL_CONVERSION = YES;
+				CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+				CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+				ENABLE_NS_ASSERTIONS = NO;
+				FRAMEWORK_SEARCH_PATHS = (
+					"$(SDKROOT)/Developer/Library/Frameworks",
+					"$(inherited)",
+					"$(DEVELOPER_FRAMEWORKS_DIR)",
+				);
 				GCC_PRECOMPILE_PREFIX_HEADER = YES;
-				GCC_PREFIX_HEADER = "AFNetworking-Prefix.pch";
-				GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
-				INFOPLIST_FILE = "AFNetworkingTests-Info.plist";
-				MACOSX_DEPLOYMENT_TARGET = 10.8;
+				GCC_PREFIX_HEADER = "OS X Tests/OS X Tests-Prefix.pch";
+				GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+				GCC_WARN_UNDECLARED_SELECTOR = YES;
+				GCC_WARN_UNUSED_FUNCTION = YES;
+				INFOPLIST_FILE = "OS X Tests/OS X Tests-Info.plist";
+				IPHONEOS_DEPLOYMENT_TARGET = 7.0;
 				PRODUCT_NAME = "$(TARGET_NAME)";
-				SDKROOT = macosx;
-				WRAPPER_EXTENSION = octest;
+				WRAPPER_EXTENSION = xctest;
 			};
 			name = Release;
 		};
@@ -484,20 +650,20 @@
 			defaultConfigurationIsVisible = 0;
 			defaultConfigurationName = Release;
 		};
-		2544EC5A173BE382004117E8 /* Build configuration list for PBXNativeTarget "iOS Tests" */ = {
+		2902D28717DF4E1200C81C5A /* Build configuration list for PBXNativeTarget "iOS Tests" */ = {
 			isa = XCConfigurationList;
 			buildConfigurations = (
-				2544EC5B173BE382004117E8 /* Debug */,
-				2544EC5C173BE382004117E8 /* Release */,
+				2902D28517DF4E1200C81C5A /* Debug */,
+				2902D28617DF4E1200C81C5A /* Release */,
 			);
 			defaultConfigurationIsVisible = 0;
 			defaultConfigurationName = Release;
 		};
-		2544ECA7173BFAA8004117E8 /* Build configuration list for PBXNativeTarget "OS X Tests" */ = {
+		2902D29917DF4E2A00C81C5A /* Build configuration list for PBXNativeTarget "OS X Tests" */ = {
 			isa = XCConfigurationList;
 			buildConfigurations = (
-				2544ECA8173BFAA8004117E8 /* Debug */,
-				2544ECA9173BFAA8004117E8 /* Release */,
+				2902D29A17DF4E2A00C81C5A /* Debug */,
+				2902D29B17DF4E2A00C81C5A /* Release */,
 			);
 			defaultConfigurationIsVisible = 0;
 			defaultConfigurationName = Release;

+ 22 - 0
Tests/OS X Tests/OS X Tests-Info.plist

@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>CFBundleDevelopmentRegion</key>
+	<string>en</string>
+	<key>CFBundleExecutable</key>
+	<string>${EXECUTABLE_NAME}</string>
+	<key>CFBundleIdentifier</key>
+	<string>com.alamofire.afnetworking.${PRODUCT_NAME:rfc1034identifier}</string>
+	<key>CFBundleInfoDictionaryVersion</key>
+	<string>6.0</string>
+	<key>CFBundlePackageType</key>
+	<string>BNDL</string>
+	<key>CFBundleShortVersionString</key>
+	<string>1.0</string>
+	<key>CFBundleSignature</key>
+	<string>????</string>
+	<key>CFBundleVersion</key>
+	<string>1</string>
+</dict>
+</plist>

+ 10 - 0
Tests/OS X Tests/OS X Tests-Prefix.pch

@@ -0,0 +1,10 @@
+//
+//  Prefix header
+//
+//  The contents of this file are implicitly included at the beginning of every source file.
+//
+
+#ifdef __OBJC__
+    #import <UIKit/UIKit.h>
+    #import <Foundation/Foundation.h>
+#endif

+ 2 - 0
Tests/OS X Tests/en.lproj/InfoPlist.strings

@@ -0,0 +1,2 @@
+/* Localized versions of Info.plist keys */
+

+ 2 - 3
Tests/Podfile

@@ -5,18 +5,17 @@ inhibit_all_warnings!
 def import_pods
   pod 'OCMock', '~> 2.1.1'
   pod 'Expecta', '~> 0.2.1'
-  pod 'AFHTTPRequestOperationLogger', '~> 0.10.0'
   pod 'AFNetworking', :path => '../'
 end
 
 target :ios do
-  platform :ios, '5.0'
+  platform :ios, '7.0'
   link_with 'iOS Tests'
   import_pods
 end
 
 target :osx do
-  platform :osx, '10.7'
+  platform :osx, '10.9'
   link_with 'OS X Tests'
   import_pods
 end

+ 15 - 9
Tests/Podfile.lock

@@ -1,12 +1,19 @@
 PODS:
-  - AFHTTPRequestOperationLogger (0.10.0):
-    - AFNetworking (>= 0.9.0)
-  - AFNetworking (1.3.2)
-  - Expecta (0.2.1)
+  - AFNetworking (2.0.0-RC3):
+    - AFNetworking/Core
+  - AFNetworking/Core (2.0.0-RC3):
+    - AFNetworking/NSURLConnection
+    - AFNetworking/Reachability
+    - AFNetworking/Security
+    - AFNetworking/Serialization
+  - AFNetworking/NSURLConnection (2.0.0-RC3)
+  - AFNetworking/Reachability (2.0.0-RC3)
+  - AFNetworking/Security (2.0.0-RC3)
+  - AFNetworking/Serialization (2.0.0-RC3)
+  - Expecta (0.2.2)
   - OCMock (2.1.1)
 
 DEPENDENCIES:
-  - AFHTTPRequestOperationLogger (~> 0.10.0)
   - AFNetworking (from `../`)
   - Expecta (~> 0.2.1)
   - OCMock (~> 2.1.1)
@@ -16,9 +23,8 @@ EXTERNAL SOURCES:
     :path: ../
 
 SPEC CHECKSUMS:
-  AFHTTPRequestOperationLogger: 34ba125cb9eeb77a3b67aaaca105720ba3a0798c
-  AFNetworking: 91bb494e2bd884a93d60a7a3126bc65b873486b4
-  Expecta: d46fb1bd78c90a83da0158b9b1e108de106e369f
+  AFNetworking: 2c32044b6aeb1f022e462bcb73cf6f2679f0d1ff
+  Expecta: 99adbb2e366a02796477523bfd426143350d9caf
   OCMock: 79212e5e328378af5cfd6edb5feacfd6c49cd8a3
 
-COCOAPODS: 0.22.2
+COCOAPODS: 0.24.0

BIN
Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_0.cer


BIN
Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_1.cer


BIN
Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_2.cer


BIN
Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_0.cer


BIN
Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_1.cer


BIN
Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_2.cer


BIN
Tests/Resources/HTTPBin.org/httpbinorg_10242013.cer


BIN
Tests/Resources/ca.cer


BIN
Tests/Resources/derived.cert


BIN
Tests/Resources/root_certificate.cer


+ 0 - 15
Tests/Resources/root_certificate.key

@@ -1,15 +0,0 @@
------BEGIN RSA PRIVATE KEY-----
-MIICXAIBAAKBgQCc9QJKFLopeILA83YzRmFenXIcgfIIaIbfCbFbvm/ntwCtZ7eK
-cqGBA2SI/kSEJGpIkpzq0lyb1ZJB8ayGD8p8lKfxnmOsc1RSzXz3cieomqF3ftIF
-21yp79qnwo8roWV2AAolWnmcpCwbrWmgbWueupl7ieu4gcSOXU4EikwGKwIDAQAB
-AoGASq0zmqWD8Sk6JK1xJnIs74Q/f5q/2gpJaSLGdJ0FxxxFwTsgk0l419YSZi97
-z9c3jjHbYMoXb7lMbf2bFOm8b4zQvmdVpLbiHC9Lned30VHgZJ55WSPd0GQJl9EJ
-uw4C9J2Uk7uUjQbbgGPHwO5w/75F++Cp5jN91M/7fqgxO9kCQQDMC15vSVrHR0hU
-GO235KeaDIUlIWBQYcPXZTn2kBfpSE2T3aYuIqfM5fx0z5A4nSM9Ylo/FOrm+y/p
-ogT+APTFAkEAxOxAn09r9vx46drP8ap8ca2+0x46+1xVoaAdUv/OlXV4Ftgo5l7h
-5ZRvs+JILmtvErtzkaUiCudh96F3tLAeLwJAOXO2ClW4NsYuamd+f7nlKy39S2Aj
-c16juwFombEm2mueVFUjlnfxkXLsa6OJ8zbjlkQcLwjfv1vYuMsC5tY0FQJBAJcd
-hWm7lOpwTImI9NJLNjw2TJ3OMQz7imsBZ/9tdqaTApjlQF2oqkl3Y1DzcNjOcOo7
-FzDJPBqJ/U/+hNIP5NkCQCUhCnfTXxx48sL7XKjlTr66rEbk3e1rZL7vx+24jcax
-xUooGhnRWaQsbEynVteYbPg7I8e8N6YEHtW5jwxhFaE=
------END RSA PRIVATE KEY-----

+ 5 - 124
Tests/AFHTTPClientTests.m → Tests/Tests/1.0 Tests/AFHTTPClientTests.m

@@ -22,116 +22,20 @@
 
 #import "AFNetworkingTests.h"
 
-@interface AFBufferedInputStreamProvider : NSObject <NSStreamDelegate>
-@property (nonatomic, strong) NSData *data;
-@property (nonatomic, strong) NSInputStream *inputStream;
-@property (nonatomic, strong) NSOutputStream *outputStream;
-@property (nonatomic, readonly) NSUInteger bytesWritten;
-
-- (id)initWithData:(NSData *)data;
-@end
-
-@implementation AFBufferedInputStreamProvider
-
-- (id)initWithData:(NSData *)data {
-    self = [super init];
-    if (!self) {
-        return nil;
-    }
-
-    self.data = data;
-
-    CFReadStreamRef readStream;
-    CFWriteStreamRef writeStream;
-    CFStreamCreateBoundPair(NULL, &readStream, &writeStream, 16);
-    
-    self.inputStream = CFBridgingRelease(readStream);
-    
-    self.outputStream = CFBridgingRelease(writeStream);
-    self.outputStream.delegate = self;
-    [self.outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
-    
-    [self.outputStream open];
-
-    return self;
-}
-
-- (void)dealloc {
-    [self cleanup];
-}
-
-- (void)cleanup {
-    [self.outputStream close];
-    self.outputStream.delegate = nil;
-    [self.outputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
-    _outputStream = nil;
-
-    [self.inputStream close];
-    _inputStream = nil;
-}
-
-- (void)writeBytesIfPossible {
-    while ([self.outputStream hasSpaceAvailable] && self.bytesWritten < [self.data length]) {
-        const uint8_t *bytes = [self.data bytes];
-        NSInteger bytesWritten = [self.outputStream write:bytes maxLength:[self.data length] - self.bytesWritten];
-
-        if (bytesWritten < 0) {
-            [self cleanup];
-            return;
-        }
-
-        _bytesWritten += bytesWritten;
-    }
-
-    if (self.bytesWritten >= [self.data length]) {
-        [self cleanup];
-    }
-}
-
-#pragma mark - NSStreamDelegate
-
-- (void)stream:(NSStream *)stream
-   handleEvent:(NSStreamEvent)eventCode
-{
-    if (stream == self.outputStream && (eventCode & NSStreamEventHasSpaceAvailable)) {
-        [self writeBytesIfPossible];
-    } else if (eventCode & NSStreamEventErrorOccurred || eventCode & NSStreamEventEndEncountered) {
-        [self cleanup];
-    }
-}
-
-@end
-
-#pragma mark -
-
 @interface AFHTTPClientTests : SenTestCase
-@property (readwrite, nonatomic, strong) AFHTTPClient *client;
+@property (readwrite, nonatomic, strong) AFHTTPSessionManager *client;
 @end
 
 @implementation AFHTTPClientTests
-@synthesize client = _client;
 
 - (void)setUp {
-    self.client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:AFNetworkingTestsBaseURLString]];
+    self.client = [AFHTTPSessionManager clientWithBaseURL:[NSURL URLWithString:AFNetworkingTestsBaseURLString]];
 }
 
 #pragma mark -
 
 - (void)testInitRaisesException {
-    expect(^{ (void)[[AFHTTPClient alloc] init]; }).to.raiseAny();
-}
-
-- (void)testInitAppendsTerminatingSlashToPath {
-    AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://httpbin.org/test"]];
-    expect([[client baseURL] absoluteString]).to.equal(@"http://httpbin.org/test/");
-}
-
-- (void)testDefaultStringEncoding {
-    expect([[self client] stringEncoding]).to.equal(NSUTF8StringEncoding);
-}
-
-- (void)testDefaultParameterEncoding {
-    expect([[self client] parameterEncoding]).to.equal(AFFormURLParameterEncoding);
+    expect(^{ (void)[[AFHTTPSessionManager alloc] init]; }).to.raiseAny();
 }
 
 - (void)testDefaultHeaders {
@@ -339,15 +243,13 @@
 }
 
 - (void)testPostWithParameters {
-    [Expecta setAsynchronousTestTimeout:5.0];
-
     __block id blockResponseObject = nil;
     [self.client postPath:@"/post" parameters:@{ @"key": @"value" } success:^(AFHTTPRequestOperation *operation, id responseObject) {
         blockResponseObject = responseObject;
     } failure:nil];
 
     expect([self.client.operationQueue operationCount]).will.equal(0);
-    expect(blockResponseObject).willNot.beNil();
+    expect(blockResponseObject).notTo.beNil();
     expect(blockResponseObject).to.beKindOf([NSData class]);
 
     NSError *error = nil;
@@ -419,7 +321,7 @@
 }
 
 - (void)testMultipartUploadDoesNotFailDueToStreamSentAnEventBeforeBeingOpenedError {
-    NSString *pathToImage = [[NSBundle bundleForClass:[AFHTTPClient class]] pathForResource:@"Icon" ofType:@"png"];
+    NSString *pathToImage = [[NSBundle bundleForClass:[AFHTTPSessionManager class]] pathForResource:@"Icon" ofType:@"png"];
     NSData *imageData = [NSData dataWithContentsOfFile:pathToImage];
     NSMutableURLRequest *request = [self.client multipartFormRequestWithMethod:@"POST" path:@"/post" parameters:@{ @"foo": @"bar" } constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
         [formData appendPartWithFileData:imageData name:@"icon[image]" fileName:@"icon.png" mimeType:@"image/png"];
@@ -431,25 +333,4 @@
     expect(operation.error).notTo.equal(NSURLErrorTimedOut);
 }
 
-- (void)testMultipartUploadDoesNotPrematurelyCloseInputStream {
-    NSData *data = [@"ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" dataUsingEncoding:NSUTF8StringEncoding];
-    __block AFBufferedInputStreamProvider *streamProvider = [[AFBufferedInputStreamProvider alloc] initWithData:data];
-    __block NSUInteger bytesWritten = 0;
-    NSInputStream *inputStream = streamProvider.inputStream;
-
-    NSMutableURLRequest *request = [self.client multipartFormRequestWithMethod:@"POST" path:@"/post" parameters:@{ @"foo": @"bar" } constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
-        [formData appendPartWithInputStream:inputStream name:@"data" fileName:@"string.txt" length:[data length] mimeType:@"text/plain"];
-    }];
-    
-    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
-    operation.completionBlock = ^{
-        bytesWritten = streamProvider.bytesWritten;
-        streamProvider = nil;
-    };
-    
-    [self.client enqueueHTTPRequestOperation:operation];
-    expect(operation.isFinished).will.beTruthy();
-    expect(bytesWritten).will.equal([data length]);
-}
-
 @end

+ 0 - 3
Tests/AFHTTPRequestOperationTests.m → Tests/Tests/1.0 Tests/AFHTTPRequestOperationTests.m

@@ -27,7 +27,6 @@
 @end
 
 @implementation AFHTTPRequestOperationTests
-@synthesize baseURL = _baseURL;
 
 - (void)setUp {
     self.baseURL = [NSURL URLWithString:AFNetworkingTestsBaseURLString];
@@ -76,8 +75,6 @@
 }
 
 - (void)testThatCancellationOfRequestOperationInvokesFailureCompletionBlock {
-    [Expecta setAsynchronousTestTimeout:10.0];
-
     __block NSError *blockError = nil;
     
     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/delay/5" relativeToURL:self.baseURL]];

+ 1 - 4
Tests/AFImageRequestOperationTests.m → Tests/Tests/1.0 Tests/AFImageRequestOperationTests.m

@@ -27,7 +27,6 @@
 @end
 
 @implementation AFImageRequestOperationTests
-@synthesize baseURL = _baseURL;
 
 - (void)setUp {
     self.baseURL = [NSURL URLWithString:AFNetworkingTestsBaseURLString];
@@ -105,9 +104,7 @@
 }
 
 - (void)testThatImageResponseIsNotNilWhenRequestSucceeds {
-    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"/image" relativeToURL:self.baseURL]];
-    [request setValue:@"image/png" forHTTPHeaderField:@"Accept"];
-
+    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=image/png" relativeToURL:self.baseURL]];
     AFImageRequestOperation *operation = [[AFImageRequestOperation alloc] initWithRequest:request];
     [operation start];
 

+ 0 - 1
Tests/AFJSONRequestOperationTests.m → Tests/Tests/1.0 Tests/AFJSONRequestOperationTests.m

@@ -27,7 +27,6 @@
 @end
 
 @implementation AFJSONRequestOperationTests
-@synthesize baseURL = _baseURL;
 
 - (void)setUp {
     self.baseURL = [NSURL URLWithString:AFNetworkingTestsBaseURLString];

+ 0 - 0
Tests/AFMockURLProtocol.h → Tests/Tests/1.0 Tests/AFMockURLProtocol.h


+ 0 - 0
Tests/AFMockURLProtocol.m → Tests/Tests/1.0 Tests/AFMockURLProtocol.m


+ 1 - 0
Tests/AFNetworkingTests.h → Tests/Tests/1.0 Tests/AFNetworkingTests.h

@@ -30,4 +30,5 @@
 extern NSString * const AFNetworkingTestsBaseURLString;
 
 @interface AFNetworkingTests : NSObject
+
 @end

+ 0 - 0
Tests/AFNetworkingTests.m → Tests/Tests/1.0 Tests/AFNetworkingTests.m


+ 0 - 1
Tests/AFURLConnectionOperationTests.m → Tests/Tests/1.0 Tests/AFURLConnectionOperationTests.m

@@ -29,7 +29,6 @@
 @end
 
 @implementation AFURLConnectionOperationTests
-@synthesize baseURL = _baseURL;
 
 - (void)setUp {
     self.baseURL = [NSURL URLWithString:AFNetworkingTestsBaseURLString];

+ 278 - 0
Tests/Tests/AFHTTPRequestOperationTests.m

@@ -0,0 +1,278 @@
+// AFHTTPRequestOperationTests.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 "AFTestCase.h"
+
+#import "AFHTTPRequestOperation.h"
+
+@interface AFHTTPRequestOperationTests : AFTestCase
+@end
+
+@implementation AFHTTPRequestOperationTests
+
+- (void)testThatOperationInvokesSuccessCompletionBlockWithResponseObjectOnSuccess {
+    __block id blockResponseObject = nil;
+    
+    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/get" relativeToURL:self.baseURL]];
+    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
+    
+    // AFHTTPOperation currently does not have a default response serializer
+    [operation setResponseSerializer:[AFHTTPResponseSerializer serializer]];
+    
+    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
+        blockResponseObject = responseObject;
+    } failure:nil];
+    
+    [operation start];
+
+    expect([operation isFinished]).will.beTruthy();
+    expect(blockResponseObject).willNot.beNil();
+}
+
+- (void)testThatOperationInvokesFailureCompletionBlockWithErrorOnFailure {
+    __block NSError *blockError = nil;
+    
+    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/status/404" relativeToURL:self.baseURL]];
+    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
+    
+    // AFHTTPOperation currently does not have a default response serializer
+    [operation setResponseSerializer:[AFHTTPResponseSerializer serializer]];
+    
+    [operation setCompletionBlockWithSuccess:nil failure:^(AFHTTPRequestOperation *operation, NSError *error) {
+        blockError = error;
+    }];
+    
+    [operation start];
+    expect([operation isFinished]).will.beTruthy();
+    expect(blockError).willNot.beNil();
+}
+
+- (void)testThatCancellationOfRequestOperationSetsError {
+    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/delay/5" relativeToURL:self.baseURL]];
+    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
+    
+    // AFHTTPOperation currently does not have a default response serializer
+    [operation setResponseSerializer:[AFHTTPResponseSerializer serializer]];
+    
+    [operation start];
+    expect([operation isExecuting]).will.beTruthy();
+    
+    [operation cancel];
+    expect(operation.error).willNot.beNil();
+    expect(operation.error.code).to.equal(NSURLErrorCancelled);
+}
+
+- (void)testThatCancellationOfRequestOperationInvokesFailureCompletionBlock {
+    __block NSError *blockError = nil;
+    
+    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/delay/5" relativeToURL:self.baseURL]];
+    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
+    
+    // AFHTTPOperation currently does not have a default response serializer
+    [operation setResponseSerializer:[AFHTTPResponseSerializer serializer]];
+    
+    [operation setCompletionBlockWithSuccess:nil failure:^(AFHTTPRequestOperation *operation, NSError *error) {
+        blockError = error;
+    }];
+    
+    [operation start];
+    expect([operation isExecuting]).will.beTruthy();
+    
+    [operation cancel];
+    expect(operation.error).willNot.beNil();
+    expect(blockError).willNot.beNil();
+    expect(blockError.code).will.equal(NSURLErrorCancelled);
+}
+
+- (void)testThat500StatusCodeInvokesFailureCompletionBlockWithErrorOnFailure {
+    __block NSError *blockError = nil;
+    
+    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/status/500" relativeToURL:self.baseURL]];
+    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
+    
+    // AFHTTPOperation currently does not have a default response serializer
+    [operation setResponseSerializer:[AFHTTPResponseSerializer serializer]];
+    
+    [operation setCompletionBlockWithSuccess:nil failure:^(AFHTTPRequestOperation *operation, NSError *error) {
+        blockError = error;
+    }];
+    
+    [operation start];
+    expect([operation isFinished]).will.beTruthy();
+    expect(blockError).willNot.beNil();
+}
+
+- (void)testThatRedirectBlockIsCalledWhen302IsEncountered {
+    __block BOOL success;
+    
+    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/redirect/1" relativeToURL:self.baseURL]];
+    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
+    
+    // AFHTTPOperation currently does not have a default response serializer
+    [operation setResponseSerializer:[AFHTTPResponseSerializer serializer]];
+    
+    [operation setCompletionBlockWithSuccess:nil failure:nil];
+    [operation setRedirectResponseBlock:^NSURLRequest *(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse) {
+        if(redirectResponse){
+            success = YES;
+        }
+        
+        return request;
+    }];
+    
+    [operation start];
+    expect([operation isFinished]).will.beTruthy();
+    expect(success).will.beTruthy();
+}
+
+- (void)testThatRedirectBlockIsCalledMultipleTimesWhenMultiple302sAreEncountered {
+    [Expecta setAsynchronousTestTimeout:5.0];
+    __block NSInteger numberOfRedirects = 0;
+    
+    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/redirect/5" relativeToURL:self.baseURL]];
+    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
+    
+    // AFHTTPOperation currently does not have a default response serializer
+    [operation setResponseSerializer:[AFHTTPResponseSerializer serializer]];
+    
+    [operation setCompletionBlockWithSuccess:nil failure:nil];
+    [operation setRedirectResponseBlock:^NSURLRequest *(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse) {
+        if(redirectResponse){
+            numberOfRedirects++;
+        }
+        
+        return request;
+    }];
+    
+    [operation start];
+    expect([operation isFinished]).will.beTruthy();
+    expect(numberOfRedirects).will.equal(5);
+}
+
+#pragma mark - Pause
+
+- (void)testThatOperationCanBePaused {
+    [Expecta setAsynchronousTestTimeout:3.0];
+    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/delay/1" relativeToURL:self.baseURL]];
+    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
+    
+    // AFHTTPOperation currently does not have a default response serializer
+    [operation setResponseSerializer:[AFHTTPResponseSerializer serializer]];
+    
+    [operation start];
+    expect([operation isExecuting]).will.beTruthy();
+    
+    [operation pause];
+    expect([operation isPaused]).will.beTruthy();
+    [operation cancel];
+}
+
+- (void)testThatPausedOperationCanBeResumed {
+    [Expecta setAsynchronousTestTimeout:3.0];
+    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/delay/1" relativeToURL:self.baseURL]];
+    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
+    
+    // AFHTTPOperation currently does not have a default response serializer
+    [operation setResponseSerializer:[AFHTTPResponseSerializer serializer]];
+    
+    [operation start];
+    expect([operation isExecuting]).will.beTruthy();
+    
+    [operation pause];
+    expect([operation isPaused]).will.beTruthy();
+    
+    [operation resume];
+    expect([operation isExecuting]).will.beTruthy();
+    
+    [operation cancel];
+}
+
+- (void)testThatPausedOperationCanBeCompleted {
+    [Expecta setAsynchronousTestTimeout:3.0];
+    
+    __block id blockResponseObject = nil;
+    
+    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/delay/1" relativeToURL:self.baseURL]];
+    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
+    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
+        blockResponseObject = responseObject;
+    } failure:nil];
+    
+    // AFHTTPOperation currently does not have a default response serializer
+    [operation setResponseSerializer:[AFHTTPResponseSerializer serializer]];
+    
+    [operation start];
+    expect([operation isExecuting]).will.beTruthy();
+    
+    [operation pause];
+    expect([operation isPaused]).will.beTruthy();
+    
+    [operation resume];
+    expect([operation isExecuting]).will.beTruthy();
+    expect([operation isFinished]).will.beTruthy();
+    expect(blockResponseObject).willNot.beNil();
+}
+
+- (void)testThatOperationPostsDidStartNotificationWhenStarted{
+
+    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/get" relativeToURL:self.baseURL]];
+    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
+    
+    __block BOOL notificationFound;
+    
+    id observer = [[NSNotificationCenter defaultCenter] addObserverForName:AFNetworkingOperationDidStartNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
+        if([[[note object] request] isEqual:operation.request]){
+            notificationFound = YES;
+        }
+    }];
+    
+    // AFHTTPOperation currently does not have a default response serializer
+    [operation setResponseSerializer:[AFHTTPResponseSerializer serializer]];
+    
+    [operation start];
+    expect(notificationFound).will.beTruthy();
+    
+    [[NSNotificationCenter defaultCenter] removeObserver:observer];
+}
+
+- (void)testThatOperationPostsDidFinishNotificationWhenFinished {
+    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/get" relativeToURL:self.baseURL]];
+    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
+    
+    __block BOOL notificationFound;
+
+    id observer = [[NSNotificationCenter defaultCenter] addObserverForName:AFNetworkingOperationDidFinishNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
+        if([[[note object] request] isEqual:operation.request]){
+            notificationFound = YES;
+        }
+    }];
+    
+    // AFHTTPOperation currently does not have a default response serializer
+    [operation setResponseSerializer:[AFHTTPResponseSerializer serializer]];
+    
+    [operation start];
+    expect(notificationFound).will.beTruthy();
+    
+    [[NSNotificationCenter defaultCenter] removeObserver:observer];
+}
+
+@end

+ 62 - 0
Tests/Tests/AFHTTPSerializationTests.m

@@ -0,0 +1,62 @@
+// AFHTTPSerializationTests.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 "AFTestCase.h"
+
+#import "AFURLResponseSerialization.h"
+
+@interface AFHTTPSerializationTests : AFTestCase
+@end
+
+@implementation AFHTTPSerializationTests
+
+- (void)testThatAFHTTPResponseSerializationHandlesAll2XXCodes {
+    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
+    [indexSet enumerateIndexesUsingBlock:^(NSUInteger statusCode, BOOL *stop) {
+        NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:statusCode HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/html"}];
+
+        AFHTTPResponseSerializer *serializer = [AFHTTPResponseSerializer serializer];
+        XCTAssert([serializer.acceptableStatusCodes containsIndex:statusCode], @"Status code %d should be acceptable");
+
+        NSError *error = nil;
+        [serializer validateResponse:response data:[@"text" dataUsingEncoding:NSUTF8StringEncoding] error:&error];
+
+        XCTAssertNil(error, @"Error handling status code %d", statusCode);
+    }];
+}
+
+- (void)testThatAFHTTPResponseSerializationFailsAll4XX5XXStatusCodes {
+    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(400, 200)];
+    [indexSet enumerateIndexesUsingBlock:^(NSUInteger statusCode, BOOL *stop) {
+        NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:statusCode HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/html"}];
+
+        AFHTTPResponseSerializer *serializer = [AFHTTPResponseSerializer serializer];
+        XCTAssert(![serializer.acceptableStatusCodes containsIndex:statusCode], @"Status code %d should not be acceptable");
+
+        NSError *error = nil;
+        [serializer validateResponse:response data:[@"text" dataUsingEncoding:NSUTF8StringEncoding] error:&error];
+
+        XCTAssertNotNil(error, @"Did not fail handling status code %d",statusCode);
+    }];
+}
+
+@end

+ 99 - 0
Tests/Tests/AFJSONSerializationTests.m

@@ -0,0 +1,99 @@
+// AFJSONSerializationTests.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 "AFTestCase.h"
+
+#import "AFURLResponseSerialization.h"
+
+static NSData * AFJSONTestData() {
+    return [NSJSONSerialization dataWithJSONObject:@{@"foo": @"bar"} options:0 error:nil];
+}
+
+#pragma mark -
+
+@interface AFJSONSerializationTests : AFTestCase
+@end
+
+@implementation AFJSONSerializationTests
+
+- (void)testThatJSONResponseSerializerAcceptsApplicationJSONMimeType {
+    NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"application/json"}];
+
+    AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];
+    NSError *error = nil;
+    [serializer validateResponse:response data:AFJSONTestData() error:&error];
+
+    XCTAssertNil(error, @"Error handling application/json");
+}
+
+- (void)testThatJSONResponseSerializerAcceptsTextJSONMimeType {
+    NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/json"}];
+
+    AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];
+    NSError *error = nil;
+    [serializer validateResponse:response data:AFJSONTestData()error:&error];
+
+    XCTAssertNil(error, @"Error handling text/json");
+}
+
+- (void)testThatJSONResponseSerializerAcceptsTextJavaScriptMimeType {
+    NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/javascript"}];
+
+    AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];
+    NSError *error = nil;
+    [serializer validateResponse:response data:AFJSONTestData() error:&error];
+
+    XCTAssertNil(error, @"Error handling text/javascript");
+}
+
+- (void)testThatJSONResponseSerializerDoesNotAcceptNonStandardJSONMimeType {
+    NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"nonstandard/json"}];
+
+    AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];
+    NSError *error = nil;
+    [serializer validateResponse:response data:AFJSONTestData() error:&error];
+
+    XCTAssertNotNil(error, @"Error should have been thrown for nonstandard/json");
+}
+
+- (void)testThatJSONResponseSerializerReturnsDictionaryForValidJSONDictionary {
+    NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/json"}];
+
+    AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];
+    NSError *error = nil;
+    id responseObject = [serializer responseObjectForResponse:response data:AFJSONTestData() error:&error];
+
+    XCTAssertNil(error, @"Serialization error should be nil");
+    XCTAssert([responseObject isKindOfClass:[NSDictionary class]], @"Expected response to be a NSDictionary");
+}
+
+- (void)testThatJSONResponseSerializerReturnsErrorForInvalidJSON {
+    NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type":@"text/json"}];
+
+    AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];
+    NSError *error = nil;
+    [serializer responseObjectForResponse:response data:[@"{invalid}" dataUsingEncoding:NSUTF8StringEncoding] error:&error];
+
+    XCTAssertNotNil(error, @"Serialization error should not be nil");
+}
+
+@end

+ 168 - 0
Tests/Tests/AFSecurityPolicyTests.m

@@ -0,0 +1,168 @@
+// AFSecurityPolicyTests.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 "AFTestCase.h"
+
+#import "AFSecurityPolicy.h"
+
+@interface AFSecurityPolicyTests : AFTestCase
+@end
+
+static SecTrustRef AFUTTrustChainForCertsInDirectory(NSString *directoryPath) {
+    NSArray *certFileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:nil];
+    NSMutableArray *certs  = [NSMutableArray arrayWithCapacity:[certFileNames count]];
+    for (NSString *path in certFileNames) {
+        NSData *certData = [NSData dataWithContentsOfFile:[directoryPath stringByAppendingPathComponent:path]];
+        SecCertificateRef cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData));
+        [certs addObject:(__bridge id)(cert)];
+    }
+
+    SecPolicyRef policy = SecPolicyCreateBasicX509();
+    SecTrustRef trust = NULL;
+    SecTrustCreateWithCertificates((__bridge CFTypeRef)(certs), policy, &trust);
+
+    return trust;
+}
+
+static SecTrustRef AFUTHTTPBinOrgServerTrust() {
+    NSString *bundlePath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] bundlePath];
+    NSString *serverCertDirectoryPath = [bundlePath stringByAppendingPathComponent:@"HTTPBinOrgServerTrustChain"];
+
+    return AFUTTrustChainForCertsInDirectory(serverCertDirectoryPath);
+}
+
+static SecTrustRef AFUTADNNetServerTrust() {
+    NSString *bundlePath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] bundlePath];
+    NSString *serverCertDirectoryPath = [bundlePath stringByAppendingPathComponent:@"ADNNetServerTrustChain"];
+
+    return AFUTTrustChainForCertsInDirectory(serverCertDirectoryPath);
+}
+
+static SecCertificateRef AFUTHTTPBinOrgCertificate() {
+    NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"httpbinorg_10242013" ofType:@"cer"];
+    NSCAssert(certPath != nil, @"Path for certificate should not be nil");
+    NSData *certData = [NSData dataWithContentsOfFile:certPath];
+
+    return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData));
+}
+
+#pragma mark -
+
+@implementation AFSecurityPolicyTests
+
+- (void)testPublicKeyPinningIsEnforcedForHTTPBinOrgPinnedCertificateAgainstHTTPBinOrgServerTrust {
+    AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
+    SecCertificateRef certificate = AFUTHTTPBinOrgCertificate();
+    [policy setPinnedCertificates:@[(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]];
+    [policy setSSLPinningMode:AFSSLPinningModePublicKey];
+
+    XCTAssert([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust()], @"HTTPBin.org Public Key Pinning Mode Failed");
+}
+
+- (void)testCertificatePinningIsEnforcedForHTTPBinOrgPinnedCertificateAgainstHTTPBinOrgServerTrust {
+    AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
+    SecCertificateRef certificate = AFUTHTTPBinOrgCertificate();
+    [policy setPinnedCertificates:@[(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]];
+    [policy setSSLPinningMode:AFSSLPinningModeCertificate];
+
+    XCTAssert([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust()], @"HTTPBin.org Public Key Pinning Mode Failed");
+}
+
+- (void)testNoPinningIsEnforcedForHTTPBinOrgPinnedCertificateAgainstHTTPBinOrgServerTrust {
+    AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
+    SecCertificateRef certificate = AFUTHTTPBinOrgCertificate();
+    [policy setPinnedCertificates:@[(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]];
+    [policy setSSLPinningMode:AFSSLPinningModeNone];
+
+    XCTAssert([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust()], @"HTTPBin.org Pinning should not have been enforced");
+}
+
+- (void)testPublicKeyPinningFailsForHTTPBinOrgIfNoCertificateIsPinned {
+    AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
+    [policy setPinnedCertificates:@[]];
+    [policy setSSLPinningMode:AFSSLPinningModePublicKey];
+
+    XCTAssert([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust()] == NO, @"HTTPBin.org Public Key Pinning Should have failed with no pinned certificate");
+}
+
+- (void)testCertificatePinningFailsForHTTPBinOrgIfNoCertificateIsPinned {
+    AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
+    [policy setPinnedCertificates:@[]];
+    [policy setSSLPinningMode:AFSSLPinningModeCertificate];
+
+    XCTAssert([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust()] == NO, @"HTTPBin.org Certificate Pinning Should have failed with no pinned certificate");
+}
+
+- (void)testNoPinningIsEnforcedForHTTPBinOrgIfNoCertificateIsPinned {
+    AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
+    [policy setPinnedCertificates:@[]];
+    [policy setSSLPinningMode:AFSSLPinningModeNone];
+
+    XCTAssert([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust()], @"HTTPBin.org Pinning should not have been enforced");
+}
+
+- (void)testPublicKeyPinningForHTTPBinOrgFailsWhenPinnedAgainstADNServerTrust {
+    AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
+    [policy setPinnedCertificates:@[]];
+    [policy setSSLPinningMode:AFSSLPinningModePublicKey];
+
+    XCTAssert([policy evaluateServerTrust:AFUTADNNetServerTrust()] == NO, @"HTTPBin.org Public Key Pinning Should have failed against ADN");
+}
+
+- (void)testCertificatePinningForHTTPBinOrgFailsWhenPinnedAgainstADNServerTrust {
+    AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
+    [policy setPinnedCertificates:@[]];
+    [policy setSSLPinningMode:AFSSLPinningModeCertificate];
+
+    XCTAssert([policy evaluateServerTrust:AFUTADNNetServerTrust()] == NO, @"HTTPBin.org Certificate Pinning Should have failed against ADN");
+}
+
+- (void)testDefaultPolicyContainsHTTPBinOrgCertificate {
+    AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy];
+    SecCertificateRef cert = AFUTHTTPBinOrgCertificate();
+    NSData *certData = (__bridge NSData *)(SecCertificateCopyData(cert));
+    NSInteger index = [policy.pinnedCertificates indexOfObjectPassingTest:^BOOL(NSData *data, NSUInteger idx, BOOL *stop) {
+        return [data isEqualToData:certData];
+    }];
+
+    XCTAssert(index!=NSNotFound, @"HTTPBin.org certificate not found in the default certificates");
+}
+
+- (void)testDefaultPolicyIsSetToAFSSLPinningModePublicKey {
+    AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy];
+
+    XCTAssert(policy.SSLPinningMode==AFSSLPinningModeNone, @"Default policy is not set to AFSSLPinningModePublicKey.");
+}
+
+- (void)testDefaultPolicyIsSetToNotAllowInvalidSSLCertificates {
+    AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy];
+
+    XCTAssert(policy.allowInvalidCertificates == NO, @"Default policy should not allow invalid ssl certificates");
+}
+
+- (void)testPolicyWithPinningModeIsSetToNotAllowInvalidSSLCertificates {
+    AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
+    
+    XCTAssert(policy.allowInvalidCertificates == NO, @"policyWithPinningMode: should not allow invalid ssl certificates by default.");
+}
+
+@end

+ 35 - 0
Tests/Tests/AFTestCase.h

@@ -0,0 +1,35 @@
+// AFTestCase.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 <XCTest/XCTest.h>
+
+#define EXP_SHORTHAND YES
+#import "Expecta.h"
+#import "OCMock.h"
+
+extern NSString * const AFNetworkingTestsBaseURLString;
+
+@interface AFTestCase : XCTestCase
+
+@property (nonatomic, strong, readonly) NSURL *baseURL;
+
+@end

+ 45 - 0
Tests/Tests/AFTestCase.m

@@ -0,0 +1,45 @@
+// AFTestCase.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 "AFTestCase.h"
+
+NSString * const AFNetworkingTestsBaseURLString = @"https://httpbin.org/";
+
+@implementation AFTestCase
+
+- (void)setUp {
+    [super setUp];
+
+    [Expecta setAsynchronousTestTimeout:5.0];
+}
+
+- (void)tearDown {
+    [super tearDown];
+}
+
+#pragma mark -
+
+- (NSURL *)baseURL {
+    return [NSURL URLWithString:AFNetworkingTestsBaseURLString];
+}
+
+@end

+ 2 - 0
Tests/iOS Tests/en.lproj/InfoPlist.strings

@@ -0,0 +1,2 @@
+/* Localized versions of Info.plist keys */
+

+ 22 - 0
Tests/iOS Tests/iOS Tests-Info.plist

@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>CFBundleDevelopmentRegion</key>
+	<string>en</string>
+	<key>CFBundleExecutable</key>
+	<string>${EXECUTABLE_NAME}</string>
+	<key>CFBundleIdentifier</key>
+	<string>com.alamofire.afnetworking.${PRODUCT_NAME:rfc1034identifier}</string>
+	<key>CFBundleInfoDictionaryVersion</key>
+	<string>6.0</string>
+	<key>CFBundlePackageType</key>
+	<string>BNDL</string>
+	<key>CFBundleShortVersionString</key>
+	<string>1.0</string>
+	<key>CFBundleSignature</key>
+	<string>????</string>
+	<key>CFBundleVersion</key>
+	<string>1</string>
+</dict>
+</plist>

+ 10 - 0
Tests/iOS Tests/iOS Tests-Prefix.pch

@@ -0,0 +1,10 @@
+//
+//  Prefix header
+//
+//  The contents of this file are implicitly included at the beginning of every source file.
+//
+
+#ifdef __OBJC__
+    #import <UIKit/UIKit.h>
+    #import <Foundation/Foundation.h>
+#endif

+ 1 - 1
AFNetworking/AFNetworkActivityIndicatorManager.h → UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h

@@ -1,6 +1,6 @@
 // AFNetworkActivityIndicatorManager.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

+ 25 - 20
AFNetworking/AFNetworkActivityIndicatorManager.m → UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m

@@ -1,6 +1,6 @@
 // AFNetworkActivityIndicatorManager.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
@@ -23,10 +23,22 @@
 #import "AFNetworkActivityIndicatorManager.h"
 
 #import "AFHTTPRequestOperation.h"
+#import "AFURLSessionManager.h"
 
 #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
 static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17;
 
+static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) {
+    NSURLRequest *request = nil;
+    if ([[notification object] isKindOfClass:[AFURLConnectionOperation class]]) {
+        request = [(AFURLConnectionOperation *)[notification object] request];
+    } else if ([[notification object] respondsToSelector:@selector(originalRequest)]) {
+        request = [(NSURLSessionTask *)[notification object] originalRequest];
+    }
+
+    return request;
+}
+
 @interface AFNetworkActivityIndicatorManager ()
 @property (readwrite, nonatomic, assign) NSInteger activityCount;
 @property (readwrite, nonatomic, strong) NSTimer *activityIndicatorVisibilityTimer;
@@ -37,9 +49,6 @@ static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17;
 @end
 
 @implementation AFNetworkActivityIndicatorManager
-@synthesize activityCount = _activityCount;
-@synthesize activityIndicatorVisibilityTimer = _activityIndicatorVisibilityTimer;
-@synthesize enabled = _enabled;
 @dynamic networkActivityIndicatorVisible;
 
 + (instancetype)sharedManager {
@@ -62,8 +71,12 @@ static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17;
         return nil;
     }
 
-    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkingOperationDidStart:) name:AFNetworkingOperationDidStartNotification object:nil];
-    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkingOperationDidFinish:) name:AFNetworkingOperationDidFinishNotification object:nil];
+    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingOperationDidStartNotification object:nil];
+    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingOperationDidFinishNotification object:nil];
+
+    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidStartNotification object:nil];
+    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil];
+    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidFinishNotification object:nil];
 
     return self;
 }
@@ -72,7 +85,6 @@ static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17;
     [[NSNotificationCenter defaultCenter] removeObserver:self];
 
     [_activityIndicatorVisibilityTimer invalidate];
-
 }
 
 - (void)updateNetworkActivityIndicatorVisibilityDelayed {
@@ -83,24 +95,19 @@ static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17;
             self.activityIndicatorVisibilityTimer = [NSTimer timerWithTimeInterval:kAFNetworkActivityIndicatorInvisibilityDelay target:self selector:@selector(updateNetworkActivityIndicatorVisibility) userInfo:nil repeats:NO];
             [[NSRunLoop mainRunLoop] addTimer:self.activityIndicatorVisibilityTimer forMode:NSRunLoopCommonModes];
         } else {
-            [self performSelectorOnMainThread:@selector(updateNetworkActivityIndicatorVisibility) withObject:nil waitUntilDone:NO modes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
+            [self performSelectorOnMainThread:@selector(updateNetworkActivityIndicatorVisibility) withObject:nil waitUntilDone:NO modes:@[NSRunLoopCommonModes]];
         }
     }
 }
 
 - (BOOL)isNetworkActivityIndicatorVisible {
-    return _activityCount > 0;
+    return self.activityCount > 0;
 }
 
 - (void)updateNetworkActivityIndicatorVisibility {
     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:[self isNetworkActivityIndicatorVisible]];
 }
 
-// Not exposed, but used if activityCount is set via KVC.
-- (NSInteger)activityCount {
-	return _activityCount;
-}
-
 - (void)setActivityCount:(NSInteger)activityCount {
 	@synchronized(self) {
 		_activityCount = activityCount;
@@ -138,16 +145,14 @@ static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17;
     });
 }
 
-- (void)networkingOperationDidStart:(NSNotification *)notification {
-    AFURLConnectionOperation *connectionOperation = [notification object];
-    if (connectionOperation.request.URL) {
+- (void)networkRequestDidStart:(NSNotification *)notification {
+    if ([AFNetworkRequestFromNotification(notification) URL]) {
         [self incrementActivityCount];
     }
 }
 
-- (void)networkingOperationDidFinish:(NSNotification *)notification {
-    AFURLConnectionOperation *connectionOperation = [notification object];
-    if (connectionOperation.request.URL) {
+- (void)networkRequestDidFinish:(NSNotification *)notification {
+    if ([AFNetworkRequestFromNotification(notification) URL]) {
         [self decrementActivityCount];
     }
 }

+ 44 - 0
UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h

@@ -0,0 +1,44 @@
+// UIActivityIndicatorView+AFNetworking.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 <UIKit/UIKit.h>
+
+@class AFURLConnectionOperation;
+
+/**
+ 
+ */
+@interface UIActivityIndicatorView (AFNetworking)
+
+/**
+ 
+ */
+- (void)setAnimatingWithStateOfOperation:(AFURLConnectionOperation *)operation;
+
+///
+
+/**
+ 
+ */
+- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task;
+
+@end

+ 68 - 0
UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m

@@ -0,0 +1,68 @@
+// UIActivityIndicatorView+AFNetworking.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 "UIActivityIndicatorView+AFNetworking.h"
+
+#import "AFURLConnectionOperation.h"
+#import "AFURLSessionManager.h"
+
+@implementation UIActivityIndicatorView (AFNetworking)
+
+- (void)setAnimatingWithStateOfOperation:(AFURLConnectionOperation *)operation {
+    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
+
+    [notificationCenter removeObserver:self name:AFNetworkingOperationDidStartNotification object:nil];
+    [notificationCenter removeObserver:self name:AFNetworkingOperationDidFinishNotification object:nil];
+
+    if (![operation isFinished]) {
+        if ([operation isExecuting]) {
+            [self startAnimating];
+        } else {
+            [self stopAnimating];
+        }
+
+        [notificationCenter addObserver:self selector:@selector(startAnimating) name:AFNetworkingOperationDidStartNotification object:operation];
+        [notificationCenter addObserver:self selector:@selector(stopAnimating) name:AFNetworkingOperationDidFinishNotification object:operation];
+    }
+}
+
+- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task {
+    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
+
+    [notificationCenter removeObserver:self name:AFNetworkingTaskDidStartNotification object:nil];
+    [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
+    [notificationCenter removeObserver:self name:AFNetworkingTaskDidFinishNotification object:nil];
+
+    if (task.state != NSURLSessionTaskStateCompleted) {
+        if (task.state == NSURLSessionTaskStateRunning) {
+            [self startAnimating];
+        } else {
+            [self stopAnimating];
+        }
+
+        [notificationCenter addObserver:self selector:@selector(startAnimating) name:AFNetworkingTaskDidStartNotification object:task];
+        [notificationCenter addObserver:self selector:@selector(stopAnimating) name:AFNetworkingTaskDidFinishNotification object:task];
+        [notificationCenter addObserver:self selector:@selector(stopAnimating) name:AFNetworkingTaskDidSuspendNotification object:task];
+    }
+}
+
+@end

+ 70 - 0
UIKit+AFNetworking/UIAlertView+AFNetworking.h

@@ -0,0 +1,70 @@
+// UIAlertView+AFNetworking.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 <UIKit/UIKit.h>
+
+#import "AFURLConnectionOperation.h"
+#import "AFURLSessionManager.h"
+
+/**
+ 
+ */
+@interface UIAlertView (AFNetworking)
+
+///-------------------------------------
+/// @name Showing Alert for Session Task
+///-------------------------------------
+
+/**
+
+ */
++ (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task
+                                         delegate:(id /*<UIAlertViewDelegate>*/)delegate;
+
+/**
+ 
+ */
++ (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task
+                                         delegate:(id /*<UIAlertViewDelegate>*/)delegate
+                                cancelButtonTitle:(NSString *)cancelButtonTitle
+                                otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION;
+
+
+///------------------------------------------
+/// @name Showing Alert for Request Operation
+///------------------------------------------
+
+/**
+ 
+ */
++ (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation
+                                                     delegate:(id /*<UIAlertViewDelegate>*/)delegate;
+
+/**
+ 
+ */
++ (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation
+                                                     delegate:(id /*<UIAlertViewDelegate>*/)delegate
+                                            cancelButtonTitle:(NSString *)cancelButtonTitle
+                                            otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION;
+
+@end

+ 99 - 0
UIKit+AFNetworking/UIAlertView+AFNetworking.m

@@ -0,0 +1,99 @@
+// UIAlertView+AFNetworking.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 "UIAlertView+AFNetworking.h"
+
+static void AFGetAlertViewTitleAndMessageFromError(NSError *error, NSString * __autoreleasing *title, NSString * __autoreleasing *message) {
+    if (error.localizedDescription && (error.localizedRecoverySuggestion || error.localizedFailureReason)) {
+        *title = error.localizedDescription;
+
+        if (error.localizedRecoverySuggestion) {
+            *message = error.localizedRecoverySuggestion;
+        } else {
+            *message = error.localizedFailureReason;
+        }
+    } else if (error.localizedDescription) {
+        *title = NSLocalizedStringFromTable(@"Error", @"AFNetworking", @"Fallback Error Description");
+        *message = error.localizedDescription;
+    } else {
+        *title = NSLocalizedStringFromTable(@"Error", @"AFNetworking", @"Fallback Error Description");
+        *message = [NSString stringWithFormat:NSLocalizedStringFromTable(@"%@ Error: %d", @"AFNetworking", @"Fallback Error Failure Reason Format"), error.domain, error.code];
+    }
+}
+
+@implementation UIAlertView (AFNetworking)
+
++ (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task
+                                         delegate:(id /*<UIAlertViewDelegate>*/)delegate
+{
+    [self showAlertViewForTaskWithErrorOnCompletion:task delegate:delegate cancelButtonTitle:NSLocalizedStringFromTable(@"Dismiss", @"AFNetworking", @"UIAlertView Cancel Button Title") otherButtonTitles:nil, nil];
+}
+
++ (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task
+                                         delegate:(id /*<UIAlertViewDelegate>*/)delegate
+                                cancelButtonTitle:(NSString *)cancelButtonTitle
+                                otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION
+{
+    __block id observer = [[NSNotificationCenter defaultCenter] addObserverForName:AFNetworkingTaskDidFinishNotification object:task queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) {
+
+        NSError *error = notification.userInfo[AFNetworkingTaskDidFinishErrorKey];
+        if (error) {
+            NSString *title, *message;
+            AFGetAlertViewTitleAndMessageFromError(error, &title, &message);
+
+            [[[UIAlertView alloc] initWithTitle:title message:message delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil] show];
+        }
+
+        [[NSNotificationCenter defaultCenter] removeObserver:observer name:AFNetworkingTaskDidFinishNotification object:notification.object];
+    }];
+}
+
+#pragma mark -
+
++ (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation
+                                                     delegate:(id /*<UIAlertViewDelegate>*/)delegate
+{
+    [self showAlertViewForRequestOperationWithErrorOnCompletion:operation delegate:delegate cancelButtonTitle:NSLocalizedStringFromTable(@"Dismiss", @"AFNetworking", @"UIAlert View Cancel Button Title") otherButtonTitles:nil, nil];
+}
+
++ (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation
+                                                     delegate:(id /*<UIAlertViewDelegate>*/)delegate
+                                            cancelButtonTitle:(NSString *)cancelButtonTitle
+                                            otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION
+{
+    __block id observer = [[NSNotificationCenter defaultCenter] addObserverForName:AFNetworkingOperationDidFinishNotification object:operation queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) {
+
+        if (notification.object && [notification.object isKindOfClass:[AFURLConnectionOperation class]]) {
+            NSError *error = [(AFURLConnectionOperation *)notification.object error];
+            if (error) {
+                NSString *title, *message;
+                AFGetAlertViewTitleAndMessageFromError(error, &title, &message);
+
+                [[[UIAlertView alloc] initWithTitle:title message:message delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil] show];
+            }
+        }
+
+        [[NSNotificationCenter defaultCenter] removeObserver:observer name:AFNetworkingTaskDidFinishNotification object:notification.object];
+    }];
+}
+
+@end

+ 100 - 0
UIKit+AFNetworking/UIButton+AFNetworking.h

@@ -0,0 +1,100 @@
+// UIButton+AFNetworking.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 <Availability.h>
+
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+#import <UIKit/UIKit.h>
+
+/**
+ 
+ */
+@interface UIButton (AFNetworking)
+
+///--------------------
+/// @name Setting Image
+///--------------------
+
+/**
+ 
+ */
+- (void)setImageForState:(UIControlState)state
+                 withURL:(NSURL *)url;
+
+/**
+ 
+ */
+- (void)setImageForState:(UIControlState)state
+                 withURL:(NSURL *)url
+        placeholderImage:(UIImage *)placeholderImage;
+
+/**
+ 
+ */
+- (void)setImageForState:(UIControlState)state
+          withURLRequest:(NSURLRequest *)urlRequest
+        placeholderImage:(UIImage *)placeholderImage
+                 success:(void (^)(NSHTTPURLResponse *response, UIImage *image))success
+                 failure:(void (^)(NSError *error))failure;
+
+
+///-------------------------------
+/// @name Setting Background Image
+///-------------------------------
+
+/**
+ 
+ */
+- (void)setBackgroundImageForState:(UIControlState)state
+                           withURL:(NSURL *)url;
+
+/**
+ 
+ */
+- (void)setBackgroundImageForState:(UIControlState)state
+                           withURL:(NSURL *)url
+                  placeholderImage:(UIImage *)image;
+
+/**
+ 
+ */
+- (void)setBackgroundImageForState:(UIControlState)state
+                    withURLRequest:(NSURLRequest *)urlRequest
+                  placeholderImage:(UIImage *)placeholderImage
+                           success:(void (^)(NSHTTPURLResponse *response, UIImage *image))success
+                           failure:(void (^)(NSError *error))failure;
+
+
+///-------------------------------
+/// @name Cancelling Image Loading
+///-------------------------------
+
+/**
+ 
+ */
+- (void)cancelImageDataTasks;
+
+@end
+
+#endif

+ 134 - 0
UIKit+AFNetworking/UIButton+AFNetworking.m

@@ -0,0 +1,134 @@
+// UIButton+AFNetworking.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 <objc/message.h>
+
+#import "AFHTTPRequestOperation.h"
+#import "AFHTTPSessionManager.h"
+
+#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+#import "UIButton+AFNetworking.h"
+
+@implementation UIButton (AFNetworking)
+
++ (AFHTTPSessionManager *)af_sharedHTTPClient {
+    static AFHTTPSessionManager *_af_sharedHTTPClient = nil;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        _af_sharedHTTPClient = [[AFHTTPSessionManager alloc] init];
+        _af_sharedHTTPClient.responseSerializer = [AFImageResponseSerializer serializer];
+    });
+
+    return _af_sharedHTTPClient;
+}
+
+#pragma mark -
+
+- (void)setImageForState:(UIControlState)state
+                 withURL:(NSURL *)url
+{
+    [self setImageForState:state withURL:url placeholderImage:nil];
+}
+
+- (void)setImageForState:(UIControlState)state
+                 withURL:(NSURL *)url
+        placeholderImage:(UIImage *)placeholderImage
+{
+    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
+    [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
+
+    [self setImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
+}
+
+- (void)setImageForState:(UIControlState)state
+          withURLRequest:(NSURLRequest *)urlRequest
+        placeholderImage:(UIImage *)placeholderImage
+                 success:(void (^)(NSHTTPURLResponse *response, UIImage *image))success
+                 failure:(void (^)(NSError *error))failure
+{
+    [self setImageWithSelector:@selector(setImage:forState:) forState:state withURLRequest:urlRequest placeholderImage:placeholderImage success:success failure:failure];
+}
+
+#pragma mark -
+
+- (void)setBackgroundImageForState:(UIControlState)state
+                           withURL:(NSURL *)url
+{
+    [self setBackgroundImageForState:state withURL:url placeholderImage:nil];
+}
+
+- (void)setBackgroundImageForState:(UIControlState)state
+                           withURL:(NSURL *)url
+                  placeholderImage:(UIImage *)placeholderImage
+{
+    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
+    [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
+
+    [self setBackgroundImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
+}
+
+- (void)setBackgroundImageForState:(UIControlState)state
+                    withURLRequest:(NSURLRequest *)urlRequest
+                  placeholderImage:(UIImage *)placeholderImage
+                           success:(void (^)(NSHTTPURLResponse *response, UIImage *image))success
+                           failure:(void (^)(NSError *error))failure
+{
+    [self setImageWithSelector:@selector(setBackgroundImage:forState:) forState:state withURLRequest:urlRequest placeholderImage:placeholderImage success:success failure:failure];
+}
+
+#pragma mark -
+
+- (void)setImageWithSelector:(SEL)selector
+                    forState:(UIControlState)state
+              withURLRequest:(NSURLRequest *)urlRequest
+            placeholderImage:(UIImage *)placeholderImage
+                     success:(void (^)(NSHTTPURLResponse *response, UIImage *image))success
+                     failure:(void (^)(NSError *error))failure
+{
+    void (*objc_msgSend_typed)(id, SEL, UIImage *, UIControlState) = (void *)objc_msgSend;
+    objc_msgSend_typed(self, selector, placeholderImage, state);
+
+    NSURLSessionTask *task = [[[self class] af_sharedHTTPClient] dataTaskWithRequest:urlRequest completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
+        if (error) {
+            if (failure) {
+                failure(error);
+            }
+        } else {
+            if (success) {
+                success((NSHTTPURLResponse *)response, responseObject);
+            } else if (responseObject) {
+                objc_msgSend_typed(self, selector, responseObject, state);
+            }
+        }
+    }];
+
+    [task resume];
+}
+
+- (void)cancelImageDataTasks {
+    [[[[self class] af_sharedHTTPClient] tasks] makeObjectsPerformSelector:@selector(cancel)];
+}
+
+@end
+
+#endif

+ 12 - 2
AFNetworking/UIImageView+AFNetworking.h → UIKit+AFNetworking/UIImageView+AFNetworking.h

@@ -1,6 +1,6 @@
 // UIImageView+AFNetworking.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
@@ -21,18 +21,28 @@
 // THE SOFTWARE.
 
 #import <Foundation/Foundation.h>
-#import "AFImageRequestOperation.h"
 
 #import <Availability.h>
 
 #if __IPHONE_OS_VERSION_MIN_REQUIRED
 #import <UIKit/UIKit.h>
 
+#import "AFURLResponseSerialization.h"
+#import "AFSecurityPolicy.h"
+
 /**
  This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL.
  */
 @interface UIImageView (AFNetworking)
 
+/**
+ The response serializer used to create an image representation from the server response and response data. By default, this is an instance of `AFImageResponseSerializer`.
+ 
+ @discussion Subclasses of `AFImageResponseSerializer` could be used to perform post-processing, such as color correction, face detection, or other effects. See https://github.com/AFNetworking/AFCoreImageSerializer
+ */
+@property (nonatomic, strong) AFImageResponseSerializer <AFURLResponseSerialization> * imageResponseSerializer;
+
+
 /**
  Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL, and sets it the request is finished. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
 

+ 55 - 45
AFNetworking/UIImageView+AFNetworking.m → UIKit+AFNetworking/UIImageView+AFNetworking.m

@@ -1,6 +1,6 @@
 // UIImageView+AFNetworking.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
@@ -23,6 +23,9 @@
 #import <Foundation/Foundation.h>
 #import <objc/runtime.h>
 
+#import "AFHTTPRequestOperation.h"
+#import "AFHTTPSessionManager.h"
+
 #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
 #import "UIImageView+AFNetworking.h"
 
@@ -34,10 +37,11 @@
 
 #pragma mark -
 
-static char kAFImageRequestOperationObjectKey;
+static char kAFImageRequestOperationKey;
+static char kAFResponseSerializerKey;
 
 @interface UIImageView (_AFNetworking)
-@property (readwrite, nonatomic, strong, setter = af_setImageRequestOperation:) AFImageRequestOperation *af_imageRequestOperation;
+@property (readwrite, nonatomic, strong, setter = af_setImageRequestOperation:) AFHTTPRequestOperation *af_imageRequestOperation;
 @end
 
 @implementation UIImageView (_AFNetworking)
@@ -47,24 +51,17 @@ static char kAFImageRequestOperationObjectKey;
 #pragma mark -
 
 @implementation UIImageView (AFNetworking)
-
-- (AFHTTPRequestOperation *)af_imageRequestOperation {
-    return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, &kAFImageRequestOperationObjectKey);
-}
-
-- (void)af_setImageRequestOperation:(AFImageRequestOperation *)imageRequestOperation {
-    objc_setAssociatedObject(self, &kAFImageRequestOperationObjectKey, imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
-}
+@dynamic imageResponseSerializer;
 
 + (NSOperationQueue *)af_sharedImageRequestOperationQueue {
-    static NSOperationQueue *_af_imageRequestOperationQueue = nil;
+    static NSOperationQueue *_af_sharedImageRequestOperationQueue = nil;
     static dispatch_once_t onceToken;
     dispatch_once(&onceToken, ^{
-        _af_imageRequestOperationQueue = [[NSOperationQueue alloc] init];
-        [_af_imageRequestOperationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
+        _af_sharedImageRequestOperationQueue = [[NSOperationQueue alloc] init];
+        _af_sharedImageRequestOperationQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount;
     });
 
-    return _af_imageRequestOperationQueue;
+    return _af_sharedImageRequestOperationQueue;
 }
 
 + (AFImageCache *)af_sharedImageCache {
@@ -72,11 +69,37 @@ static char kAFImageRequestOperationObjectKey;
     static dispatch_once_t oncePredicate;
     dispatch_once(&oncePredicate, ^{
         _af_imageCache = [[AFImageCache alloc] init];
+
+        [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidReceiveMemoryWarningNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
+            [_af_imageCache removeAllObjects];
+        }];
     });
 
     return _af_imageCache;
 }
 
+- (AFHTTPRequestOperation *)af_imageRequestOperation {
+    return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, &kAFImageRequestOperationKey);
+}
+
+- (void)af_setImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation {
+    objc_setAssociatedObject(self, &kAFImageRequestOperationKey, imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+- (id <AFURLResponseSerialization>)imageResponseSerializer {
+    static id <AFURLResponseSerialization> _af_defaultImageResponseSerializer = nil;
+    static dispatch_once_t onceToken;
+    dispatch_once(&onceToken, ^{
+        _af_defaultImageResponseSerializer = [AFImageResponseSerializer serializer];
+    });
+
+    return objc_getAssociatedObject(self, &kAFResponseSerializerKey) ?: _af_defaultImageResponseSerializer;
+}
+
+- (void)setImageResponseSerializer:(id <AFURLResponseSerialization>)serializer {
+    objc_setAssociatedObject(self, &kAFResponseSerializerKey, serializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
 #pragma mark -
 
 - (void)setImageWithURL:(NSURL *)url {
@@ -101,52 +124,39 @@ static char kAFImageRequestOperationObjectKey;
 
     UIImage *cachedImage = [[[self class] af_sharedImageCache] cachedImageForRequest:urlRequest];
     if (cachedImage) {
-        self.af_imageRequestOperation = nil;
-
         if (success) {
             success(nil, nil, cachedImage);
         } else {
             self.image = cachedImage;
         }
-    } else {
-        if (placeholderImage) {
-            self.image = placeholderImage;
-        }
-
-        AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest];
-		
-#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
-		requestOperation.allowsInvalidSSLCertificate = YES;
-#endif
-		
-        [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
-            if ([urlRequest isEqual:[self.af_imageRequestOperation request]]) {
-                if (self.af_imageRequestOperation == operation) {
-                    self.af_imageRequestOperation = nil;
-                }
 
+        self.af_imageRequestOperation = nil;
+    } else {
+        self.image = placeholderImage;
+
+        __weak __typeof(self)weakSelf = self;
+        self.af_imageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
+        self.af_imageRequestOperation.responseSerializer = self.imageResponseSerializer;
+        [self.af_imageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
+            __strong __typeof(weakSelf)strongSelf = weakSelf;
+            if ([[urlRequest URL] isEqual:[operation.request URL]]) {
                 if (success) {
-                    success(operation.request, operation.response, responseObject);
+                    success(urlRequest, operation.response, responseObject);
                 } else if (responseObject) {
-                    self.image = responseObject;
+                    strongSelf.image = responseObject;
                 }
+            } else {
+                
             }
 
-            [[[self class] af_sharedImageCache] cacheImage:responseObject forRequest:urlRequest];
+            [[[strongSelf class] af_sharedImageCache] cacheImage:responseObject forRequest:urlRequest];
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
-            if ([urlRequest isEqual:[self.af_imageRequestOperation request]]) {
-                if (self.af_imageRequestOperation == operation) {
-                    self.af_imageRequestOperation = nil;
-                }
-
+            if ([[urlRequest URL] isEqual:[operation.response URL]]) {
                 if (failure) {
-                    failure(operation.request, operation.response, error);
+                    failure(urlRequest, operation.response, error);
                 }
             }
         }];
-
-        self.af_imageRequestOperation = requestOperation;
-
         [[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation];
     }
 }

+ 60 - 0
UIKit+AFNetworking/UIProgressView+AFNetworking.h

@@ -0,0 +1,60 @@
+// UIProgressView+AFNetworking.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 <UIKit/UIKit.h>
+
+@class AFURLConnectionOperation;
+
+/**
+ 
+ */
+@interface UIProgressView (AFNetworking)
+
+///
+
+/**
+ 
+ */
+- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task
+                                   animated:(BOOL)animated;
+
+/**
+ 
+ */
+- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task
+                                     animated:(BOOL)animated;
+
+///
+
+/**
+ 
+ */
+- (void)setProgressWithUploadProgressOfOperation:(AFURLConnectionOperation *)operation
+                                        animated:(BOOL)animated;
+
+/**
+ 
+ */
+- (void)setProgressWithDownloadProgressOfOperation:(AFURLConnectionOperation *)operation
+                                          animated:(BOOL)animated;
+
+@end

+ 134 - 0
UIKit+AFNetworking/UIProgressView+AFNetworking.m

@@ -0,0 +1,134 @@
+// UIProgressView+AFNetworking.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 "UIProgressView+AFNetworking.h"
+
+#import "AFURLConnectionOperation.h"
+
+static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext;
+static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext;
+
+@interface AFURLConnectionOperation (_UIProgressView)
+@property (readwrite, nonatomic, copy) void (^uploadProgress)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected);
+@property (readwrite, nonatomic, copy) void (^downloadProgress)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected);
+@end
+
+@implementation AFURLConnectionOperation (_UIProgressView)
+@dynamic uploadProgress;
+@dynamic downloadProgress;
+@end
+
+#pragma mark -
+
+@interface UIProgressView (_AFNetworking) <NSURLSessionDownloadDelegate>
+- (void)_af_observeValueForKeyPath:(NSString *)keyPath
+                          ofObject:(id)object
+                            change:(NSDictionary *)change
+                           context:(void *)context;
+@end
+
+@implementation UIProgressView (AFNetworking)
+
+- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task
+                                   animated:(BOOL)animated
+{
+    [task addObserver:self forKeyPath:@"state" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:AFTaskCountOfBytesSentContext];
+    [task addObserver:self forKeyPath:@"countOfBytesSent" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:AFTaskCountOfBytesSentContext];
+}
+
+- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task
+                                     animated:(BOOL)animated
+{
+    [task addObserver:self forKeyPath:@"state" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:AFTaskCountOfBytesReceivedContext];
+    [task addObserver:self forKeyPath:@"countOfBytesReceived" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:AFTaskCountOfBytesReceivedContext];
+}
+
+#pragma mark -
+
+- (void)setProgressWithUploadProgressOfOperation:(AFURLConnectionOperation *)operation
+                                        animated:(BOOL)animated
+{
+    __weak __typeof(self)weakSelf = self;
+    void (^original)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected) = [operation.uploadProgress copy];
+    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
+        if (original) {
+            original(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
+        }
+
+        if (totalBytesExpectedToWrite > 0) {
+            [weakSelf setProgress:(totalBytesWritten / (totalBytesExpectedToWrite * 1.0f)) animated:animated];
+        }
+    }];
+}
+
+- (void)setProgressWithDownloadProgressOfOperation:(AFURLConnectionOperation *)operation
+                                          animated:(BOOL)animated
+{
+    __weak __typeof(self)weakSelf = self;
+    void (^original)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected) = [operation.downloadProgress copy];
+    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
+        if (original) {
+            original(bytesRead, totalBytesRead, totalBytesExpectedToRead);
+        }
+        
+        if (totalBytesExpectedToRead > 0) {
+            [weakSelf setProgress:(totalBytesRead / (totalBytesExpectedToRead  * 1.0f)) animated:animated];
+        }
+    }];
+}
+
+#pragma mark - NSKeyValueObserving
+
+- (void)observeValueForKeyPath:(NSString *)keyPath
+                      ofObject:(id)object
+                        change:(NSDictionary *)change
+                       context:(void *)context
+{
+    if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) {
+        if ([keyPath isEqualToString:@"countOfBytesSent"]) {
+            if ([object countOfBytesExpectedToSend] > 0) {
+                self.progress = [object countOfBytesSent] / ([object countOfBytesExpectedToSend] * 1.0f);
+            }
+        } else if ([keyPath isEqualToString:@"countOfBytesReceived"]) {
+            if ([object countOfBytesExpectedToReceive] > 0) {
+                self.progress = [object countOfBytesReceived] / ([object countOfBytesExpectedToReceive] * 1.0f);
+            }
+        } else if ([keyPath isEqualToString:@"state"]) {
+            if ([object state] == NSURLSessionTaskStateCompleted) {
+                @try {
+                    [object removeObserver:self forKeyPath:@"state"];
+
+                    if (context == AFTaskCountOfBytesSentContext) {
+                        [object removeObserver:self forKeyPath:@"countOfBytesSent"];
+                    }
+
+                    if (context == AFTaskCountOfBytesReceivedContext) {
+                        [object removeObserver:self forKeyPath:@"countOfBytesReceived"];
+                    }
+                }
+                @catch (NSException *exception) {}
+            }
+        }
+    }
+}
+
+@end

+ 38 - 0
UIKit+AFNetworking/UIWebView+AFNetworking.h

@@ -0,0 +1,38 @@
+// UIWebView+AFNetworking.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 <UIKit/UIKit.h>
+
+/**
+ 
+ */
+@interface UIWebView (AFNetworking)
+
+/**
+ 
+ */
+- (void)loadRequest:(NSURLRequest *)request
+           progress:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress
+            success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
+            failure:(void (^)(NSError *error))failure;
+
+@end

+ 77 - 0
UIKit+AFNetworking/UIWebView+AFNetworking.m

@@ -0,0 +1,77 @@
+// UIWebView+AFNetworking.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 "UIWebView+AFNetworking.h"
+
+#import "AFHTTPRequestOperation.h"
+
+#import <objc/runtime.h>
+
+static char kAFHTTPRequestOperationKey;
+
+@interface UIWebView (_AFNetworking)
+@property (readwrite, nonatomic, strong, setter = af_setHTTPRequestOperation:) AFHTTPRequestOperation *af_HTTPRequestOperation;
+@end
+
+@implementation UIWebView (_AFNetworking)
+@dynamic af_HTTPRequestOperation;
+@end
+
+#pragma mark -
+
+@implementation UIWebView (AFNetworking)
+
+- (AFHTTPRequestOperation *)af_HTTPRequestOperation {
+    return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, &kAFHTTPRequestOperationKey);
+}
+
+- (void)af_setHTTPRequestOperation:(AFHTTPRequestOperation *)operation {
+    objc_setAssociatedObject(self, &kAFHTTPRequestOperationKey, operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+#pragma mark -
+
+- (void)loadRequest:(NSURLRequest *)request
+           progress:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress
+            success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
+            failure:(void (^)(NSError *error))failure
+{
+    if (self.af_HTTPRequestOperation) {
+        [self.af_HTTPRequestOperation cancel];
+    }
+
+    self.af_HTTPRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
+    
+    __weak __typeof(self)weakSelf = self;
+    [self.af_HTTPRequestOperation setDownloadProgressBlock:progress];
+    [self.af_HTTPRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
+        NSString *HTML = success ? success(operation.response, operation.responseString) : operation.responseString;
+        [weakSelf loadHTMLString:HTML baseURL:[operation.response URL]];
+    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
+        if (failure) {
+            failure(error);
+        }
+    }];
+    [self.af_HTTPRequestOperation start];
+}
+
+@end