├── Example ├── adn.cer ├── Icon.png ├── Default.png ├── Icon@2x.png ├── root_ca.cer ├── Default@2x.png ├── digicert_ca_3.cer ├── Default-568h@2x.png ├── AFNetworking watchOS Extension │ ├── Assets.xcassets │ │ └── README__ignoredByTemplate__ │ ├── ExtensionDelegate.h │ ├── InterfaceController.h │ ├── InterfaceController.m │ ├── ExtensionDelegate.m │ └── Info.plist ├── Images │ ├── profile-image-placeholder.png │ └── profile-image-placeholder@2x.png ├── AFNetworking OS X Example.xcodeproj │ └── project.xcworkspace │ │ └── contents.xcworkspacedata ├── AFNetworking iOS Example.xcodeproj │ └── project.xcworkspace │ │ └── contents.xcworkspacedata ├── AFNetworking Example.entitlements ├── Prefix.pch ├── AFNetworking watchOS │ ├── Base.lproj │ │ └── Interface.storyboard │ ├── Info.plist │ └── Assets.xcassets │ │ └── AppIcon.appiconset │ │ └── Contents.json ├── Today Extension │ ├── Info.plist │ ├── TodayViewController.h │ ├── TodayViewController.m │ └── MainInterface.storyboard ├── Mac-Info.plist ├── Classes │ ├── Controllers │ │ ├── GlobalTimelineViewController.h │ │ └── GlobalTimelineViewController.m │ ├── AFAppDotNetAPIClient.h │ ├── Views │ │ ├── PostTableViewCell.h │ │ └── PostTableViewCell.m │ ├── Models │ │ ├── Post.h │ │ ├── User.h │ │ ├── Post.m │ │ └── User.m │ └── AFAppDotNetAPIClient.m ├── main.m ├── iOS-Info.plist ├── AppDelegate.h └── AppDelegate.m ├── Tests ├── OS X Tests │ ├── en.lproj │ │ └── InfoPlist.strings │ ├── OS X Tests-Prefix.pch │ └── OS X Tests-Info.plist ├── iOS Tests │ ├── en.lproj │ │ └── InfoPlist.strings │ ├── iOS Tests-Prefix.pch │ └── iOS Tests-Info.plist ├── Resources │ ├── SelfSigned │ │ ├── AltName.cer │ │ ├── NoDomains.cer │ │ └── foobar.com.cer │ ├── HTTPBin.org │ │ ├── httpbinorg_01162016.cer │ │ ├── AddTrust_External_CA_Root.cer │ │ ├── COMODO_RSA_Certification_Authority.cer │ │ ├── HTTPBinOrgServerTrustChain │ │ │ ├── httpbin_0.cer │ │ │ ├── httpbin_1.cer │ │ │ ├── httpbin_2.cer │ │ │ └── httpbin_3.cer │ │ └── COMODO_RSA_Domain_Validation_Secure_Server_CA.cer │ └── ADN.net │ │ └── ADNNetServerTrustChain │ │ ├── adn_0.cer │ │ ├── adn_1.cer │ │ └── adn_2.cer ├── Podfile ├── AFNetworking-Prefix.pch ├── AFNetworkingTests-Info.plist ├── Tests │ ├── AFTestCase.h │ ├── 1.0 Tests │ │ ├── AFNetworkingTests.h │ │ ├── AFMockURLProtocol.h │ │ ├── AFNetworkingTests.m │ │ ├── AFMockURLProtocol.m │ │ └── AFJSONRequestOperationTests.m │ ├── AFTestCase.m │ ├── AFPropertyListResponseSerializerTests.m │ ├── AFHTTPResponseSerializationTests.m │ ├── AFUIImageViewTests.m │ ├── AFNetworkActivityManagerTests.m │ ├── AFNetworkReachabilityManagerTests.m │ ├── AFJSONSerializationTests.m │ └── AFHTTPSessionManagerTests.m └── Schemes │ ├── iOS Tests.xcscheme │ └── OS X Tests.xcscheme ├── .cocoadocs.yml ├── .travis.yml ├── .gitignore ├── LICENSE ├── UIKit+AFNetworking ├── UIImage+AFNetworking.h ├── UIKit+AFNetworking.h ├── UIActivityIndicatorView+AFNetworking.h ├── UIRefreshControl+AFNetworking.h ├── UIProgressView+AFNetworking.h ├── AFNetworkActivityIndicatorManager.h ├── UIAlertView+AFNetworking.h ├── UIWebView+AFNetworking.h ├── AFNetworkActivityIndicatorManager.m ├── UIRefreshControl+AFNetworking.m ├── UIWebView+AFNetworking.m └── UIAlertView+AFNetworking.m ├── AFNetworking ├── AFNetworking.h ├── AFHTTPRequestOperation.h └── AFSecurityPolicy.h ├── Rakefile ├── AFNetworking.podspec ├── CONTRIBUTING.md └── AFNetworking.xcworkspace └── contents.xcworkspacedata /Example/adn.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Example/adn.cer -------------------------------------------------------------------------------- /Example/Icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Example/Icon.png -------------------------------------------------------------------------------- /Tests/OS X Tests/en.lproj/InfoPlist.strings: -------------------------------------------------------------------------------- 1 | /* Localized versions of Info.plist keys */ 2 | 3 | -------------------------------------------------------------------------------- /Tests/iOS Tests/en.lproj/InfoPlist.strings: -------------------------------------------------------------------------------- 1 | /* Localized versions of Info.plist keys */ 2 | 3 | -------------------------------------------------------------------------------- /Example/Default.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Example/Default.png -------------------------------------------------------------------------------- /Example/Icon@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Example/Icon@2x.png -------------------------------------------------------------------------------- /Example/root_ca.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Example/root_ca.cer -------------------------------------------------------------------------------- /Example/Default@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Example/Default@2x.png -------------------------------------------------------------------------------- /Example/digicert_ca_3.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Example/digicert_ca_3.cer -------------------------------------------------------------------------------- /Example/Default-568h@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Example/Default-568h@2x.png -------------------------------------------------------------------------------- /Tests/Resources/SelfSigned/AltName.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Tests/Resources/SelfSigned/AltName.cer -------------------------------------------------------------------------------- /Tests/Resources/SelfSigned/NoDomains.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Tests/Resources/SelfSigned/NoDomains.cer -------------------------------------------------------------------------------- /Tests/Resources/SelfSigned/foobar.com.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Tests/Resources/SelfSigned/foobar.com.cer -------------------------------------------------------------------------------- /Example/AFNetworking watchOS Extension/Assets.xcassets/README__ignoredByTemplate__: -------------------------------------------------------------------------------- 1 | Did you know that git does not support storing empty directories? 2 | -------------------------------------------------------------------------------- /Example/Images/profile-image-placeholder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Example/Images/profile-image-placeholder.png -------------------------------------------------------------------------------- /Example/Images/profile-image-placeholder@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Example/Images/profile-image-placeholder@2x.png -------------------------------------------------------------------------------- /Tests/Resources/HTTPBin.org/httpbinorg_01162016.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Tests/Resources/HTTPBin.org/httpbinorg_01162016.cer -------------------------------------------------------------------------------- /Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_0.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_0.cer -------------------------------------------------------------------------------- /Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_1.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_1.cer -------------------------------------------------------------------------------- /Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_2.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_2.cer -------------------------------------------------------------------------------- /Tests/Resources/HTTPBin.org/AddTrust_External_CA_Root.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Tests/Resources/HTTPBin.org/AddTrust_External_CA_Root.cer -------------------------------------------------------------------------------- /Tests/Resources/HTTPBin.org/COMODO_RSA_Certification_Authority.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Tests/Resources/HTTPBin.org/COMODO_RSA_Certification_Authority.cer -------------------------------------------------------------------------------- /Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_0.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_0.cer -------------------------------------------------------------------------------- /Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_1.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_1.cer -------------------------------------------------------------------------------- /Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_2.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_2.cer -------------------------------------------------------------------------------- /Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_3.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_3.cer -------------------------------------------------------------------------------- /Tests/Resources/HTTPBin.org/COMODO_RSA_Domain_Validation_Secure_Server_CA.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flightaware/AFNetworking/master/Tests/Resources/HTTPBin.org/COMODO_RSA_Domain_Validation_Secure_Server_CA.cer -------------------------------------------------------------------------------- /.cocoadocs.yml: -------------------------------------------------------------------------------- 1 | highlight-color: "#F89915" 2 | highlight-dark-color: "#E23B1B" 3 | darker-color: "#D8A688" 4 | darker-dark-color: "#E93D1C" 5 | background-color: "#E9DFDB" 6 | alt-link-color: "#E23B1B" 7 | warning-color: "#E23B1B" 8 | -------------------------------------------------------------------------------- /Tests/OS X Tests/OS X Tests-Prefix.pch: -------------------------------------------------------------------------------- 1 | // 2 | // Prefix header 3 | // 4 | // The contents of this file are implicitly included at the beginning of every source file. 5 | // 6 | 7 | #ifdef __OBJC__ 8 | #import 9 | #endif 10 | -------------------------------------------------------------------------------- /Example/AFNetworking OS X Example.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Example/AFNetworking iOS Example.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Tests/iOS Tests/iOS Tests-Prefix.pch: -------------------------------------------------------------------------------- 1 | // 2 | // Prefix header 3 | // 4 | // The contents of this file are implicitly included at the beginning of every source file. 5 | // 6 | 7 | #ifdef __OBJC__ 8 | #import 9 | #import 10 | #endif 11 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: objective-c 2 | osx_image: beta-xcode6.3 3 | before_install: 4 | - gem install cocoapods --no-rdoc --no-ri --no-document --quiet 5 | - gem install xcpretty --no-rdoc --no-ri --no-document --quiet 6 | - cd Tests && pod install && cd $TRAVIS_BUILD_DIR 7 | script: rake test 8 | 9 | -------------------------------------------------------------------------------- /Example/AFNetworking watchOS Extension/ExtensionDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // ExtensionDelegate.h 3 | // AFNetworking watchOS Extension 4 | // 5 | // Created by Kevin Harwood on 8/3/15. 6 | // Copyright © 2015 Gowalla. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ExtensionDelegate : NSObject 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /Example/AFNetworking watchOS Extension/InterfaceController.h: -------------------------------------------------------------------------------- 1 | // 2 | // InterfaceController.h 3 | // AFNetworking watchOS Extension 4 | // 5 | // Created by Kevin Harwood on 8/3/15. 6 | // Copyright © 2015 Gowalla. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | 12 | @interface InterfaceController : WKInterfaceController 13 | 14 | @end 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | .DS_Store 3 | build/ 4 | *.pbxuser 5 | !default.pbxuser 6 | *.mode1v3 7 | !default.mode1v3 8 | *.mode2v3 9 | !default.mode2v3 10 | *.perspectivev3 11 | !default.perspectivev3 12 | *.xcworkspace 13 | !default.xcworkspace 14 | xcuserdata 15 | profile 16 | *.moved-aside 17 | DerivedData 18 | .idea/ 19 | Tests/Pods 20 | Tests/Podfile.lock 21 | Tests/AFNetworking Tests.xcodeproj/xcshareddata/xcschemes/ 22 | -------------------------------------------------------------------------------- /Example/AFNetworking Example.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | com.apple.security.network.client 8 | 9 | com.apple.security.network.server 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Tests/Podfile: -------------------------------------------------------------------------------- 1 | source 'https://github.com/CocoaPods/Specs' 2 | 3 | xcodeproj 'AFNetworking Tests' 4 | workspace '../AFNetworking' 5 | inhibit_all_warnings! 6 | 7 | def import_pods 8 | pod 'OCMock', '~> 2.1.1' 9 | pod 'Expecta', '~> 0.2.1' 10 | pod 'AFNetworking', :path => '../' 11 | end 12 | 13 | target :ios do 14 | platform :ios, '7.0' 15 | link_with 'iOS Tests' 16 | import_pods 17 | end 18 | 19 | target :osx do 20 | platform :osx, '10.9' 21 | link_with 'OS X Tests' 22 | import_pods 23 | end 24 | -------------------------------------------------------------------------------- /Tests/AFNetworking-Prefix.pch: -------------------------------------------------------------------------------- 1 | // 2 | // Prefix header for all source files of the 'AFNetworking' target in the 'AFNetworking' project 3 | // 4 | 5 | #ifdef __OBJC__ 6 | #import 7 | 8 | #import 9 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 10 | #import 11 | #import 12 | #else 13 | #import 14 | #import 15 | #endif 16 | #endif 17 | -------------------------------------------------------------------------------- /Example/Prefix.pch: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 4 | #ifndef __IPHONE_6_0 5 | #warning "This project uses features only available in iPhone SDK 6.0 and later." 6 | #endif 7 | 8 | #ifdef __OBJC__ 9 | #import 10 | #import 11 | #import 12 | #import 13 | #endif 14 | #else 15 | #ifdef __OBJC__ 16 | #import 17 | #import 18 | #import 19 | #import 20 | #endif 21 | #endif 22 | -------------------------------------------------------------------------------- /Tests/AFNetworkingTests-Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | ${EXECUTABLE_NAME} 9 | CFBundleIdentifier 10 | org.afnetworking.${PRODUCT_NAME:rfc1034identifier} 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundlePackageType 14 | BNDL 15 | CFBundleShortVersionString 16 | 1.0 17 | CFBundleSignature 18 | ???? 19 | CFBundleVersion 20 | 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /Tests/iOS Tests/iOS Tests-Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | ${EXECUTABLE_NAME} 9 | CFBundleIdentifier 10 | com.alamofire.afnetworking.${PRODUCT_NAME:rfc1034identifier} 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundlePackageType 14 | BNDL 15 | CFBundleShortVersionString 16 | 1.0 17 | CFBundleSignature 18 | ???? 19 | CFBundleVersion 20 | 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /Tests/OS X Tests/OS X Tests-Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | ${EXECUTABLE_NAME} 9 | CFBundleIdentifier 10 | com.alamofire.afnetworking.${PRODUCT_NAME:rfc1034identifier} 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundlePackageType 14 | BNDL 15 | CFBundleShortVersionString 16 | 1.0 17 | CFBundleSignature 18 | ???? 19 | CFBundleVersion 20 | 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /Example/AFNetworking watchOS Extension/InterfaceController.m: -------------------------------------------------------------------------------- 1 | // 2 | // InterfaceController.m 3 | // AFNetworking watchOS Extension 4 | // 5 | // Created by Kevin Harwood on 8/3/15. 6 | // Copyright © 2015 Gowalla. All rights reserved. 7 | // 8 | 9 | #import "InterfaceController.h" 10 | 11 | 12 | @interface InterfaceController() 13 | 14 | @end 15 | 16 | 17 | @implementation InterfaceController 18 | 19 | - (void)awakeWithContext:(id)context { 20 | [super awakeWithContext:context]; 21 | 22 | // Configure interface objects here. 23 | } 24 | 25 | - (void)willActivate { 26 | // This method is called when watch view controller is about to be visible to user 27 | [super willActivate]; 28 | } 29 | 30 | - (void)didDeactivate { 31 | // This method is called when watch view controller is no longer visible 32 | [super didDeactivate]; 33 | } 34 | 35 | @end 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Example/AFNetworking watchOS/Base.lproj/Interface.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /Example/AFNetworking watchOS Extension/ExtensionDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // ExtensionDelegate.m 3 | // AFNetworking watchOS Extension 4 | // 5 | // Created by Kevin Harwood on 8/3/15. 6 | // Copyright © 2015 Gowalla. All rights reserved. 7 | // 8 | 9 | #import "ExtensionDelegate.h" 10 | 11 | @implementation ExtensionDelegate 12 | 13 | - (void)applicationDidFinishLaunching { 14 | // Perform any final initialization of your application. 15 | } 16 | 17 | - (void)applicationDidBecomeActive { 18 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 19 | } 20 | 21 | - (void)applicationWillResignActive { 22 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 23 | // Use this method to pause ongoing tasks, disable timers, etc. 24 | } 25 | 26 | @end 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /Example/Today Extension/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | Most recent post 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | com.alamofire.AFNetworking-iOS-Example.$(PRODUCT_NAME:rfc1034identifier) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | XPC! 19 | CFBundleShortVersionString 20 | 1.0 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | 1 25 | NSExtension 26 | 27 | NSExtensionMainStoryboard 28 | MainInterface 29 | NSExtensionPointIdentifier 30 | com.apple.widget-extension 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Example/Mac-Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | ${EXECUTABLE_NAME} 9 | CFBundleIconFile 10 | 11 | CFBundleIdentifier 12 | com.alamofire.${PRODUCT_NAME:rfc1034identifier} 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | ${PRODUCT_NAME} 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | 1.0 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | 1 25 | LSMinimumSystemVersion 26 | ${MACOSX_DEPLOYMENT_TARGET} 27 | NSHumanReadableCopyright 28 | Copyright © 2012年 Mattt Thompson. All rights reserved. 29 | NSMainNibFile 30 | MainMenu 31 | NSPrincipalClass 32 | NSApplication 33 | 34 | 35 | -------------------------------------------------------------------------------- /Example/AFNetworking watchOS/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | AFNetworking iOS Example 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | 1.0 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | 1 25 | UISupportedInterfaceOrientations 26 | 27 | UIInterfaceOrientationPortrait 28 | UIInterfaceOrientationPortraitUpsideDown 29 | 30 | WKCompanionAppBundleIdentifier 31 | com.alamofire.AFNetworking-iOS-Example 32 | WKWatchKitApp 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Example/Today Extension/TodayViewController.h: -------------------------------------------------------------------------------- 1 | // TodayViewController.h 2 | // 3 | // Copyright (c) 2015 Brian Nickel 4 | // 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import 25 | 26 | @interface TodayViewController : UIViewController 27 | @end 28 | -------------------------------------------------------------------------------- /Example/Classes/Controllers/GlobalTimelineViewController.h: -------------------------------------------------------------------------------- 1 | // GlobalTimelineViewController.h 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | 25 | @interface GlobalTimelineViewController : UITableViewController 26 | 27 | @end 28 | -------------------------------------------------------------------------------- /Example/AFNetworking watchOS Extension/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | AFNetworking watchOS Extension 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | XPC! 19 | CFBundleShortVersionString 20 | 1.0 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | 1 25 | NSExtension 26 | 27 | NSExtensionAttributes 28 | 29 | WKAppBundleIdentifier 30 | com.alamofire.AFNetworking-iOS-Example.watchkitapp 31 | 32 | NSExtensionPointIdentifier 33 | com.apple.watchkit 34 | 35 | RemoteInterfacePrincipalClass 36 | InterfaceController 37 | WKExtensionDelegateClassName 38 | ExtensionDelegate 39 | 40 | 41 | -------------------------------------------------------------------------------- /Example/Classes/AFAppDotNetAPIClient.h: -------------------------------------------------------------------------------- 1 | // AFAppDotNetAPIClient.h 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | #import "AFHTTPSessionManager.h" 25 | 26 | @interface AFAppDotNetAPIClient : AFHTTPSessionManager 27 | 28 | + (instancetype)sharedClient; 29 | 30 | @end 31 | -------------------------------------------------------------------------------- /UIKit+AFNetworking/UIImage+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+AFNetworking.h 3 | // 4 | // 5 | // Created by Paulo Ferreira on 08/07/15. 6 | // 7 | // Permission is hereby granted, free of charge, to any person obtaining a copy 8 | // of this software and associated documentation files (the "Software"), to deal 9 | // in the Software without restriction, including without limitation the rights 10 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | // copies of the Software, and to permit persons to whom the Software is 12 | // furnished to do so, subject to the following conditions: 13 | // 14 | // The above copyright notice and this permission notice shall be included in 15 | // all copies or substantial portions of the Software. 16 | // 17 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 23 | // THE SOFTWARE. 24 | 25 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 26 | 27 | #import 28 | 29 | @interface UIImage (AFNetworking) 30 | 31 | + (UIImage*) safeImageWithData:(NSData*)data; 32 | 33 | @end 34 | 35 | #endif 36 | -------------------------------------------------------------------------------- /Example/AFNetworking watchOS/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "size" : "24x24", 5 | "idiom" : "watch", 6 | "scale" : "2x", 7 | "role" : "notificationCenter", 8 | "subtype" : "38mm" 9 | }, 10 | { 11 | "size" : "27.5x27.5", 12 | "idiom" : "watch", 13 | "scale" : "2x", 14 | "role" : "notificationCenter", 15 | "subtype" : "42mm" 16 | }, 17 | { 18 | "size" : "29x29", 19 | "idiom" : "watch", 20 | "role" : "companionSettings", 21 | "scale" : "2x" 22 | }, 23 | { 24 | "size" : "29x29", 25 | "idiom" : "watch", 26 | "role" : "companionSettings", 27 | "scale" : "3x" 28 | }, 29 | { 30 | "size" : "40x40", 31 | "idiom" : "watch", 32 | "scale" : "2x", 33 | "role" : "appLauncher", 34 | "subtype" : "38mm" 35 | }, 36 | { 37 | "size" : "44x44", 38 | "idiom" : "watch", 39 | "scale" : "2x", 40 | "role" : "longLook", 41 | "subtype" : "42mm" 42 | }, 43 | { 44 | "size" : "86x86", 45 | "idiom" : "watch", 46 | "scale" : "2x", 47 | "role" : "quickLook", 48 | "subtype" : "38mm" 49 | }, 50 | { 51 | "size" : "98x98", 52 | "idiom" : "watch", 53 | "scale" : "2x", 54 | "role" : "quickLook", 55 | "subtype" : "42mm" 56 | } 57 | ], 58 | "info" : { 59 | "version" : 1, 60 | "author" : "xcode" 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Example/Classes/Views/PostTableViewCell.h: -------------------------------------------------------------------------------- 1 | // TweetTableViewCell.h 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | 25 | @class Post; 26 | 27 | @interface PostTableViewCell : UITableViewCell 28 | 29 | @property (nonatomic, strong) Post *post; 30 | 31 | + (CGFloat)heightForCellWithPost:(Post *)post; 32 | 33 | @end 34 | -------------------------------------------------------------------------------- /Tests/Tests/AFTestCase.h: -------------------------------------------------------------------------------- 1 | // AFTestCase.h 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #define EXP_SHORTHAND YES 25 | #import "Expecta.h" 26 | #import "OCMock.h" 27 | 28 | extern NSString * const AFNetworkingTestsBaseURLString; 29 | 30 | @interface AFTestCase : XCTestCase 31 | 32 | @property (nonatomic, strong, readonly) NSURL *baseURL; 33 | 34 | @end 35 | -------------------------------------------------------------------------------- /Tests/Tests/1.0 Tests/AFNetworkingTests.h: -------------------------------------------------------------------------------- 1 | // AFNetworkingTests.h 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | #import "AFNetworking.h" 24 | 25 | #define EXP_SHORTHAND YES 26 | #import "Expecta.h" 27 | #import "OCMock.h" 28 | 29 | extern NSString * const AFNetworkingTestsBaseURLString; 30 | 31 | @interface AFNetworkingTests : NSObject 32 | 33 | @end 34 | -------------------------------------------------------------------------------- /Example/main.m: -------------------------------------------------------------------------------- 1 | // main.m 2 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 23 | #import 24 | 25 | int main(int argc, char *argv[]) { 26 | @autoreleasepool { 27 | int retVal = UIApplicationMain(argc, argv, @"UIApplication", @"AppDelegate"); 28 | return retVal; 29 | } 30 | } 31 | #else 32 | #import 33 | 34 | int main(int argc, char *argv[]) { 35 | return NSApplicationMain(argc, (const char **)argv); 36 | } 37 | #endif 38 | -------------------------------------------------------------------------------- /Tests/Tests/AFTestCase.m: -------------------------------------------------------------------------------- 1 | // AFTestCase.m 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFTestCase.h" 23 | 24 | NSString * const AFNetworkingTestsBaseURLString = @"https://httpbin.org/"; 25 | 26 | @implementation AFTestCase 27 | 28 | - (void)setUp { 29 | [super setUp]; 30 | 31 | [Expecta setAsynchronousTestTimeout:5.0]; 32 | } 33 | 34 | - (void)tearDown { 35 | [super tearDown]; 36 | } 37 | 38 | #pragma mark - 39 | 40 | - (NSURL *)baseURL { 41 | return [NSURL URLWithString:AFNetworkingTestsBaseURLString]; 42 | } 43 | 44 | @end 45 | -------------------------------------------------------------------------------- /Tests/Tests/1.0 Tests/AFMockURLProtocol.h: -------------------------------------------------------------------------------- 1 | // AFMockURLProtocol.h 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #import "OCMock.h" 25 | 26 | @protocol AFMockURLProtocolProxy 27 | - (id)stub; 28 | - (id)expect; 29 | - (id)reject; 30 | @end 31 | 32 | @interface AFMockURLProtocol : NSURLProtocol 33 | 34 | + (void)handleNextRequestForURL:(NSURL *)URL 35 | usingBlock:(void (^)(AFMockURLProtocol * protocol))block; 36 | 37 | @end 38 | -------------------------------------------------------------------------------- /Tests/Tests/1.0 Tests/AFNetworkingTests.m: -------------------------------------------------------------------------------- 1 | // AFNetworkingTests.m 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFNetworkingTests.h" 23 | #import "AFHTTPRequestOperationLogger.h" 24 | 25 | NSString * const AFNetworkingTestsBaseURLString = @"http://httpbin.org/"; 26 | 27 | @implementation AFNetworkingTests 28 | 29 | + (void)load { 30 | if ([[[[[NSProcessInfo processInfo] environment] valueForKey:@"AFTestsLoggingEnabled"] uppercaseString] isEqualToString:@"YES"]) { 31 | [[AFHTTPRequestOperationLogger sharedLogger] startLogging]; 32 | } 33 | } 34 | 35 | @end 36 | -------------------------------------------------------------------------------- /Example/Classes/Models/Post.h: -------------------------------------------------------------------------------- 1 | // Post.h 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | 25 | @class User; 26 | 27 | @interface Post : NSObject 28 | 29 | @property (nonatomic, assign) NSUInteger postID; 30 | @property (nonatomic, strong) NSString *text; 31 | 32 | @property (nonatomic, strong) User *user; 33 | 34 | - (instancetype)initWithAttributes:(NSDictionary *)attributes; 35 | 36 | + (NSURLSessionDataTask *)globalTimelinePostsWithBlock:(void (^)(NSArray *posts, NSError *error))block; 37 | 38 | @end 39 | 40 | @interface Post (NSCoding) 41 | @end 42 | -------------------------------------------------------------------------------- /Example/iOS-Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | AFNetworking 9 | CFBundleExecutable 10 | ${EXECUTABLE_NAME} 11 | CFBundleIconFile 12 | 13 | CFBundleIconFiles 14 | 15 | Icon.png 16 | Icon@2x.png 17 | 18 | CFBundleIcons 19 | 20 | CFBundlePrimaryIcon 21 | 22 | CFBundleIconFiles 23 | 24 | Icon.png 25 | Icon@2x.png 26 | 27 | UIPrerenderedIcon 28 | 29 | 30 | 31 | CFBundleIdentifier 32 | com.alamofire.${PRODUCT_NAME:rfc1034identifier} 33 | CFBundleInfoDictionaryVersion 34 | 6.0 35 | CFBundleName 36 | ${PRODUCT_NAME} 37 | CFBundlePackageType 38 | APPL 39 | CFBundleShortVersionString 40 | 1.0 41 | CFBundleSignature 42 | ???? 43 | CFBundleVersion 44 | 1.0.0 45 | LSRequiresIPhoneOS 46 | 47 | UIBackgroundModes 48 | 49 | fetch 50 | 51 | UIPrerenderedIcon 52 | 53 | UIStatusBarHidden 54 | 55 | UISupportedInterfaceOrientations 56 | 57 | UIInterfaceOrientationPortrait 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /UIKit+AFNetworking/UIKit+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIKit+AFNetworking.h 2 | // 3 | // Copyright (c) 2013 AFNetworking (http://afnetworking.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #if TARGET_OS_IOS 24 | #import 25 | 26 | #ifndef _UIKIT_AFNETWORKING_ 27 | #define _UIKIT_AFNETWORKING_ 28 | 29 | #import "AFNetworkActivityIndicatorManager.h" 30 | 31 | #import "UIActivityIndicatorView+AFNetworking.h" 32 | #import "UIAlertView+AFNetworking.h" 33 | #import "UIButton+AFNetworking.h" 34 | #import "UIImageView+AFNetworking.h" 35 | #import "UIProgressView+AFNetworking.h" 36 | #import "UIRefreshControl+AFNetworking.h" 37 | #import "UIWebView+AFNetworking.h" 38 | #endif /* _UIKIT_AFNETWORKING_ */ 39 | #endif 40 | -------------------------------------------------------------------------------- /Example/Classes/Models/User.h: -------------------------------------------------------------------------------- 1 | // User.h 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | 25 | extern NSString * const kUserProfileImageDidLoadNotification; 26 | 27 | @interface User : NSObject 28 | 29 | @property (readonly, nonatomic, assign) NSUInteger userID; 30 | @property (readonly, nonatomic, copy) NSString *username; 31 | @property (readonly, nonatomic, unsafe_unretained) NSURL *avatarImageURL; 32 | 33 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 34 | @property (nonatomic, strong) NSImage *profileImage; 35 | #endif 36 | 37 | - (instancetype)initWithAttributes:(NSDictionary *)attributes; 38 | 39 | @end 40 | 41 | @interface User (NSCoding) 42 | @end 43 | -------------------------------------------------------------------------------- /Example/Classes/AFAppDotNetAPIClient.m: -------------------------------------------------------------------------------- 1 | // AFAppDotNetAPIClient.h 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "AFAppDotNetAPIClient.h" 24 | 25 | static NSString * const AFAppDotNetAPIBaseURLString = @"https://api.app.net/"; 26 | 27 | @implementation AFAppDotNetAPIClient 28 | 29 | + (instancetype)sharedClient { 30 | static AFAppDotNetAPIClient *_sharedClient = nil; 31 | static dispatch_once_t onceToken; 32 | dispatch_once(&onceToken, ^{ 33 | _sharedClient = [[AFAppDotNetAPIClient alloc] initWithBaseURL:[NSURL URLWithString:AFAppDotNetAPIBaseURLString]]; 34 | _sharedClient.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; 35 | }); 36 | 37 | return _sharedClient; 38 | } 39 | 40 | @end 41 | -------------------------------------------------------------------------------- /Example/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // AppDelegate.h 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | 25 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 26 | #import 27 | 28 | @interface AppDelegate : NSObject 29 | 30 | @property (nonatomic, strong) UIWindow *window; 31 | @property (nonatomic, strong) UINavigationController *navigationController; 32 | 33 | @end 34 | #else 35 | #import 36 | 37 | @interface AppDelegate : NSObject 38 | 39 | @property (strong) IBOutlet NSWindow *window; 40 | @property (strong) IBOutlet NSTableView *tableView; 41 | @property (strong) IBOutlet NSArrayController *postsArrayController; 42 | 43 | @end 44 | #endif 45 | -------------------------------------------------------------------------------- /AFNetworking/AFNetworking.h: -------------------------------------------------------------------------------- 1 | // AFNetworking.h 2 | // 3 | // Copyright (c) 2013 AFNetworking (http://afnetworking.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | #import 25 | 26 | #ifndef _AFNETWORKING_ 27 | #define _AFNETWORKING_ 28 | 29 | #import "AFURLRequestSerialization.h" 30 | #import "AFURLResponseSerialization.h" 31 | #import "AFSecurityPolicy.h" 32 | #if !TARGET_OS_WATCH 33 | #import "AFNetworkReachabilityManager.h" 34 | #import "AFURLConnectionOperation.h" 35 | #import "AFHTTPRequestOperation.h" 36 | #import "AFHTTPRequestOperationManager.h" 37 | #endif 38 | 39 | #if ( ( defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || \ 40 | ( defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 ) || \ 41 | TARGET_OS_WATCH ) 42 | #import "AFURLSessionManager.h" 43 | #import "AFHTTPSessionManager.h" 44 | #endif 45 | 46 | #endif /* _AFNETWORKING_ */ 47 | -------------------------------------------------------------------------------- /Tests/Tests/AFPropertyListResponseSerializerTests.m: -------------------------------------------------------------------------------- 1 | // AFPropertyListResponseSerializerTests.m 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFTestCase.h" 23 | 24 | #import "AFURLResponseSerialization.h" 25 | 26 | @interface AFPropertyListResponseSerializerTests : AFTestCase 27 | @property (nonatomic, strong) AFPropertyListResponseSerializer *responseSerializer; 28 | @end 29 | 30 | @implementation AFPropertyListResponseSerializerTests 31 | 32 | - (void)setUp { 33 | [super setUp]; 34 | self.responseSerializer = [AFPropertyListResponseSerializer serializer]; 35 | } 36 | 37 | #pragma mark - 38 | 39 | - (void)testThatPropertyListResponseSerializerHandles204 { 40 | NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:204 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"application/x-plist"}]; 41 | NSError *error; 42 | id responseObject = [self.responseSerializer responseObjectForResponse:response data:nil error:&error]; 43 | 44 | XCTAssertNil(responseObject, @"Response should be nil when handling 204 with application/x-plist"); 45 | XCTAssertNil(error, @"Error handling application/x-plist"); 46 | } 47 | 48 | @end 49 | -------------------------------------------------------------------------------- /UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIActivityIndicatorView+AFNetworking.h 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #import 25 | 26 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 27 | 28 | #import 29 | 30 | @class AFURLConnectionOperation; 31 | 32 | /** 33 | This category adds methods to the UIKit framework's `UIActivityIndicatorView` class. The methods in this category provide support for automatically starting and stopping animation depending on the loading state of a request operation or session task. 34 | */ 35 | @interface UIActivityIndicatorView (AFNetworking) 36 | 37 | ///---------------------------------- 38 | /// @name Animating for Session Tasks 39 | ///---------------------------------- 40 | 41 | /** 42 | Binds the animating state to the state of the specified task. 43 | 44 | @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. 45 | */ 46 | #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 47 | - (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task; 48 | #endif 49 | 50 | ///--------------------------------------- 51 | /// @name Animating for Request Operations 52 | ///--------------------------------------- 53 | 54 | /** 55 | Binds the animating state to the execution state of the specified operation. 56 | 57 | @param operation The operation. If `nil`, automatic updating from any previously specified operation will be disabled. 58 | */ 59 | - (void)setAnimatingWithStateOfOperation:(nullable AFURLConnectionOperation *)operation; 60 | 61 | @end 62 | 63 | #endif 64 | -------------------------------------------------------------------------------- /UIKit+AFNetworking/UIRefreshControl+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIRefreshControl+AFNetworking.m 2 | // 3 | // Copyright (c) 2014 AFNetworking (http://afnetworking.com) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | 25 | #import 26 | 27 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 28 | 29 | #import 30 | 31 | NS_ASSUME_NONNULL_BEGIN 32 | 33 | @class AFURLConnectionOperation; 34 | 35 | /** 36 | This category adds methods to the UIKit framework's `UIRefreshControl` class. The methods in this category provide support for automatically beginning and ending refreshing depending on the loading state of a request operation or session task. 37 | */ 38 | @interface UIRefreshControl (AFNetworking) 39 | 40 | ///----------------------------------- 41 | /// @name Refreshing for Session Tasks 42 | ///----------------------------------- 43 | 44 | /** 45 | Binds the refreshing state to the state of the specified task. 46 | 47 | @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. 48 | */ 49 | #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 50 | - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; 51 | #endif 52 | 53 | ///---------------------------------------- 54 | /// @name Refreshing for Request Operations 55 | ///---------------------------------------- 56 | 57 | /** 58 | Binds the refreshing state to the execution state of the specified operation. 59 | 60 | @param operation The operation. If `nil`, automatic updating from any previously specified operation will be disabled. 61 | */ 62 | - (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation; 63 | 64 | @end 65 | 66 | NS_ASSUME_NONNULL_END 67 | 68 | #endif 69 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | include FileUtils::Verbose 2 | 3 | namespace :test do 4 | task :prepare do 5 | mkdir_p "Tests/AFNetworking Tests.xcodeproj/xcshareddata/xcschemes" 6 | cp Dir.glob('Tests/Schemes/*.xcscheme'), "Tests/AFNetworking Tests.xcodeproj/xcshareddata/xcschemes/" 7 | end 8 | 9 | desc "Run the AFNetworking Tests for iOS" 10 | task :ios => :prepare do 11 | simulators = get_ios_simulators 12 | destinations = Array.new 13 | simulators.each {|version, available_simulators| 14 | destinations.push("platform=iOS Simulator,OS=#{available_simulators[:runtime]},name=#{available_simulators[:device_names][0]}") 15 | puts "Will run tests for iOS Simulator on iOS #{available_simulators[:runtime]} using #{available_simulators[:device_names][0]}" 16 | } 17 | 18 | run_tests('iOS Tests', 'iphonesimulator', destinations) 19 | tests_failed('iOS') unless $?.success? 20 | end 21 | 22 | desc "Run the AFNetworking Tests for Mac OS X" 23 | task :osx => :prepare do 24 | run_tests('OS X Tests', 'macosx', ['platform=OS X,arch=x86_64']) 25 | tests_failed('OSX') unless $?.success? 26 | end 27 | end 28 | 29 | desc "Run the AFNetworking Tests for iOS & Mac OS X" 30 | task :test do 31 | Rake::Task['test:ios'].invoke 32 | Rake::Task['test:osx'].invoke if is_mavericks_or_above 33 | end 34 | 35 | task :default => 'test' 36 | 37 | 38 | private 39 | 40 | def run_tests(scheme, sdk, destinations) 41 | destinations = destinations.map! { |destination| "-destination \'#{destination}\'" }.join(' ') 42 | sh("xcodebuild -workspace AFNetworking.xcworkspace -scheme '#{scheme}' -sdk '#{sdk}' #{destinations} -configuration Release clean test | xcpretty -c ; exit ${PIPESTATUS[0]}") rescue nil 43 | end 44 | 45 | def is_mavericks_or_above 46 | osx_version = `sw_vers -productVersion`.chomp 47 | Gem::Version.new(osx_version) >= Gem::Version.new('10.9') 48 | end 49 | 50 | def tests_failed(platform) 51 | puts red("#{platform} unit tests failed") 52 | exit $?.exitstatus 53 | end 54 | 55 | def red(string) 56 | "\033[0;31m! #{string}" 57 | end 58 | 59 | def get_ios_simulators 60 | device_section_regex = /== Devices ==(.*?)(?=(?===)|\z)/m 61 | runtime_section_regex = /== Runtimes ==(.*?)(?=(?===)|\z)/m 62 | runtime_version_regex = /iOS (.*) \((.*) - .*?\) (\(.*\))/ 63 | xcrun_output = `xcrun simctl list` 64 | puts "Available iOS Simulators: \n#{xcrun_output}" 65 | 66 | simulators = Hash.new 67 | runtimes_section = xcrun_output.scan(runtime_section_regex)[0] 68 | runtimes_section[0].scan(runtime_version_regex) {|result| 69 | if result[2] !~ /unavailable/ 70 | simulators[result[0]] = Hash.new 71 | simulators[result[0]][:runtime] = result[1] 72 | end 73 | } 74 | 75 | device_section = xcrun_output.scan(device_section_regex)[0] 76 | version_regex = /-- iOS (.*?) --(.*?)(?=(?=-- .*? --)|\z)/m 77 | simulator_name_regex = /(.*) \([A-F0-9-]*\) \(.*\)/ 78 | device_section[0].scan(version_regex) {|result| 79 | if simulators.has_key?(result[0]) 80 | simulators[result[0]][:device_names] = Array.new 81 | result[1].scan(simulator_name_regex) { |device_name_result| 82 | device_name = device_name_result[0].strip 83 | simulators[result[0]][:device_names].push(device_name) 84 | } 85 | end 86 | } 87 | return simulators 88 | end 89 | 90 | -------------------------------------------------------------------------------- /Tests/Schemes/iOS Tests.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 29 | 35 | 36 | 37 | 38 | 39 | 44 | 45 | 47 | 53 | 54 | 55 | 56 | 57 | 66 | 67 | 68 | 69 | 75 | 76 | 78 | 79 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /Tests/Schemes/OS X Tests.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 29 | 35 | 36 | 37 | 38 | 39 | 44 | 45 | 47 | 53 | 54 | 55 | 56 | 57 | 66 | 67 | 68 | 69 | 75 | 76 | 78 | 79 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /Example/Classes/Views/PostTableViewCell.m: -------------------------------------------------------------------------------- 1 | // TweetTableViewCell.m 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "PostTableViewCell.h" 24 | 25 | #import "Post.h" 26 | #import "User.h" 27 | 28 | #import "UIImageView+AFNetworking.h" 29 | 30 | @implementation PostTableViewCell 31 | 32 | - (id)initWithStyle:(UITableViewCellStyle)style 33 | reuseIdentifier:(NSString *)reuseIdentifier 34 | { 35 | self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 36 | if (!self) { 37 | return nil; 38 | } 39 | 40 | self.textLabel.adjustsFontSizeToFitWidth = YES; 41 | self.textLabel.textColor = [UIColor darkGrayColor]; 42 | self.detailTextLabel.font = [UIFont systemFontOfSize:12.0f]; 43 | self.detailTextLabel.numberOfLines = 0; 44 | self.selectionStyle = UITableViewCellSelectionStyleGray; 45 | 46 | return self; 47 | } 48 | 49 | - (void)setPost:(Post *)post { 50 | _post = post; 51 | 52 | self.textLabel.text = _post.user.username; 53 | self.detailTextLabel.text = _post.text; 54 | [self.imageView setImageWithURL:_post.user.avatarImageURL placeholderImage:[UIImage imageNamed:@"profile-image-placeholder"]]; 55 | 56 | [self setNeedsLayout]; 57 | } 58 | 59 | + (CGFloat)heightForCellWithPost:(Post *)post { 60 | return (CGFloat)fmaxf(70.0f, (float)[self detailTextHeight:post.text] + 45.0f); 61 | } 62 | 63 | + (CGFloat)detailTextHeight:(NSString *)text { 64 | CGRect rectToFit = [text boundingRectWithSize:CGSizeMake(240.0f, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12.0f]} context:nil]; 65 | return rectToFit.size.height; 66 | } 67 | 68 | #pragma mark - UIView 69 | 70 | - (void)layoutSubviews { 71 | [super layoutSubviews]; 72 | 73 | self.imageView.frame = CGRectMake(10.0f, 10.0f, 50.0f, 50.0f); 74 | self.textLabel.frame = CGRectMake(70.0f, 6.0f, 240.0f, 20.0f); 75 | 76 | CGRect detailTextLabelFrame = CGRectOffset(self.textLabel.frame, 0.0f, 25.0f); 77 | CGFloat calculatedHeight = [[self class] detailTextHeight:self.post.text]; 78 | detailTextLabelFrame.size.height = calculatedHeight; 79 | self.detailTextLabel.frame = detailTextLabelFrame; 80 | } 81 | 82 | @end 83 | -------------------------------------------------------------------------------- /AFNetworking.podspec: -------------------------------------------------------------------------------- 1 | Pod::Spec.new do |s| 2 | s.name = 'AFNetworking' 3 | s.version = '2.6.0' 4 | s.license = 'MIT' 5 | s.summary = 'A delightful iOS and OS X networking framework.' 6 | s.homepage = 'https://github.com/AFNetworking/AFNetworking' 7 | s.social_media_url = 'https://twitter.com/AFNetworking' 8 | s.authors = { 'Mattt Thompson' => 'm@mattt.me' } 9 | s.source = { :git => 'https://github.com/AFNetworking/AFNetworking.git', :tag => s.version, :submodules => true } 10 | s.requires_arc = true 11 | 12 | s.public_header_files = 'AFNetworking/AFNetworking.h' 13 | s.source_files = 'AFNetworking/AFNetworking.h' 14 | 15 | pch_AF = <<-EOS 16 | #ifndef TARGET_OS_IOS 17 | #define TARGET_OS_IOS TARGET_OS_IPHONE 18 | #endif 19 | 20 | #ifndef TARGET_OS_WATCH 21 | #define TARGET_OS_WATCH 0 22 | #endif 23 | EOS 24 | s.prefix_header_contents = pch_AF 25 | 26 | s.ios.deployment_target = '7.0' 27 | s.osx.deployment_target = '10.9' 28 | s.watchos.deployment_target = '2.0' 29 | 30 | s.subspec 'Serialization' do |ss| 31 | ss.source_files = 'AFNetworking/AFURL{Request,Response}Serialization.{h,m}' 32 | ss.public_header_files = 'AFNetworking/AFURL{Request,Response}Serialization.h' 33 | ss.watchos.frameworks = 'MobileCoreServices', 'CoreGraphics' 34 | ss.ios.frameworks = 'MobileCoreServices', 'CoreGraphics' 35 | ss.osx.frameworks = 'CoreServices' 36 | end 37 | 38 | s.subspec 'Security' do |ss| 39 | ss.source_files = 'AFNetworking/AFSecurityPolicy.{h,m}' 40 | ss.public_header_files = 'AFNetworking/AFSecurityPolicy.h' 41 | ss.frameworks = 'Security' 42 | end 43 | 44 | s.subspec 'Reachability' do |ss| 45 | ss.ios.deployment_target = '7.0' 46 | ss.osx.deployment_target = '10.9' 47 | 48 | ss.source_files = 'AFNetworking/AFNetworkReachabilityManager.{h,m}' 49 | ss.public_header_files = 'AFNetworking/AFNetworkReachabilityManager.h' 50 | 51 | ss.frameworks = 'SystemConfiguration' 52 | end 53 | 54 | s.subspec 'NSURLConnection' do |ss| 55 | ss.ios.deployment_target = '7.0' 56 | ss.osx.deployment_target = '10.9' 57 | 58 | ss.dependency 'AFNetworking/Serialization' 59 | ss.dependency 'AFNetworking/Reachability' 60 | ss.dependency 'AFNetworking/Security' 61 | 62 | ss.source_files = 'AFNetworking/AFURLConnectionOperation.{h,m}', 'AFNetworking/AFHTTPRequestOperation.{h,m}', 'AFNetworking/AFHTTPRequestOperationManager.{h,m}' 63 | ss.public_header_files = 'AFNetworking/AFURLConnectionOperation.h', 'AFNetworking/AFHTTPRequestOperation.h', 'AFNetworking/AFHTTPRequestOperationManager.h' 64 | end 65 | 66 | s.subspec 'NSURLSession' do |ss| 67 | ss.ios.deployment_target = '7.0' 68 | ss.osx.deployment_target = '10.9' 69 | ss.watchos.deployment_target = '2.0' 70 | 71 | ss.dependency 'AFNetworking/Serialization' 72 | ss.ios.dependency 'AFNetworking/Reachability' 73 | ss.osx.dependency 'AFNetworking/Reachability' 74 | ss.dependency 'AFNetworking/Security' 75 | 76 | ss.source_files = 'AFNetworking/AF{URL,HTTP}SessionManager.{h,m}' 77 | ss.public_header_files = 'AFNetworking/AF{URL,HTTP}SessionManager.h' 78 | end 79 | 80 | s.subspec 'UIKit' do |ss| 81 | ss.platform = :ios 82 | ss.dependency 'AFNetworking/NSURLConnection' 83 | ss.dependency 'AFNetworking/NSURLSession' 84 | 85 | ss.public_header_files = 'UIKit+AFNetworking/*.h' 86 | ss.source_files = 'UIKit+AFNetworking' 87 | end 88 | end 89 | -------------------------------------------------------------------------------- /Tests/Tests/AFHTTPResponseSerializationTests.m: -------------------------------------------------------------------------------- 1 | // AFHTTPResponseSerializationTests.m 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFTestCase.h" 23 | 24 | #import "AFURLResponseSerialization.h" 25 | 26 | @interface AFHTTPResponseSerializationTests : AFTestCase 27 | @property (nonatomic, strong) AFHTTPResponseSerializer *responseSerializer; 28 | @end 29 | 30 | @implementation AFHTTPResponseSerializationTests 31 | 32 | - (void)setUp { 33 | [super setUp]; 34 | self.responseSerializer = [AFHTTPResponseSerializer serializer]; 35 | } 36 | 37 | #pragma mark - 38 | 39 | - (void)testThatAFHTTPResponseSerializationHandlesAll2XXCodes { 40 | NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; 41 | [indexSet enumerateIndexesUsingBlock:^(NSUInteger statusCode, BOOL *stop) { 42 | NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:statusCode HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/html"}]; 43 | 44 | XCTAssert([self.responseSerializer.acceptableStatusCodes containsIndex:statusCode], @"Status code %@ should be acceptable", @(statusCode)); 45 | 46 | NSError *error = nil; 47 | [self.responseSerializer validateResponse:response data:[@"text" dataUsingEncoding:NSUTF8StringEncoding] error:&error]; 48 | 49 | XCTAssertNil(error, @"Error handling status code %@", @(statusCode)); 50 | }]; 51 | } 52 | 53 | - (void)testThatAFHTTPResponseSerializationFailsAll4XX5XXStatusCodes { 54 | NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(400, 200)]; 55 | [indexSet enumerateIndexesUsingBlock:^(NSUInteger statusCode, BOOL *stop) { 56 | NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:statusCode HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/html"}]; 57 | 58 | XCTAssert(![self.responseSerializer.acceptableStatusCodes containsIndex:statusCode], @"Status code %@ should not be acceptable", @(statusCode)); 59 | 60 | NSError *error = nil; 61 | [self.responseSerializer validateResponse:response data:[@"text" dataUsingEncoding:NSUTF8StringEncoding] error:&error]; 62 | 63 | XCTAssertNotNil(error, @"Did not fail handling status code %@",@(statusCode)); 64 | }]; 65 | } 66 | 67 | @end 68 | -------------------------------------------------------------------------------- /Tests/Tests/AFUIImageViewTests.m: -------------------------------------------------------------------------------- 1 | // AFUIImageViewTests.h 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFTestCase.h" 23 | #import 24 | #import 25 | 26 | @interface AFUIImageViewTests : AFTestCase 27 | @property (nonatomic, strong) UIImage *cachedImage; 28 | @property (nonatomic, strong) NSURLRequest *cachedImageRequest; 29 | @property (nonatomic, strong) UIImageView *imageView; 30 | @end 31 | 32 | @implementation AFUIImageViewTests 33 | 34 | - (void)setUp { 35 | [super setUp]; 36 | self.imageView = [UIImageView new]; 37 | [self setUpSharedImageCache]; 38 | } 39 | 40 | - (void)tearDown { 41 | [self tearDownSharedImageCache]; 42 | [super tearDown]; 43 | } 44 | 45 | - (void)setUpSharedImageCache { 46 | NSString *resourcePath = [[NSBundle bundleForClass:[self class]] resourcePath]; 47 | NSString *imagePath = [resourcePath stringByAppendingPathComponent:@"Icon.png"]; 48 | self.cachedImage = [UIImage imageWithContentsOfFile:imagePath]; 49 | self.cachedImageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://foo.bar/image"]]; 50 | 51 | id mockImageCache = [OCMockObject mockForProtocol:@protocol(AFImageCache)]; 52 | [[[(OCMockObject *)mockImageCache stub] andReturn:self.cachedImage] cachedImageForRequest:self.cachedImageRequest]; 53 | [UIImageView setSharedImageCache:mockImageCache]; 54 | } 55 | 56 | - (void)tearDownSharedImageCache { 57 | [UIImageView setSharedImageCache:nil]; 58 | } 59 | 60 | - (void)testSetImageWithURLRequestUsesCachedImage { 61 | XCTestExpectation *expectation = [self expectationWithDescription:@"Image view uses cached image"]; 62 | typeof(self) __weak weakSelf = self; 63 | [self.imageView 64 | setImageWithURLRequest:self.cachedImageRequest 65 | placeholderImage:nil 66 | success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) { 67 | XCTAssertEqual(request, weakSelf.cachedImageRequest, @"URL requests do not match"); 68 | XCTAssertNil(response, @"Response should be nil when image is returned from cache"); 69 | XCTAssertEqual(image, weakSelf.cachedImage, @"Cached images do not match"); 70 | [expectation fulfill]; 71 | } 72 | failure:nil]; 73 | [self waitForExpectationsWithTimeout:5.0 handler:nil]; 74 | } 75 | 76 | @end 77 | -------------------------------------------------------------------------------- /Example/Classes/Models/Post.m: -------------------------------------------------------------------------------- 1 | // Post.m 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "Post.h" 24 | #import "User.h" 25 | 26 | #import "AFAppDotNetAPIClient.h" 27 | 28 | @implementation Post 29 | 30 | - (instancetype)initWithAttributes:(NSDictionary *)attributes { 31 | self = [super init]; 32 | if (!self) { 33 | return nil; 34 | } 35 | 36 | self.postID = (NSUInteger)[[attributes valueForKeyPath:@"id"] integerValue]; 37 | self.text = [attributes valueForKeyPath:@"text"]; 38 | 39 | self.user = [[User alloc] initWithAttributes:[attributes valueForKeyPath:@"user"]]; 40 | 41 | return self; 42 | } 43 | 44 | #pragma mark - 45 | 46 | + (NSURLSessionDataTask *)globalTimelinePostsWithBlock:(void (^)(NSArray *posts, NSError *error))block { 47 | return [[AFAppDotNetAPIClient sharedClient] GET:@"stream/0/posts/stream/global" parameters:nil success:^(NSURLSessionDataTask * __unused task, id JSON) { 48 | NSArray *postsFromResponse = [JSON valueForKeyPath:@"data"]; 49 | NSMutableArray *mutablePosts = [NSMutableArray arrayWithCapacity:[postsFromResponse count]]; 50 | for (NSDictionary *attributes in postsFromResponse) { 51 | Post *post = [[Post alloc] initWithAttributes:attributes]; 52 | [mutablePosts addObject:post]; 53 | } 54 | 55 | if (block) { 56 | block([NSArray arrayWithArray:mutablePosts], nil); 57 | } 58 | } failure:^(NSURLSessionDataTask *__unused task, NSError *error) { 59 | if (block) { 60 | block([NSArray array], error); 61 | } 62 | }]; 63 | } 64 | 65 | @end 66 | 67 | @implementation Post (NSCoding) 68 | 69 | - (void)encodeWithCoder:(NSCoder *)aCoder { 70 | [aCoder encodeInteger:(NSInteger)self.postID forKey:@"AF.postID"]; 71 | [aCoder encodeObject:self.text forKey:@"AF.text"]; 72 | [aCoder encodeObject:self.user forKey:@"AF.user"]; 73 | } 74 | 75 | - (instancetype)initWithCoder:(NSCoder *)aDecoder { 76 | self = [super init]; 77 | if (!self) { 78 | return nil; 79 | } 80 | 81 | self.postID = (NSUInteger)[aDecoder decodeIntegerForKey:@"AF.postID"]; 82 | self.text = [aDecoder decodeObjectOfClass:[NSString class] forKey:@"AF.text"]; 83 | self.user = [aDecoder decodeObjectOfClass:[User class] forKey:@"AF.user"]; 84 | 85 | return self; 86 | } 87 | 88 | + (BOOL)supportsSecureCoding { 89 | return YES; 90 | } 91 | 92 | @end 93 | -------------------------------------------------------------------------------- /UIKit+AFNetworking/UIProgressView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIProgressView+AFNetworking.h 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #import 25 | 26 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 27 | 28 | #import 29 | 30 | NS_ASSUME_NONNULL_BEGIN 31 | 32 | @class AFURLConnectionOperation; 33 | 34 | /** 35 | This category adds methods to the UIKit framework's `UIProgressView` class. The methods in this category provide support for binding the progress to the upload and download progress of a session task or request operation. 36 | */ 37 | @interface UIProgressView (AFNetworking) 38 | 39 | ///------------------------------------ 40 | /// @name Setting Session Task Progress 41 | ///------------------------------------ 42 | 43 | /** 44 | Binds the progress to the upload progress of the specified session task. 45 | 46 | @param task The session task. 47 | @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. 48 | */ 49 | #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 50 | - (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task 51 | animated:(BOOL)animated; 52 | #endif 53 | 54 | /** 55 | Binds the progress to the download progress of the specified session task. 56 | 57 | @param task The session task. 58 | @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. 59 | */ 60 | #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 61 | - (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task 62 | animated:(BOOL)animated; 63 | #endif 64 | 65 | ///------------------------------------ 66 | /// @name Setting Session Task Progress 67 | ///------------------------------------ 68 | 69 | /** 70 | Binds the progress to the upload progress of the specified request operation. 71 | 72 | @param operation The request operation. 73 | @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. 74 | */ 75 | - (void)setProgressWithUploadProgressOfOperation:(AFURLConnectionOperation *)operation 76 | animated:(BOOL)animated; 77 | 78 | /** 79 | Binds the progress to the download progress of the specified request operation. 80 | 81 | @param operation The request operation. 82 | @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. 83 | */ 84 | - (void)setProgressWithDownloadProgressOfOperation:(AFURLConnectionOperation *)operation 85 | animated:(BOOL)animated; 86 | 87 | @end 88 | 89 | NS_ASSUME_NONNULL_END 90 | 91 | #endif 92 | -------------------------------------------------------------------------------- /Tests/Tests/1.0 Tests/AFMockURLProtocol.m: -------------------------------------------------------------------------------- 1 | // AFMockURLProtocol.m 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFMockURLProtocol.h" 23 | 24 | typedef void (^AFTestURLProtocolInitializationCallback)(AFMockURLProtocol *protocol); 25 | 26 | static volatile NSURL *_matchingURL = nil; 27 | static volatile AFTestURLProtocolInitializationCallback _initializationCallback = nil; 28 | 29 | @implementation AFMockURLProtocol 30 | 31 | + (void)load { 32 | [NSURLProtocol registerClass:[AFMockURLProtocol class]]; 33 | } 34 | 35 | + (void)handleNextRequestForURL:(NSURL *)URL 36 | usingBlock:(void (^)(AFMockURLProtocol * protocol))block; 37 | { 38 | _matchingURL = URL; 39 | _initializationCallback = block; 40 | } 41 | 42 | #pragma mark - NSURLProtocol 43 | 44 | + (BOOL)canInitWithRequest:(NSURLRequest *)request { 45 | return [request.URL isEqual:_matchingURL] && _initializationCallback; 46 | } 47 | 48 | + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { 49 | return request; 50 | } 51 | 52 | + (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a 53 | toRequest:(NSURLRequest *)b 54 | { 55 | return NO; 56 | } 57 | 58 | - (id)initWithRequest:(NSURLRequest *)request 59 | cachedResponse:(NSCachedURLResponse *)cachedResponse 60 | client:(id )client 61 | { 62 | self = [super initWithRequest:request cachedResponse:cachedResponse client:client]; 63 | if (!self) { 64 | return nil; 65 | } 66 | 67 | if (_initializationCallback) { 68 | self = [OCMockObject partialMockForObject:self]; 69 | 70 | _initializationCallback(self); 71 | } 72 | 73 | _initializationCallback = nil; 74 | _matchingURL = nil; 75 | 76 | return self; 77 | } 78 | 79 | - (void)startLoading {} 80 | 81 | - (void)stopLoading {} 82 | 83 | #pragma mark - NSURLAuthenticationChallengeSender 84 | 85 | - (void)cancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { 86 | [self doesNotRecognizeSelector:_cmd]; 87 | } 88 | 89 | - (void)continueWithoutCredentialForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { 90 | [self doesNotRecognizeSelector:_cmd]; 91 | } 92 | 93 | - (void)useCredential:(NSURLCredential *)credential 94 | forAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { 95 | [self doesNotRecognizeSelector:_cmd]; 96 | } 97 | 98 | - (void)performDefaultHandlingForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { 99 | [self doesNotRecognizeSelector:_cmd]; 100 | } 101 | 102 | - (void)rejectProtectionSpaceAndContinueWithChallenge:(NSURLAuthenticationChallenge *)challenge { 103 | [self doesNotRecognizeSelector:_cmd]; 104 | } 105 | 106 | @end 107 | -------------------------------------------------------------------------------- /Example/Classes/Controllers/GlobalTimelineViewController.m: -------------------------------------------------------------------------------- 1 | // GlobalTimelineViewController.m 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "GlobalTimelineViewController.h" 24 | 25 | #import "Post.h" 26 | 27 | #import "PostTableViewCell.h" 28 | 29 | #import "UIRefreshControl+AFNetworking.h" 30 | #import "UIAlertView+AFNetworking.h" 31 | 32 | @interface GlobalTimelineViewController () 33 | @property (readwrite, nonatomic, strong) NSArray *posts; 34 | @end 35 | 36 | @implementation GlobalTimelineViewController 37 | 38 | - (void)reload:(__unused id)sender { 39 | self.navigationItem.rightBarButtonItem.enabled = NO; 40 | 41 | NSURLSessionTask *task = [Post globalTimelinePostsWithBlock:^(NSArray *posts, NSError *error) { 42 | if (!error) { 43 | self.posts = posts; 44 | [self.tableView reloadData]; 45 | } 46 | }]; 47 | 48 | [UIAlertView showAlertViewForTaskWithErrorOnCompletion:task delegate:nil]; 49 | [self.refreshControl setRefreshingWithStateOfTask:task]; 50 | } 51 | 52 | #pragma mark - UIViewController 53 | 54 | - (void)viewDidLoad { 55 | [super viewDidLoad]; 56 | 57 | self.title = NSLocalizedString(@"AFNetworking", nil); 58 | 59 | self.refreshControl = [[UIRefreshControl alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.frame.size.width, 100.0f)]; 60 | [self.refreshControl addTarget:self action:@selector(reload:) forControlEvents:UIControlEventValueChanged]; 61 | [self.tableView.tableHeaderView addSubview:self.refreshControl]; 62 | 63 | self.tableView.rowHeight = 70.0f; 64 | 65 | [self reload:nil]; 66 | } 67 | 68 | #pragma mark - UITableViewDataSource 69 | 70 | - (NSInteger)tableView:(__unused UITableView *)tableView 71 | numberOfRowsInSection:(__unused NSInteger)section 72 | { 73 | return (NSInteger)[self.posts count]; 74 | } 75 | 76 | - (UITableViewCell *)tableView:(UITableView *)tableView 77 | cellForRowAtIndexPath:(NSIndexPath *)indexPath 78 | { 79 | static NSString *CellIdentifier = @"Cell"; 80 | 81 | PostTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 82 | if (!cell) { 83 | cell = [[PostTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 84 | } 85 | 86 | cell.post = self.posts[(NSUInteger)indexPath.row]; 87 | 88 | return cell; 89 | } 90 | 91 | #pragma mark - UITableViewDelegate 92 | 93 | - (CGFloat)tableView:(__unused UITableView *)tableView 94 | heightForRowAtIndexPath:(NSIndexPath *)indexPath 95 | { 96 | return [PostTableViewCell heightForCellWithPost:self.posts[(NSUInteger)indexPath.row]]; 97 | } 98 | 99 | - (void)tableView:(UITableView *)tableView 100 | didSelectRowAtIndexPath:(NSIndexPath *)indexPath 101 | { 102 | [tableView deselectRowAtIndexPath:indexPath animated:YES]; 103 | } 104 | 105 | @end 106 | -------------------------------------------------------------------------------- /Example/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // AppDelegate.m 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "AppDelegate.h" 24 | 25 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 26 | #import "GlobalTimelineViewController.h" 27 | 28 | #import "AFNetworkActivityIndicatorManager.h" 29 | 30 | @implementation AppDelegate 31 | 32 | - (BOOL)application:(__unused UIApplication *)application 33 | didFinishLaunchingWithOptions:(__unused NSDictionary *)launchOptions 34 | { 35 | NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil]; 36 | [NSURLCache setSharedURLCache:URLCache]; 37 | 38 | [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; 39 | 40 | UITableViewController *viewController = [[GlobalTimelineViewController alloc] initWithStyle:UITableViewStylePlain]; 41 | self.navigationController = [[UINavigationController alloc] initWithRootViewController:viewController]; 42 | self.navigationController.navigationBar.tintColor = [UIColor darkGrayColor]; 43 | 44 | self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 45 | self.window.backgroundColor = [UIColor whiteColor]; 46 | self.window.rootViewController = self.navigationController; 47 | [self.window makeKeyAndVisible]; 48 | 49 | return YES; 50 | } 51 | 52 | @end 53 | #else 54 | #import "Post.h" 55 | #import "User.h" 56 | 57 | @implementation AppDelegate 58 | 59 | - (void)applicationDidFinishLaunching:(NSNotification *)notification { 60 | NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil]; 61 | [NSURLCache setSharedURLCache:URLCache]; 62 | 63 | [self.window makeKeyAndOrderFront:self]; 64 | 65 | [Post globalTimelinePostsWithBlock:^(NSArray *posts, NSError *error) { 66 | if (error) { 67 | NSAlert *alert = [[NSAlert alloc] init]; 68 | alert.messageText = NSLocalizedString(@"Error", nil); 69 | alert.informativeText = error.localizedDescription; 70 | [alert addButtonWithTitle:NSLocalizedString(@"OK", nil)]; 71 | [alert runModal]; 72 | } 73 | 74 | self.postsArrayController.content = posts; 75 | }]; 76 | 77 | [[NSNotificationCenter defaultCenter] addObserverForName:kUserProfileImageDidLoadNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) { 78 | [self.tableView reloadData]; 79 | }]; 80 | } 81 | 82 | - (BOOL)applicationShouldHandleReopen:(NSApplication *)application 83 | hasVisibleWindows:(BOOL)flag 84 | { 85 | [self.window makeKeyAndOrderFront:self]; 86 | 87 | return YES; 88 | } 89 | 90 | @end 91 | #endif 92 | -------------------------------------------------------------------------------- /UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h: -------------------------------------------------------------------------------- 1 | // AFNetworkActivityIndicatorManager.h 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #import 25 | 26 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 27 | 28 | #import 29 | 30 | NS_ASSUME_NONNULL_BEGIN 31 | 32 | /** 33 | `AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a network request operation has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero. 34 | 35 | You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code: 36 | 37 | [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; 38 | 39 | By setting `enabled` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself. 40 | 41 | See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information: 42 | http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44 43 | */ 44 | NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropriate instead.") 45 | @interface AFNetworkActivityIndicatorManager : NSObject 46 | 47 | /** 48 | A Boolean value indicating whether the manager is enabled. 49 | 50 | If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO. 51 | */ 52 | @property (nonatomic, assign, getter = isEnabled) BOOL enabled; 53 | 54 | /** 55 | A Boolean value indicating whether the network activity indicator is currently displayed in the status bar. 56 | */ 57 | @property (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible; 58 | 59 | /** 60 | Returns the shared network activity indicator manager object for the system. 61 | 62 | @return The systemwide network activity indicator manager. 63 | */ 64 | + (instancetype)sharedManager; 65 | 66 | /** 67 | Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator. 68 | */ 69 | - (void)incrementActivityCount; 70 | 71 | /** 72 | Decrements the number of active network requests. If this number becomes zero after decrementing, this will stop animating the status bar network activity indicator. 73 | */ 74 | - (void)decrementActivityCount; 75 | 76 | @end 77 | 78 | NS_ASSUME_NONNULL_END 79 | 80 | #endif 81 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | This document contains information and guidelines about contributing to this project. 4 | Please read it before you start participating. 5 | 6 | **Topics** 7 | 8 | * [Asking Questions](#asking-questions) 9 | * [Reporting Security Issues](#reporting-security-issues) 10 | * [Reporting Issues](#reporting-other-issues) 11 | * [Developers Certificate of Origin](#developers-certificate-of-origin) 12 | * [Code of Conduct](#code-of-conduct) 13 | 14 | ## Asking Questions 15 | 16 | We don't use GitHub as a support forum. 17 | For any usage questions that are not specific to the project itself, 18 | please ask on [Stack Overflow](https://stackoverflow.com) instead. 19 | By doing so, you'll be more likely to quickly solve your problem, 20 | and you'll allow anyone else with the same question to find the answer. 21 | This also allows maintainers to focus on improving the project for others. 22 | 23 | ## Reporting Security Issues 24 | 25 | The Alamofire Software Foundation takes security seriously. 26 | If you discover a security issue, please bring it to our attention right away! 27 | 28 | Please **DO NOT** file a public issue, 29 | instead send your report privately to . 30 | This will help ensure that any vulnerabilities that _are_ found 31 | can be [disclosed responsibly](http://en.wikipedia.org/wiki/Responsible_disclosure) 32 | to any affected parties. 33 | 34 | ## Reporting Other Issues 35 | 36 | A great way to contribute to the project 37 | is to send a detailed issue when you encounter an problem. 38 | We always appreciate a well-written, thorough bug report. 39 | 40 | Check that the project issues database 41 | doesn't already include that problem or suggestion before submitting an issue. 42 | If you find a match, add a quick "+1" or "I have this problem too." 43 | Doing this helps prioritize the most common problems and requests. 44 | 45 | When reporting issues, please include the following: 46 | 47 | * The version of Xcode you're using 48 | * The version of iOS or OS X you're targeting 49 | * The full output of any stack trace or compiler error 50 | * A code snippet that reproduces the described behavior, if applicable 51 | * Any other details that would be useful in understanding the problem 52 | 53 | This information will help us review and fix your issue faster. 54 | 55 | ## Developer's Certificate of Origin 1.1 56 | 57 | By making a contribution to this project, I certify that: 58 | 59 | - (a) The contribution was created in whole or in part by me and I 60 | have the right to submit it under the open source license 61 | indicated in the file; or 62 | 63 | - (b) The contribution is based upon previous work that, to the best 64 | of my knowledge, is covered under an appropriate open source 65 | license and I have the right under that license to submit that 66 | work with modifications, whether created in whole or in part 67 | by me, under the same open source license (unless I am 68 | permitted to submit under a different license), as indicated 69 | in the file; or 70 | 71 | - (c) The contribution was provided directly to me by some other 72 | person who certified (a), (b) or (c) and I have not modified 73 | it. 74 | 75 | - (d) I understand and agree that this project and the contribution 76 | are public and that a record of the contribution (including all 77 | personal information I submit with it, including my sign-off) is 78 | maintained indefinitely and may be redistributed consistent with 79 | this project or the open source license(s) involved. 80 | 81 | ## Code of Conduct 82 | 83 | The Code of Conduct governs how we behave in public or in private 84 | whenever the project will be judged by our actions. 85 | We expect it to be honored by everyone who contributes to this project. 86 | 87 | See [CONDUCT.md](https://github.com/Alamofire/Foundation/blob/master/CONDUCT.md) for details. 88 | 89 | --- 90 | 91 | *Some of the ideas and wording for the statements above were based on work by the [Docker](https://github.com/docker/docker/blob/master/CONTRIBUTING.md) and [Linux](http://elinux.org/Developer_Certificate_Of_Origin) communities. We commend them for their efforts to facilitate collaboration in their projects.* 92 | -------------------------------------------------------------------------------- /Example/Today Extension/TodayViewController.m: -------------------------------------------------------------------------------- 1 | // TodayViewController.m 2 | // 3 | // Copyright (c) 2015 Brian Nickel 4 | // 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | 24 | #import 25 | #import "TodayViewController.h" 26 | #import "Post.h" 27 | #import "User.h" 28 | #import "UIImageView+AFNetworking.h" 29 | 30 | @interface TodayViewController () 31 | @property (strong, nonatomic) IBOutlet UIImageView *imageView; 32 | @property (strong, nonatomic) IBOutlet UILabel *titleLabel; 33 | @property (strong, nonatomic) IBOutlet UILabel *bodyLabel; 34 | @property (nonatomic, strong) Post *post; 35 | @end 36 | 37 | @implementation TodayViewController 38 | 39 | - (void)viewDidLoad { 40 | [super viewDidLoad]; 41 | 42 | NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil]; 43 | [NSURLCache setSharedURLCache:URLCache]; 44 | self.post = [self loadSavedPost]; 45 | } 46 | 47 | - (void)viewWillAppear:(BOOL)animated { 48 | [super viewWillAppear:animated]; 49 | } 50 | 51 | - (void)widgetPerformUpdateWithCompletionHandler:(void (^)(NCUpdateResult))completionHandler { 52 | [Post globalTimelinePostsWithBlock:^(NSArray *posts, NSError *error) { 53 | if (!error) { 54 | 55 | self.post = posts.firstObject; 56 | [self savePost:self.post]; 57 | 58 | if (completionHandler) { 59 | completionHandler(self.post != nil ? NCUpdateResultNewData : NCUpdateResultNoData); 60 | } 61 | 62 | } else { 63 | if (completionHandler) { 64 | completionHandler(NCUpdateResultFailed); 65 | } 66 | } 67 | }]; 68 | } 69 | 70 | - (void)setPost:(Post *)post { 71 | _post = post; 72 | 73 | self.titleLabel.hidden = post == nil; 74 | self.bodyLabel.hidden = post == nil; 75 | self.imageView.hidden = post == nil; 76 | 77 | if (post == nil) { 78 | return; 79 | } 80 | 81 | self.titleLabel.text = _post.user.username; 82 | self.bodyLabel.text = _post.text; 83 | [self.imageView setImageWithURL:_post.user.avatarImageURL placeholderImage:[UIImage imageNamed:@"profile-image-placeholder"]]; 84 | } 85 | 86 | - (void)savePost:(Post *)post { 87 | 88 | if (post == nil) { 89 | [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"AF.post"]; 90 | [[NSUserDefaults standardUserDefaults] synchronize]; 91 | return; 92 | } 93 | 94 | NSData *postData = [NSKeyedArchiver archivedDataWithRootObject:post]; 95 | [[NSUserDefaults standardUserDefaults] setObject:postData forKey:@"AF.post"]; 96 | [[NSUserDefaults standardUserDefaults] synchronize]; 97 | } 98 | 99 | - (Post *)loadSavedPost { 100 | NSData *postData = [[NSUserDefaults standardUserDefaults] objectForKey:@"AF.post"]; 101 | if (postData == nil || ![postData isKindOfClass:[NSData class]]) { 102 | return nil; 103 | } 104 | 105 | return [NSKeyedUnarchiver unarchiveObjectWithData:postData]; 106 | } 107 | 108 | @end 109 | -------------------------------------------------------------------------------- /AFNetworking/AFHTTPRequestOperation.h: -------------------------------------------------------------------------------- 1 | // AFHTTPRequestOperation.h 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | #import "AFURLConnectionOperation.h" 24 | 25 | NS_ASSUME_NONNULL_BEGIN 26 | 27 | /** 28 | `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. 29 | */ 30 | @interface AFHTTPRequestOperation : AFURLConnectionOperation 31 | 32 | ///------------------------------------------------ 33 | /// @name Getting HTTP URL Connection Information 34 | ///------------------------------------------------ 35 | 36 | /** 37 | The last HTTP response received by the operation's connection. 38 | */ 39 | @property (readonly, nonatomic, strong, nullable) NSHTTPURLResponse *response; 40 | 41 | /** 42 | 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 an AFHTTPResponse serializer, which uses the raw data as its response 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. 43 | 44 | @warning `responseSerializer` must not be `nil`. Setting a response serializer will clear out any cached value 45 | */ 46 | @property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; 47 | 48 | /** 49 | An object constructed by the `responseSerializer` from the response and response data. Returns `nil` unless the operation `isFinished`, has a `response`, and has `responseData` with non-zero content length. If an error occurs during serialization, `nil` will be returned, and the `error` property will be populated with the serialization error. 50 | */ 51 | @property (readonly, nonatomic, strong, nullable) id responseObject; 52 | 53 | ///----------------------------------------------------------- 54 | /// @name Setting Completion Block Success / Failure Callbacks 55 | ///----------------------------------------------------------- 56 | 57 | /** 58 | Sets the `completionBlock` property with a block that executes either the specified success or failure block, depending on the state of the request on completion. If `error` returns a value, which can be caused by an unacceptable status code or content type, then `failure` is executed. Otherwise, `success` is executed. 59 | 60 | This method should be overridden in subclasses in order to specify the response object passed into the success block. 61 | 62 | @param success The block to be executed on the completion of a successful request. This block has no return value and takes two arguments: the receiver operation and the object constructed from the response data of the request. 63 | @param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that occurred during the request. 64 | */ 65 | - (void)setCompletionBlockWithSuccess:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success 66 | failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; 67 | 68 | @end 69 | 70 | NS_ASSUME_NONNULL_END 71 | -------------------------------------------------------------------------------- /Tests/Tests/1.0 Tests/AFJSONRequestOperationTests.m: -------------------------------------------------------------------------------- 1 | // AFJSONRequestOperationTests.m 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFNetworkingTests.h" 23 | 24 | @interface AFJSONRequestOperationTests : SenTestCase 25 | @property (readwrite, nonatomic, strong) NSURL *baseURL; 26 | @end 27 | 28 | @implementation AFJSONRequestOperationTests 29 | 30 | - (void)setUp { 31 | self.baseURL = [NSURL URLWithString:AFNetworkingTestsBaseURLString]; 32 | } 33 | 34 | - (void)testThatJSONRequestOperationAcceptsApplicationJSON { 35 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=application/json" relativeToURL:self.baseURL]]; 36 | AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request]; 37 | 38 | [operation start]; 39 | expect([operation isFinished]).will.beTruthy(); 40 | expect(operation.error).will.beNil(); 41 | } 42 | 43 | - (void)testThatJSONRequestOperationAcceptsTextJSON { 44 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=text/json" relativeToURL:self.baseURL]]; 45 | AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request]; 46 | 47 | [operation start]; 48 | expect([operation isFinished]).will.beTruthy(); 49 | expect(operation.error).will.beNil(); 50 | } 51 | 52 | - (void)testThatJSONRequestOperationAcceptsTextJavascript { 53 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=text/javascript" relativeToURL:self.baseURL]]; 54 | AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request]; 55 | 56 | [operation start]; 57 | expect([operation isFinished]).will.beTruthy(); 58 | expect(operation.error).will.beNil(); 59 | } 60 | 61 | - (void)testThatJSONRequestOperationAcceptsCustomContentType { 62 | [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"application/customjson"]]; 63 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=application/customjson" relativeToURL:self.baseURL]]; 64 | AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request]; 65 | 66 | [operation start]; 67 | expect([operation isFinished]).will.beTruthy(); 68 | expect(operation.error).will.beNil(); 69 | } 70 | 71 | - (void)testThatJSONRequestOperationDoesNotAcceptInvalidContentType { 72 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=application/no-json" relativeToURL:self.baseURL]]; 73 | AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request]; 74 | 75 | [operation start]; 76 | expect([operation isFinished]).will.beTruthy(); 77 | expect(operation.error).willNot.beNil(); 78 | } 79 | 80 | - (void)testThatJSONResponseObjectIsNotNilWhenValidJSONIsReturned { 81 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=application/json" relativeToURL:self.baseURL]]; 82 | AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request]; 83 | 84 | [operation start]; 85 | expect([operation isFinished]).will.beTruthy(); 86 | expect(operation.responseJSON).willNot.beNil(); 87 | } 88 | 89 | - (void)testThatJSONResponseObjectIsNilWhenErrorOccurs { 90 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/status/404" relativeToURL:self.baseURL]]; 91 | AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request]; 92 | 93 | [operation start]; 94 | expect([operation isFinished]).will.beTruthy(); 95 | expect(operation.responseJSON).will.beNil(); 96 | } 97 | 98 | @end 99 | -------------------------------------------------------------------------------- /Tests/Tests/AFNetworkActivityManagerTests.m: -------------------------------------------------------------------------------- 1 | // AFNetworkActivityManagerTests.m 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFTestCase.h" 23 | 24 | #import "AFNetworkActivityIndicatorManager.h" 25 | #import "AFHTTPRequestOperation.h" 26 | 27 | @interface AFNetworkActivityManagerTests : AFTestCase 28 | @property (nonatomic, strong) AFNetworkActivityIndicatorManager *networkActivityIndicatorManager; 29 | @property (nonatomic, assign) BOOL isNetworkActivityIndicatorVisible; 30 | @property (nonatomic, strong) id mockApplication; 31 | @end 32 | 33 | #pragma mark - 34 | 35 | @implementation AFNetworkActivityManagerTests 36 | 37 | - (void)setUp { 38 | [super setUp]; 39 | 40 | self.networkActivityIndicatorManager = [[AFNetworkActivityIndicatorManager alloc] init]; 41 | self.networkActivityIndicatorManager.enabled = YES; 42 | 43 | self.mockApplication = [OCMockObject mockForClass:[UIApplication class]]; 44 | [[[self.mockApplication stub] andReturn:self.mockApplication] sharedApplication]; 45 | 46 | [[[self.mockApplication stub] andDo:^(NSInvocation *invocation) { 47 | [invocation setReturnValue:(void *)&_isNetworkActivityIndicatorVisible]; 48 | }] isNetworkActivityIndicatorVisible]; 49 | 50 | [[[self.mockApplication stub] andDo:^(NSInvocation *invocation) { 51 | [invocation getArgument:&_isNetworkActivityIndicatorVisible atIndex:2]; 52 | }] setNetworkActivityIndicatorVisible:YES]; 53 | } 54 | 55 | - (void)tearDown { 56 | [super tearDown]; 57 | [self.mockApplication stopMocking]; 58 | 59 | self.mockApplication = nil; 60 | self.networkActivityIndicatorManager = nil; 61 | } 62 | 63 | #pragma mark - 64 | 65 | - (void)testThatNetworkActivityIndicatorTurnsOffIndicatorWhenRequestSucceeds { 66 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/get" relativeToURL:self.baseURL]]; 67 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 68 | [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 69 | expect([self.mockApplication isNetworkActivityIndicatorVisible]).will.beFalsy(); 70 | } failure:nil]; 71 | 72 | [operation start]; 73 | 74 | expect([self.mockApplication isNetworkActivityIndicatorVisible]).will.beTruthy(); 75 | } 76 | 77 | - (void)testThatNetworkActivityIndicatorTurnsOffIndicatorWhenRequestFails { 78 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/status/500" relativeToURL:self.baseURL]]; 79 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 80 | [operation setCompletionBlockWithSuccess:nil failure:^(AFHTTPRequestOperation *operation, NSError *error) { 81 | expect([self.mockApplication isNetworkActivityIndicatorVisible]).will.beFalsy(); 82 | }]; 83 | 84 | [operation start]; 85 | 86 | expect([self.mockApplication isNetworkActivityIndicatorVisible]).will.beTruthy(); 87 | } 88 | 89 | - (void)testThatNetworkActivityIsUnchangedWhenManagerIsDisabled { 90 | self.networkActivityIndicatorManager.enabled = NO; 91 | 92 | __block BOOL didChangeNetworkActivityIndicatorVisible = NO; 93 | 94 | [[[self.mockApplication stub] andDo:^(NSInvocation *invocation) { 95 | didChangeNetworkActivityIndicatorVisible = YES; 96 | }] setNetworkActivityIndicatorVisible:YES]; 97 | 98 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/get" relativeToURL:self.baseURL]]; 99 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 100 | [operation setCompletionBlockWithSuccess:nil failure:nil]; 101 | 102 | [operation start]; 103 | 104 | expect(didChangeNetworkActivityIndicatorVisible).will.beFalsy(); 105 | } 106 | 107 | @end 108 | -------------------------------------------------------------------------------- /Example/Classes/Models/User.m: -------------------------------------------------------------------------------- 1 | // User.m 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "User.h" 24 | #import "AFHTTPRequestOperation.h" 25 | 26 | NSString * const kUserProfileImageDidLoadNotification = @"com.alamofire.user.profile-image.loaded"; 27 | 28 | @interface User () 29 | @property (readwrite, nonatomic, assign) NSUInteger userID; 30 | @property (readwrite, nonatomic, copy) NSString *username; 31 | @property (readwrite, nonatomic, copy) NSString *avatarImageURLString; 32 | 33 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 34 | @property (readwrite, nonatomic, strong) AFHTTPRequestOperation *avatarImageRequestOperation; 35 | #endif 36 | @end 37 | 38 | @implementation User 39 | 40 | - (instancetype)initWithAttributes:(NSDictionary *)attributes { 41 | self = [super init]; 42 | if (!self) { 43 | return nil; 44 | } 45 | 46 | self.userID = (NSUInteger)[[attributes valueForKeyPath:@"id"] integerValue]; 47 | self.username = [attributes valueForKeyPath:@"username"]; 48 | self.avatarImageURLString = [attributes valueForKeyPath:@"avatar_image.url"]; 49 | 50 | return self; 51 | } 52 | 53 | - (NSURL *)avatarImageURL { 54 | return [NSURL URLWithString:self.avatarImageURLString]; 55 | } 56 | 57 | #pragma mark - 58 | 59 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 60 | 61 | + (NSOperationQueue *)sharedProfileImageRequestOperationQueue { 62 | static NSOperationQueue *_sharedProfileImageRequestOperationQueue = nil; 63 | static dispatch_once_t onceToken; 64 | dispatch_once(&onceToken, ^{ 65 | _sharedProfileImageRequestOperationQueue = [[NSOperationQueue alloc] init]; 66 | [_sharedProfileImageRequestOperationQueue setMaxConcurrentOperationCount:8]; 67 | }); 68 | 69 | return _sharedProfileImageRequestOperationQueue; 70 | } 71 | 72 | - (NSImage *)profileImage { 73 | if (!_profileImage && !_avatarImageRequestOperation) { 74 | NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:self.avatarImageURL]; 75 | [mutableRequest setValue:@"image/*" forHTTPHeaderField:@"Accept"]; 76 | AFHTTPRequestOperation *imageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:mutableRequest]; 77 | imageRequestOperation.responseSerializer = [AFImageResponseSerializer serializer]; 78 | [imageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, NSImage *responseImage) { 79 | self.profileImage = responseImage; 80 | 81 | _avatarImageRequestOperation = nil; 82 | 83 | [[NSNotificationCenter defaultCenter] postNotificationName:kUserProfileImageDidLoadNotification object:self userInfo:nil]; 84 | } failure:nil]; 85 | 86 | [imageRequestOperation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) { 87 | return [[NSCachedURLResponse alloc] initWithResponse:cachedResponse.response data:cachedResponse.data userInfo:cachedResponse.userInfo storagePolicy:NSURLCacheStorageAllowed]; 88 | }]; 89 | 90 | _avatarImageRequestOperation = imageRequestOperation; 91 | 92 | [[[self class] sharedProfileImageRequestOperationQueue] addOperation:_avatarImageRequestOperation]; 93 | } 94 | 95 | return _profileImage; 96 | } 97 | 98 | #endif 99 | 100 | @end 101 | 102 | @implementation User (NSCoding) 103 | 104 | - (void)encodeWithCoder:(NSCoder *)aCoder { 105 | [aCoder encodeInteger:(NSInteger)self.userID forKey:@"AF.userID"]; 106 | [aCoder encodeObject:self.username forKey:@"AF.username"]; 107 | [aCoder encodeObject:self.avatarImageURLString forKey:@"AF.avatarImageURLString"]; 108 | } 109 | 110 | - (instancetype)initWithCoder:(NSCoder *)aDecoder { 111 | self = [super init]; 112 | if (!self) { 113 | return nil; 114 | } 115 | 116 | self.userID = (NSUInteger)[aDecoder decodeIntegerForKey:@"AF.userID"]; 117 | self.username = [aDecoder decodeObjectOfClass:[NSString class] forKey:@"AF.username"]; 118 | self.avatarImageURLString = [aDecoder decodeObjectOfClass:[User class] forKey:@"AF.avatarImageURLString"]; 119 | 120 | return self; 121 | } 122 | 123 | + (BOOL)supportsSecureCoding { 124 | return YES; 125 | } 126 | 127 | @end 128 | -------------------------------------------------------------------------------- /AFNetworking.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 7 | 9 | 10 | 13 | 15 | 16 | 18 | 19 | 21 | 22 | 24 | 25 | 27 | 28 | 30 | 31 | 32 | 35 | 37 | 38 | 40 | 41 | 43 | 44 | 46 | 47 | 48 | 51 | 53 | 54 | 56 | 57 | 58 | 61 | 63 | 64 | 66 | 67 | 68 | 71 | 73 | 74 | 76 | 77 | 79 | 80 | 82 | 83 | 84 | 85 | 88 | 90 | 91 | 93 | 94 | 96 | 97 | 99 | 100 | 102 | 103 | 105 | 106 | 108 | 109 | 111 | 112 | 114 | 115 | 117 | 118 | 120 | 121 | 123 | 124 | 126 | 127 | 129 | 130 | 132 | 133 | 135 | 136 | 138 | 139 | 140 | 142 | 143 | 145 | 146 | 148 | 149 | 151 | 152 | 153 | -------------------------------------------------------------------------------- /AFNetworking/AFSecurityPolicy.h: -------------------------------------------------------------------------------- 1 | // AFSecurityPolicy.h 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | #import 24 | 25 | typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { 26 | AFSSLPinningModeNone, 27 | AFSSLPinningModePublicKey, 28 | AFSSLPinningModeCertificate, 29 | }; 30 | 31 | /** 32 | `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. 33 | 34 | Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled. 35 | */ 36 | 37 | NS_ASSUME_NONNULL_BEGIN 38 | 39 | @interface AFSecurityPolicy : NSObject 40 | 41 | /** 42 | The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`. 43 | */ 44 | @property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode; 45 | 46 | /** 47 | The certificates used to evaluate server trust according to the SSL pinning mode. By default, this property is set to any (`.cer`) certificates included in the app bundle. Note that if you create an array with duplicate certificates, the duplicate certificates will be removed. Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches. 48 | */ 49 | @property (nonatomic, strong, nullable) NSArray *pinnedCertificates; 50 | 51 | /** 52 | Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. 53 | */ 54 | @property (nonatomic, assign) BOOL allowInvalidCertificates; 55 | 56 | /** 57 | Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`. 58 | */ 59 | @property (nonatomic, assign) BOOL validatesDomainName; 60 | 61 | ///----------------------------------------- 62 | /// @name Getting Specific Security Policies 63 | ///----------------------------------------- 64 | 65 | /** 66 | Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys. 67 | 68 | @return The default security policy. 69 | */ 70 | + (instancetype)defaultPolicy; 71 | 72 | ///--------------------- 73 | /// @name Initialization 74 | ///--------------------- 75 | 76 | /** 77 | Creates and returns a security policy with the specified pinning mode. 78 | 79 | @param pinningMode The SSL pinning mode. 80 | 81 | @return A new security policy. 82 | */ 83 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode; 84 | 85 | ///------------------------------ 86 | /// @name Evaluating Server Trust 87 | ///------------------------------ 88 | 89 | /** 90 | Whether or not the specified server trust should be accepted, based on the security policy. 91 | 92 | This method should be used when responding to an authentication challenge from a server. 93 | 94 | @param serverTrust The X.509 certificate trust of the server. 95 | 96 | @return Whether or not to trust the server. 97 | 98 | @warning This method has been deprecated in favor of `-evaluateServerTrust:forDomain:`. 99 | */ 100 | - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust DEPRECATED_ATTRIBUTE; 101 | 102 | /** 103 | Whether or not the specified server trust should be accepted, based on the security policy. 104 | 105 | This method should be used when responding to an authentication challenge from a server. 106 | 107 | @param serverTrust The X.509 certificate trust of the server. 108 | @param domain The domain of serverTrust. If `nil`, the domain will not be validated. 109 | 110 | @return Whether or not to trust the server. 111 | */ 112 | - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust 113 | forDomain:(nullable NSString *)domain; 114 | 115 | @end 116 | 117 | NS_ASSUME_NONNULL_END 118 | 119 | ///---------------- 120 | /// @name Constants 121 | ///---------------- 122 | 123 | /** 124 | ## SSL Pinning Modes 125 | 126 | The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes. 127 | 128 | enum { 129 | AFSSLPinningModeNone, 130 | AFSSLPinningModePublicKey, 131 | AFSSLPinningModeCertificate, 132 | } 133 | 134 | `AFSSLPinningModeNone` 135 | Do not used pinned certificates to validate servers. 136 | 137 | `AFSSLPinningModePublicKey` 138 | Validate host certificates against public keys of pinned certificates. 139 | 140 | `AFSSLPinningModeCertificate` 141 | Validate host certificates against pinned certificates. 142 | */ 143 | -------------------------------------------------------------------------------- /UIKit+AFNetworking/UIAlertView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIAlertView+AFNetworking.h 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #import 25 | 26 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 27 | 28 | #import 29 | 30 | NS_ASSUME_NONNULL_BEGIN 31 | 32 | @class AFURLConnectionOperation; 33 | 34 | /** 35 | This category adds methods to the UIKit framework's `UIAlertView` class. The methods in this category provide support for automatically showing an alert if a session task or request operation finishes with an error. Alert title and message are filled from the corresponding `localizedDescription` & `localizedRecoverySuggestion` or `localizedFailureReason` of the error. 36 | */ 37 | @interface UIAlertView (AFNetworking) 38 | 39 | ///------------------------------------- 40 | /// @name Showing Alert for Session Task 41 | ///------------------------------------- 42 | 43 | /** 44 | Shows an alert view with the error of the specified session task, if any. 45 | 46 | @param task The session task. 47 | @param delegate The alert view delegate. 48 | */ 49 | #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 50 | + (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task 51 | delegate:(nullable id)delegate NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions."); 52 | #endif 53 | 54 | /** 55 | Shows an alert view with the error of the specified session task, if any, with a custom cancel button title and other button titles. 56 | 57 | @param task The session task. 58 | @param delegate The alert view delegate. 59 | @param cancelButtonTitle The title of the cancel button or nil if there is no cancel button. Using this argument is equivalent to setting the cancel button index to the value returned by invoking addButtonWithTitle: specifying this title. 60 | @param otherButtonTitles The title of another button. Using this argument is equivalent to invoking addButtonWithTitle: with this title to add more buttons. Too many buttons can cause the alert view to scroll. For guidelines on the best ways to use an alert in an app, see "Temporary Views". Titles of additional buttons to add to the receiver, terminated with `nil`. 61 | */ 62 | #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 63 | + (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task 64 | delegate:(nullable id)delegate 65 | cancelButtonTitle:(nullable NSString *)cancelButtonTitle 66 | otherButtonTitles:(nullable NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions."); 67 | #endif 68 | 69 | ///------------------------------------------ 70 | /// @name Showing Alert for Request Operation 71 | ///------------------------------------------ 72 | 73 | /** 74 | Shows an alert view with the error of the specified request operation, if any. 75 | 76 | @param operation The request operation. 77 | @param delegate The alert view delegate. 78 | */ 79 | + (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation 80 | delegate:(nullable id)delegate NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions."); 81 | 82 | /** 83 | Shows an alert view with the error of the specified request operation, if any, with a custom cancel button title and other button titles. 84 | 85 | @param operation The request operation. 86 | @param delegate The alert view delegate. 87 | @param cancelButtonTitle The title of the cancel button or nil if there is no cancel button. Using this argument is equivalent to setting the cancel button index to the value returned by invoking addButtonWithTitle: specifying this title. 88 | @param otherButtonTitles The title of another button. Using this argument is equivalent to invoking addButtonWithTitle: with this title to add more buttons. Too many buttons can cause the alert view to scroll. For guidelines on the best ways to use an alert in an app, see "Temporary Views". Titles of additional buttons to add to the receiver, terminated with `nil`. 89 | */ 90 | + (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation 91 | delegate:(nullable id)delegate 92 | cancelButtonTitle:(nullable NSString *)cancelButtonTitle 93 | otherButtonTitles:(nullable NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION NS_EXTENSION_UNAVAILABLE_IOS("Not available in app extensions."); 94 | 95 | @end 96 | 97 | NS_ASSUME_NONNULL_END 98 | 99 | #endif 100 | -------------------------------------------------------------------------------- /Tests/Tests/AFNetworkReachabilityManagerTests.m: -------------------------------------------------------------------------------- 1 | // AFNetworkReachabilityManagerTests.h 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFTestCase.h" 23 | 24 | #import "AFNetworkReachabilityManager.h" 25 | #import 26 | 27 | @interface AFNetworkReachabilityManagerTests : AFTestCase 28 | @property (nonatomic, strong) AFNetworkReachabilityManager *addressReachability; 29 | @property (nonatomic, strong) AFNetworkReachabilityManager *domainReachability; 30 | @end 31 | 32 | @implementation AFNetworkReachabilityManagerTests 33 | 34 | - (void)setUp { 35 | [super setUp]; 36 | 37 | //both of these manager objects should always be reachable when the tests are run 38 | self.domainReachability = [AFNetworkReachabilityManager managerForDomain:@"localhost"]; 39 | 40 | //don't use the shared manager because it retains state between tests 41 | //but recreate it each time in the same way that the shared manager is created 42 | struct sockaddr_in address; 43 | bzero(&address, sizeof(address)); 44 | address.sin_len = sizeof(address); 45 | address.sin_family = AF_INET; 46 | self.addressReachability = [AFNetworkReachabilityManager managerForAddress:&address]; 47 | } 48 | 49 | - (void)tearDown 50 | { 51 | [self.addressReachability stopMonitoring]; 52 | [self.domainReachability stopMonitoring]; 53 | 54 | [super tearDown]; 55 | } 56 | 57 | - (void)testAddressReachabilityStartsInUnknownState { 58 | XCTAssertEqual(self.addressReachability.networkReachabilityStatus, AFNetworkReachabilityStatusUnknown, 59 | @"Reachability should start in an unknown state"); 60 | } 61 | 62 | - (void)testDomainReachabilityStartsInUnknownState { 63 | XCTAssertEqual(self.domainReachability.networkReachabilityStatus, AFNetworkReachabilityStatusUnknown, 64 | @"Reachability should start in an unknown state"); 65 | } 66 | 67 | - (void)verifyReachabilityNotificationGetsPostedWithManager:(AFNetworkReachabilityManager *)manager 68 | { 69 | [self expectationForNotification:AFNetworkingReachabilityDidChangeNotification 70 | object:nil 71 | handler:^BOOL(NSNotification *note) { 72 | AFNetworkReachabilityStatus status; 73 | status = [note.userInfo[AFNetworkingReachabilityNotificationStatusItem] integerValue]; 74 | BOOL reachable = (status == AFNetworkReachabilityStatusReachableViaWiFi 75 | || status == AFNetworkReachabilityStatusReachableViaWWAN); 76 | 77 | XCTAssert(reachable, 78 | @"Expected network to be reachable but got '%@'", 79 | AFStringFromNetworkReachabilityStatus(status)); 80 | XCTAssertEqual(reachable, manager.isReachable, @"Expected status to match 'isReachable'"); 81 | 82 | return YES; 83 | }]; 84 | 85 | [manager startMonitoring]; 86 | 87 | [self waitForExpectationsWithTimeout:5 handler:nil]; 88 | } 89 | 90 | - (void)testAddressReachabilityNotification { 91 | [self verifyReachabilityNotificationGetsPostedWithManager:self.addressReachability]; 92 | } 93 | 94 | - (void)testDomainReachabilityNotification { 95 | [self verifyReachabilityNotificationGetsPostedWithManager:self.domainReachability]; 96 | } 97 | 98 | - (void)verifyReachabilityStatusBlockGetsCalledWithManager:(AFNetworkReachabilityManager *)manager 99 | { 100 | XCTestExpectation *expectation = [self expectationWithDescription:@"reachability status change block gets called"]; 101 | 102 | typeof(manager) __weak weakManager = manager; 103 | [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { 104 | BOOL reachable = (status == AFNetworkReachabilityStatusReachableViaWiFi 105 | || status == AFNetworkReachabilityStatusReachableViaWWAN); 106 | 107 | XCTAssert(reachable, @"Expected network to be reachable but got '%@'", AFStringFromNetworkReachabilityStatus(status)); 108 | XCTAssertEqual(reachable, weakManager.isReachable, @"Expected status to match 'isReachable'"); 109 | 110 | [expectation fulfill]; 111 | }]; 112 | 113 | [manager startMonitoring]; 114 | 115 | [self waitForExpectationsWithTimeout:5 handler:^(NSError *error) { 116 | [manager setReachabilityStatusChangeBlock:nil]; 117 | }]; 118 | } 119 | 120 | - (void)testAddressReachabilityBlock { 121 | [self verifyReachabilityStatusBlockGetsCalledWithManager:self.addressReachability]; 122 | } 123 | 124 | - (void)testDomainReachabilityBlock { 125 | [self verifyReachabilityStatusBlockGetsCalledWithManager:self.domainReachability]; 126 | } 127 | 128 | @end 129 | -------------------------------------------------------------------------------- /UIKit+AFNetworking/UIWebView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIWebView+AFNetworking.h 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #import 25 | 26 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 27 | 28 | #import 29 | 30 | NS_ASSUME_NONNULL_BEGIN 31 | 32 | @class AFHTTPRequestSerializer, AFHTTPResponseSerializer; 33 | @protocol AFURLRequestSerialization, AFURLResponseSerialization; 34 | 35 | /** 36 | This category adds methods to the UIKit framework's `UIWebView` class. The methods in this category provide increased control over the request cycle, including progress monitoring and success / failure handling. 37 | 38 | @discussion When using these category methods, make sure to assign `delegate` for the web view, which implements `–webView:shouldStartLoadWithRequest:navigationType:` appropriately. This allows for tapped links to be loaded through AFNetworking, and can ensure that `canGoBack` & `canGoForward` update their values correctly. 39 | */ 40 | @interface UIWebView (AFNetworking) 41 | 42 | /** 43 | The request serializer used to serialize requests made with the `-loadRequest:...` category methods. By default, this is an instance of `AFHTTPRequestSerializer`. 44 | */ 45 | @property (nonatomic, strong) AFHTTPRequestSerializer * requestSerializer; 46 | 47 | /** 48 | The response serializer used to serialize responses made with the `-loadRequest:...` category methods. By default, this is an instance of `AFHTTPResponseSerializer`. 49 | */ 50 | @property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; 51 | 52 | /** 53 | Asynchronously loads the specified request. 54 | 55 | @param request A URL request identifying the location of the content to load. This must not be `nil`. 56 | @param progress 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 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 main thread. 57 | @param success A block object to be executed when the request finishes loading successfully. This block returns the HTML string to be loaded by the web view, and takes two arguments: the response, and the response string. 58 | @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 single argument: the error that occurred. 59 | */ 60 | - (void)loadRequest:(NSURLRequest *)request 61 | progress:(nullable void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress 62 | success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success 63 | failure:(nullable void (^)(NSError *error))failure; 64 | 65 | /** 66 | Asynchronously loads the data associated with a particular request with a specified MIME type and text encoding. 67 | 68 | @param request A URL request identifying the location of the content to load. This must not be `nil`. 69 | @param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified. 70 | @param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified. 71 | @param progress 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 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 main thread. 72 | @param success A block object to be executed when the request finishes loading successfully. This block returns the data to be loaded by the web view and takes two arguments: the response, and the downloaded data. 73 | @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 single argument: the error that occurred. 74 | */ 75 | - (void)loadRequest:(NSURLRequest *)request 76 | MIMEType:(nullable NSString *)MIMEType 77 | textEncodingName:(nullable NSString *)textEncodingName 78 | progress:(nullable void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress 79 | success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success 80 | failure:(nullable void (^)(NSError *error))failure; 81 | 82 | @end 83 | 84 | NS_ASSUME_NONNULL_END 85 | 86 | #endif 87 | -------------------------------------------------------------------------------- /Tests/Tests/AFJSONSerializationTests.m: -------------------------------------------------------------------------------- 1 | // AFJSONSerializationTests.m 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFTestCase.h" 23 | 24 | #import "AFURLRequestSerialization.h" 25 | #import "AFURLResponseSerialization.h" 26 | 27 | static NSData * AFJSONTestData() { 28 | return [NSJSONSerialization dataWithJSONObject:@{@"foo": @"bar"} options:0 error:nil]; 29 | } 30 | 31 | #pragma mark - 32 | 33 | @interface AFJSONRequestSerializationTests : AFTestCase 34 | @property (nonatomic, strong) AFJSONRequestSerializer *requestSerializer; 35 | @end 36 | 37 | @implementation AFJSONRequestSerializationTests 38 | 39 | - (void)setUp { 40 | self.requestSerializer = [[AFJSONRequestSerializer alloc] init]; 41 | } 42 | 43 | #pragma mark - 44 | 45 | - (void)testThatJSONRequestSerializationHandlesParametersDictionary { 46 | NSDictionary *parameters = @{@"key":@"value"}; 47 | NSError *error = nil; 48 | NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:AFNetworkingTestsBaseURLString parameters:parameters error:&error]; 49 | 50 | XCTAssertNil(error, @"Serialization error should be nil"); 51 | 52 | NSString *body = [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]; 53 | 54 | XCTAssertTrue([@"{\"key\":\"value\"}" isEqualToString:body], @"Parameters were not encoded correctly"); 55 | } 56 | 57 | - (void)testThatJSONRequestSerializationHandlesParametersArray { 58 | NSArray *parameters = @[@{@"key":@"value"}]; 59 | NSError *error = nil; 60 | NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:AFNetworkingTestsBaseURLString parameters:parameters error:&error]; 61 | 62 | XCTAssertNil(error, @"Serialization error should be nil"); 63 | 64 | NSString *body = [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]; 65 | 66 | XCTAssertTrue([@"[{\"key\":\"value\"}]" isEqualToString:body], @"Parameters were not encoded correctly"); 67 | } 68 | 69 | @end 70 | 71 | #pragma mark - 72 | 73 | @interface AFJSONResponseSerializationTests : AFTestCase 74 | @property (nonatomic, strong) AFJSONResponseSerializer *responseSerializer; 75 | @end 76 | 77 | @implementation AFJSONResponseSerializationTests 78 | 79 | - (void)setUp { 80 | [super setUp]; 81 | self.responseSerializer = [AFJSONResponseSerializer serializer]; 82 | } 83 | 84 | #pragma mark - 85 | 86 | - (void)testThatJSONResponseSerializerAcceptsApplicationJSONMimeType { 87 | NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"application/json"}]; 88 | 89 | NSError *error = nil; 90 | [self.responseSerializer validateResponse:response data:AFJSONTestData() error:&error]; 91 | 92 | XCTAssertNil(error, @"Error handling application/json"); 93 | } 94 | 95 | - (void)testThatJSONResponseSerializerAcceptsTextJSONMimeType { 96 | NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/json"}]; 97 | NSError *error = nil; 98 | [self.responseSerializer validateResponse:response data:AFJSONTestData()error:&error]; 99 | 100 | XCTAssertNil(error, @"Error handling text/json"); 101 | } 102 | 103 | - (void)testThatJSONResponseSerializerAcceptsTextJavaScriptMimeType { 104 | NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/javascript"}]; 105 | NSError *error = nil; 106 | [self.responseSerializer validateResponse:response data:AFJSONTestData() error:&error]; 107 | 108 | XCTAssertNil(error, @"Error handling text/javascript"); 109 | } 110 | 111 | - (void)testThatJSONResponseSerializerDoesNotAcceptNonStandardJSONMimeType { 112 | NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"nonstandard/json"}]; 113 | NSError *error = nil; 114 | [self.responseSerializer validateResponse:response data:AFJSONTestData() error:&error]; 115 | 116 | XCTAssertNotNil(error, @"Error should have been thrown for nonstandard/json"); 117 | } 118 | 119 | - (void)testThatJSONResponseSerializerReturnsDictionaryForValidJSONDictionary { 120 | NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/json"}]; 121 | NSError *error = nil; 122 | id responseObject = [self.responseSerializer responseObjectForResponse:response data:AFJSONTestData() error:&error]; 123 | 124 | XCTAssertNil(error, @"Serialization error should be nil"); 125 | XCTAssert([responseObject isKindOfClass:[NSDictionary class]], @"Expected response to be a NSDictionary"); 126 | } 127 | 128 | - (void)testThatJSONResponseSerializerReturnsErrorForInvalidJSON { 129 | NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type":@"text/json"}]; 130 | NSError *error = nil; 131 | [self.responseSerializer responseObjectForResponse:response data:[@"{invalid}" dataUsingEncoding:NSUTF8StringEncoding] error:&error]; 132 | 133 | XCTAssertNotNil(error, @"Serialization error should not be nil"); 134 | } 135 | 136 | @end 137 | -------------------------------------------------------------------------------- /Example/Today Extension/MainInterface.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m: -------------------------------------------------------------------------------- 1 | // AFNetworkActivityIndicatorManager.m 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFNetworkActivityIndicatorManager.h" 23 | 24 | #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) 25 | 26 | #import "AFHTTPRequestOperation.h" 27 | 28 | #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 29 | #import "AFURLSessionManager.h" 30 | #endif 31 | 32 | static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17; 33 | 34 | static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) { 35 | if ([[notification object] isKindOfClass:[AFURLConnectionOperation class]]) { 36 | return [(AFURLConnectionOperation *)[notification object] request]; 37 | } 38 | 39 | #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 40 | if ([[notification object] respondsToSelector:@selector(originalRequest)]) { 41 | return [(NSURLSessionTask *)[notification object] originalRequest]; 42 | } 43 | #endif 44 | 45 | return nil; 46 | } 47 | 48 | @interface AFNetworkActivityIndicatorManager () 49 | @property (readwrite, nonatomic, assign) NSInteger activityCount; 50 | @property (readwrite, nonatomic, strong) NSTimer *activityIndicatorVisibilityTimer; 51 | @property (readonly, nonatomic, getter = isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; 52 | 53 | - (void)updateNetworkActivityIndicatorVisibility; 54 | - (void)updateNetworkActivityIndicatorVisibilityDelayed; 55 | @end 56 | 57 | @implementation AFNetworkActivityIndicatorManager 58 | @dynamic networkActivityIndicatorVisible; 59 | 60 | + (instancetype)sharedManager { 61 | static AFNetworkActivityIndicatorManager *_sharedManager = nil; 62 | static dispatch_once_t oncePredicate; 63 | dispatch_once(&oncePredicate, ^{ 64 | _sharedManager = [[self alloc] init]; 65 | }); 66 | 67 | return _sharedManager; 68 | } 69 | 70 | + (NSSet *)keyPathsForValuesAffectingIsNetworkActivityIndicatorVisible { 71 | return [NSSet setWithObject:@"activityCount"]; 72 | } 73 | 74 | - (id)init { 75 | self = [super init]; 76 | if (!self) { 77 | return nil; 78 | } 79 | 80 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingOperationDidStartNotification object:nil]; 81 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingOperationDidFinishNotification object:nil]; 82 | 83 | #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 84 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidResumeNotification object:nil]; 85 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil]; 86 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidCompleteNotification object:nil]; 87 | #endif 88 | 89 | return self; 90 | } 91 | 92 | - (void)dealloc { 93 | [[NSNotificationCenter defaultCenter] removeObserver:self]; 94 | 95 | [_activityIndicatorVisibilityTimer invalidate]; 96 | } 97 | 98 | - (void)updateNetworkActivityIndicatorVisibilityDelayed { 99 | if (self.enabled) { 100 | // Delay hiding of activity indicator for a short interval, to avoid flickering 101 | if (![self isNetworkActivityIndicatorVisible]) { 102 | [self.activityIndicatorVisibilityTimer invalidate]; 103 | self.activityIndicatorVisibilityTimer = [NSTimer timerWithTimeInterval:kAFNetworkActivityIndicatorInvisibilityDelay target:self selector:@selector(updateNetworkActivityIndicatorVisibility) userInfo:nil repeats:NO]; 104 | [[NSRunLoop mainRunLoop] addTimer:self.activityIndicatorVisibilityTimer forMode:NSRunLoopCommonModes]; 105 | } else { 106 | [self performSelectorOnMainThread:@selector(updateNetworkActivityIndicatorVisibility) withObject:nil waitUntilDone:NO modes:@[NSRunLoopCommonModes]]; 107 | } 108 | } 109 | } 110 | 111 | - (BOOL)isNetworkActivityIndicatorVisible { 112 | return self.activityCount > 0; 113 | } 114 | 115 | - (void)updateNetworkActivityIndicatorVisibility { 116 | [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:[self isNetworkActivityIndicatorVisible]]; 117 | } 118 | 119 | - (void)setActivityCount:(NSInteger)activityCount { 120 | @synchronized(self) { 121 | _activityCount = activityCount; 122 | } 123 | 124 | dispatch_async(dispatch_get_main_queue(), ^{ 125 | [self updateNetworkActivityIndicatorVisibilityDelayed]; 126 | }); 127 | } 128 | 129 | - (void)incrementActivityCount { 130 | [self willChangeValueForKey:@"activityCount"]; 131 | @synchronized(self) { 132 | _activityCount++; 133 | } 134 | [self didChangeValueForKey:@"activityCount"]; 135 | 136 | dispatch_async(dispatch_get_main_queue(), ^{ 137 | [self updateNetworkActivityIndicatorVisibilityDelayed]; 138 | }); 139 | } 140 | 141 | - (void)decrementActivityCount { 142 | [self willChangeValueForKey:@"activityCount"]; 143 | @synchronized(self) { 144 | #pragma clang diagnostic push 145 | #pragma clang diagnostic ignored "-Wgnu" 146 | _activityCount = MAX(_activityCount - 1, 0); 147 | #pragma clang diagnostic pop 148 | } 149 | [self didChangeValueForKey:@"activityCount"]; 150 | 151 | dispatch_async(dispatch_get_main_queue(), ^{ 152 | [self updateNetworkActivityIndicatorVisibilityDelayed]; 153 | }); 154 | } 155 | 156 | - (void)networkRequestDidStart:(NSNotification *)notification { 157 | if ([AFNetworkRequestFromNotification(notification) URL]) { 158 | [self incrementActivityCount]; 159 | } 160 | } 161 | 162 | - (void)networkRequestDidFinish:(NSNotification *)notification { 163 | if ([AFNetworkRequestFromNotification(notification) URL]) { 164 | [self decrementActivityCount]; 165 | } 166 | } 167 | 168 | @end 169 | 170 | #endif 171 | -------------------------------------------------------------------------------- /UIKit+AFNetworking/UIRefreshControl+AFNetworking.m: -------------------------------------------------------------------------------- 1 | // UIRefreshControl+AFNetworking.m 2 | // 3 | // Copyright (c) 2014 AFNetworking (http://afnetworking.com) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "UIRefreshControl+AFNetworking.h" 24 | #import 25 | 26 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 27 | 28 | #import "AFHTTPRequestOperation.h" 29 | 30 | #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 31 | #import "AFURLSessionManager.h" 32 | #endif 33 | 34 | @interface AFRefreshControlNotificationObserver : NSObject 35 | @property (readonly, nonatomic, weak) UIRefreshControl *refreshControl; 36 | - (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl; 37 | 38 | #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 39 | - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; 40 | #endif 41 | - (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation; 42 | 43 | @end 44 | 45 | @implementation UIRefreshControl (AFNetworking) 46 | 47 | - (AFRefreshControlNotificationObserver *)af_notificationObserver { 48 | AFRefreshControlNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver)); 49 | if (notificationObserver == nil) { 50 | notificationObserver = [[AFRefreshControlNotificationObserver alloc] initWithActivityRefreshControl:self]; 51 | objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 52 | } 53 | return notificationObserver; 54 | } 55 | 56 | #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 57 | - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { 58 | [[self af_notificationObserver] setRefreshingWithStateOfTask:task]; 59 | } 60 | #endif 61 | 62 | - (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation { 63 | [[self af_notificationObserver] setRefreshingWithStateOfOperation:operation]; 64 | } 65 | 66 | @end 67 | 68 | @implementation AFRefreshControlNotificationObserver 69 | 70 | - (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl 71 | { 72 | self = [super init]; 73 | if (self) { 74 | _refreshControl = refreshControl; 75 | } 76 | return self; 77 | } 78 | 79 | #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 80 | - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { 81 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 82 | 83 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; 84 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; 85 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; 86 | 87 | if (task) { 88 | #pragma clang diagnostic push 89 | #pragma clang diagnostic ignored "-Wreceiver-is-weak" 90 | #pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" 91 | if (task.state == NSURLSessionTaskStateRunning) { 92 | [self.refreshControl beginRefreshing]; 93 | 94 | [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingTaskDidResumeNotification object:task]; 95 | [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidCompleteNotification object:task]; 96 | [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidSuspendNotification object:task]; 97 | } else { 98 | [self.refreshControl endRefreshing]; 99 | } 100 | #pragma clang diagnostic pop 101 | } 102 | } 103 | #endif 104 | 105 | - (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation { 106 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 107 | 108 | [notificationCenter removeObserver:self name:AFNetworkingOperationDidStartNotification object:nil]; 109 | [notificationCenter removeObserver:self name:AFNetworkingOperationDidFinishNotification object:nil]; 110 | 111 | if (operation) { 112 | #pragma clang diagnostic push 113 | #pragma clang diagnostic ignored "-Wreceiver-is-weak" 114 | #pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" 115 | if (![operation isFinished]) { 116 | if ([operation isExecuting]) { 117 | [self.refreshControl beginRefreshing]; 118 | } else { 119 | [self.refreshControl endRefreshing]; 120 | } 121 | 122 | [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingOperationDidStartNotification object:operation]; 123 | [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingOperationDidFinishNotification object:operation]; 124 | } 125 | #pragma clang diagnostic pop 126 | } 127 | } 128 | 129 | #pragma mark - 130 | 131 | - (void)af_beginRefreshing { 132 | dispatch_async(dispatch_get_main_queue(), ^{ 133 | #pragma clang diagnostic push 134 | #pragma clang diagnostic ignored "-Wreceiver-is-weak" 135 | [self.refreshControl beginRefreshing]; 136 | #pragma clang diagnostic pop 137 | }); 138 | } 139 | 140 | - (void)af_endRefreshing { 141 | dispatch_async(dispatch_get_main_queue(), ^{ 142 | #pragma clang diagnostic push 143 | #pragma clang diagnostic ignored "-Wreceiver-is-weak" 144 | [self.refreshControl endRefreshing]; 145 | #pragma clang diagnostic pop 146 | }); 147 | } 148 | 149 | #pragma mark - 150 | 151 | - (void)dealloc { 152 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 153 | 154 | #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 155 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; 156 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; 157 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; 158 | #endif 159 | 160 | [notificationCenter removeObserver:self name:AFNetworkingOperationDidStartNotification object:nil]; 161 | [notificationCenter removeObserver:self name:AFNetworkingOperationDidFinishNotification object:nil]; 162 | } 163 | 164 | @end 165 | 166 | #endif 167 | -------------------------------------------------------------------------------- /UIKit+AFNetworking/UIWebView+AFNetworking.m: -------------------------------------------------------------------------------- 1 | // UIWebView+AFNetworking.m 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "UIWebView+AFNetworking.h" 23 | 24 | #import 25 | 26 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 27 | 28 | #import "AFHTTPRequestOperation.h" 29 | #import "AFURLResponseSerialization.h" 30 | #import "AFURLRequestSerialization.h" 31 | 32 | @interface UIWebView (_AFNetworking) 33 | @property (readwrite, nonatomic, strong, setter = af_setHTTPRequestOperation:) AFHTTPRequestOperation *af_HTTPRequestOperation; 34 | @end 35 | 36 | @implementation UIWebView (_AFNetworking) 37 | 38 | - (AFHTTPRequestOperation *)af_HTTPRequestOperation { 39 | return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, @selector(af_HTTPRequestOperation)); 40 | } 41 | 42 | - (void)af_setHTTPRequestOperation:(AFHTTPRequestOperation *)operation { 43 | objc_setAssociatedObject(self, @selector(af_HTTPRequestOperation), operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 44 | } 45 | 46 | @end 47 | 48 | #pragma mark - 49 | 50 | @implementation UIWebView (AFNetworking) 51 | 52 | - (AFHTTPRequestSerializer *)requestSerializer { 53 | static AFHTTPRequestSerializer *_af_defaultRequestSerializer = nil; 54 | static dispatch_once_t onceToken; 55 | dispatch_once(&onceToken, ^{ 56 | _af_defaultRequestSerializer = [AFHTTPRequestSerializer serializer]; 57 | }); 58 | 59 | #pragma clang diagnostic push 60 | #pragma clang diagnostic ignored "-Wgnu" 61 | return objc_getAssociatedObject(self, @selector(requestSerializer)) ?: _af_defaultRequestSerializer; 62 | #pragma clang diagnostic pop 63 | } 64 | 65 | - (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { 66 | objc_setAssociatedObject(self, @selector(requestSerializer), requestSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 67 | } 68 | 69 | - (AFHTTPResponseSerializer *)responseSerializer { 70 | static AFHTTPResponseSerializer *_af_defaultResponseSerializer = nil; 71 | static dispatch_once_t onceToken; 72 | dispatch_once(&onceToken, ^{ 73 | _af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer]; 74 | }); 75 | 76 | #pragma clang diagnostic push 77 | #pragma clang diagnostic ignored "-Wgnu" 78 | return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer; 79 | #pragma clang diagnostic pop 80 | } 81 | 82 | - (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { 83 | objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 84 | } 85 | 86 | #pragma mark - 87 | 88 | - (void)loadRequest:(NSURLRequest *)request 89 | progress:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress 90 | success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success 91 | failure:(void (^)(NSError *error))failure 92 | { 93 | [self loadRequest:request MIMEType:nil textEncodingName:nil progress:progress success:^NSData *(NSHTTPURLResponse *response, NSData *data) { 94 | NSStringEncoding stringEncoding = NSUTF8StringEncoding; 95 | if (response.textEncodingName) { 96 | CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName); 97 | if (encoding != kCFStringEncodingInvalidId) { 98 | stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding); 99 | } 100 | } 101 | 102 | NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding]; 103 | if (success) { 104 | string = success(response, string); 105 | } 106 | 107 | return [string dataUsingEncoding:stringEncoding]; 108 | } failure:failure]; 109 | } 110 | 111 | - (void)loadRequest:(NSURLRequest *)request 112 | MIMEType:(NSString *)MIMEType 113 | textEncodingName:(NSString *)textEncodingName 114 | progress:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress 115 | success:(NSData * (^)(NSHTTPURLResponse *response, NSData *data))success 116 | failure:(void (^)(NSError *error))failure 117 | { 118 | NSParameterAssert(request); 119 | 120 | if (self.af_HTTPRequestOperation) { 121 | [self.af_HTTPRequestOperation cancel]; 122 | } 123 | 124 | request = [self.requestSerializer requestBySerializingRequest:request withParameters:nil error:nil]; 125 | 126 | self.af_HTTPRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 127 | self.af_HTTPRequestOperation.responseSerializer = self.responseSerializer; 128 | 129 | __weak __typeof(self)weakSelf = self; 130 | [self.af_HTTPRequestOperation setDownloadProgressBlock:progress]; 131 | [self.af_HTTPRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id __unused responseObject) { 132 | NSData *data = success ? success(operation.response, operation.responseData) : operation.responseData; 133 | 134 | #pragma clang diagnostic push 135 | #pragma clang diagnostic ignored "-Wgnu" 136 | __strong __typeof(weakSelf) strongSelf = weakSelf; 137 | [strongSelf loadData:data MIMEType:(MIMEType ?: [operation.response MIMEType]) textEncodingName:(textEncodingName ?: [operation.response textEncodingName]) baseURL:[operation.response URL]]; 138 | 139 | if ([strongSelf.delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) { 140 | [strongSelf.delegate webViewDidFinishLoad:strongSelf]; 141 | } 142 | 143 | #pragma clang diagnostic pop 144 | } failure:^(AFHTTPRequestOperation * __unused operation, NSError *error) { 145 | if (failure) { 146 | failure(error); 147 | } 148 | }]; 149 | 150 | [self.af_HTTPRequestOperation start]; 151 | 152 | if ([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) { 153 | [self.delegate webViewDidStartLoad:self]; 154 | } 155 | } 156 | 157 | @end 158 | 159 | #endif 160 | -------------------------------------------------------------------------------- /UIKit+AFNetworking/UIAlertView+AFNetworking.m: -------------------------------------------------------------------------------- 1 | // UIAlertView+AFNetworking.m 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "UIAlertView+AFNetworking.h" 23 | 24 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 25 | 26 | #import "AFURLConnectionOperation.h" 27 | 28 | #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 29 | #import "AFURLSessionManager.h" 30 | #endif 31 | 32 | static void AFGetAlertViewTitleAndMessageFromError(NSError *error, NSString * __autoreleasing *title, NSString * __autoreleasing *message) { 33 | if (error.localizedDescription && (error.localizedRecoverySuggestion || error.localizedFailureReason)) { 34 | *title = error.localizedDescription; 35 | 36 | if (error.localizedRecoverySuggestion) { 37 | *message = error.localizedRecoverySuggestion; 38 | } else { 39 | *message = error.localizedFailureReason; 40 | } 41 | } else if (error.localizedDescription) { 42 | *title = NSLocalizedStringFromTable(@"Error", @"AFNetworking", @"Fallback Error Description"); 43 | *message = error.localizedDescription; 44 | } else { 45 | *title = NSLocalizedStringFromTable(@"Error", @"AFNetworking", @"Fallback Error Description"); 46 | *message = [NSString stringWithFormat:NSLocalizedStringFromTable(@"%@ Error: %ld", @"AFNetworking", @"Fallback Error Failure Reason Format"), error.domain, (long)error.code]; 47 | } 48 | } 49 | 50 | @implementation UIAlertView (AFNetworking) 51 | 52 | #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 53 | + (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task 54 | delegate:(id)delegate 55 | { 56 | [self showAlertViewForTaskWithErrorOnCompletion:task delegate:delegate cancelButtonTitle:NSLocalizedStringFromTable(@"Dismiss", @"AFNetworking", @"UIAlertView Cancel Button Title") otherButtonTitles:nil, nil]; 57 | } 58 | 59 | + (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task 60 | delegate:(id)delegate 61 | cancelButtonTitle:(NSString *)cancelButtonTitle 62 | otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION 63 | { 64 | NSMutableArray *mutableOtherTitles = [NSMutableArray array]; 65 | va_list otherButtonTitleList; 66 | va_start(otherButtonTitleList, otherButtonTitles); 67 | { 68 | for (NSString *otherButtonTitle = otherButtonTitles; otherButtonTitle != nil; otherButtonTitle = va_arg(otherButtonTitleList, NSString *)) { 69 | [mutableOtherTitles addObject:otherButtonTitle]; 70 | } 71 | } 72 | va_end(otherButtonTitleList); 73 | 74 | __block __weak id observer = [[NSNotificationCenter defaultCenter] addObserverForName:AFNetworkingTaskDidCompleteNotification object:task queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) { 75 | NSError *error = notification.userInfo[AFNetworkingTaskDidCompleteErrorKey]; 76 | if (error) { 77 | NSString *title, *message; 78 | AFGetAlertViewTitleAndMessageFromError(error, &title, &message); 79 | 80 | UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil, nil]; 81 | for (NSString *otherButtonTitle in mutableOtherTitles) { 82 | [alertView addButtonWithTitle:otherButtonTitle]; 83 | } 84 | [alertView setTitle:title]; 85 | [alertView setMessage:message]; 86 | [alertView show]; 87 | } 88 | 89 | [[NSNotificationCenter defaultCenter] removeObserver:observer]; 90 | }]; 91 | } 92 | #endif 93 | 94 | #pragma mark - 95 | 96 | + (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation 97 | delegate:(id)delegate 98 | { 99 | [self showAlertViewForRequestOperationWithErrorOnCompletion:operation delegate:delegate cancelButtonTitle:NSLocalizedStringFromTable(@"Dismiss", @"AFNetworking", @"UIAlertView Cancel Button Title") otherButtonTitles:nil, nil]; 100 | } 101 | 102 | + (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation 103 | delegate:(id)delegate 104 | cancelButtonTitle:(NSString *)cancelButtonTitle 105 | otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION 106 | { 107 | NSMutableArray *mutableOtherTitles = [NSMutableArray array]; 108 | va_list otherButtonTitleList; 109 | va_start(otherButtonTitleList, otherButtonTitles); 110 | { 111 | for (NSString *otherButtonTitle = otherButtonTitles; otherButtonTitle != nil; otherButtonTitle = va_arg(otherButtonTitleList, NSString *)) { 112 | [mutableOtherTitles addObject:otherButtonTitle]; 113 | } 114 | } 115 | va_end(otherButtonTitleList); 116 | 117 | __block __weak id observer = [[NSNotificationCenter defaultCenter] addObserverForName:AFNetworkingOperationDidFinishNotification object:operation queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) { 118 | 119 | if (notification.object && [notification.object isKindOfClass:[AFURLConnectionOperation class]]) { 120 | NSError *error = [(AFURLConnectionOperation *)notification.object error]; 121 | if (error) { 122 | NSString *title, *message; 123 | AFGetAlertViewTitleAndMessageFromError(error, &title, &message); 124 | 125 | UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil, nil]; 126 | for (NSString *otherButtonTitle in mutableOtherTitles) { 127 | [alertView addButtonWithTitle:otherButtonTitle]; 128 | } 129 | [alertView setTitle:title]; 130 | [alertView setMessage:message]; 131 | [alertView show]; 132 | } 133 | } 134 | 135 | [[NSNotificationCenter defaultCenter] removeObserver:observer]; 136 | }]; 137 | } 138 | 139 | @end 140 | 141 | #endif 142 | -------------------------------------------------------------------------------- /Tests/Tests/AFHTTPSessionManagerTests.m: -------------------------------------------------------------------------------- 1 | // AFHTTPSessionManagerTests.m 2 | // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFTestCase.h" 23 | 24 | #import "AFHTTPSessionManager.h" 25 | 26 | @interface AFHTTPSessionManagerTests : AFTestCase 27 | @property (readwrite, nonatomic, strong) AFHTTPSessionManager *manager; 28 | @end 29 | 30 | @implementation AFHTTPSessionManagerTests 31 | 32 | - (void)setUp { 33 | [super setUp]; 34 | self.manager = [[AFHTTPSessionManager alloc] initWithBaseURL:self.baseURL]; 35 | } 36 | 37 | - (void)tearDown { 38 | [self.manager invalidateSessionCancelingTasks:YES]; 39 | [super tearDown]; 40 | } 41 | 42 | - (void)testThatOperationInvokesCompletionHandlerWithResponseObjectOnSuccess { 43 | __block id blockResponseObject = nil; 44 | __block id blockError = nil; 45 | 46 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/get" relativeToURL:self.baseURL]]; 47 | NSURLSessionDataTask *task = [self.manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { 48 | blockResponseObject = responseObject; 49 | blockError = error; 50 | }]; 51 | 52 | [task resume]; 53 | 54 | expect(task.state).will.equal(NSURLSessionTaskStateCompleted); 55 | expect(blockError).will.beNil(); 56 | expect(blockResponseObject).willNot.beNil(); 57 | } 58 | 59 | - (void)testThatOperationInvokesFailureCompletionBlockWithErrorOnFailure { 60 | __block id blockError = nil; 61 | 62 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/status/404" relativeToURL:self.baseURL]]; 63 | NSURLSessionDataTask *task = [self.manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { 64 | blockError = error; 65 | }]; 66 | 67 | [task resume]; 68 | 69 | expect(task.state).will.equal(NSURLSessionTaskStateCompleted); 70 | expect(blockError).willNot.beNil(); 71 | } 72 | 73 | - (void)testThatRedirectBlockIsCalledWhen302IsEncountered { 74 | __block BOOL success; 75 | __block NSError *blockError = nil; 76 | 77 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/redirect/1" relativeToURL:self.baseURL]]; 78 | NSURLSessionDataTask *task = [self.manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { 79 | blockError = error; 80 | }]; 81 | 82 | [self.manager setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest *(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request) { 83 | if (response) { 84 | success = YES; 85 | } 86 | 87 | return request; 88 | }]; 89 | 90 | [task resume]; 91 | 92 | expect(task.state).will.equal(NSURLSessionTaskStateCompleted); 93 | expect(blockError).will.beNil(); 94 | expect(success).will.beTruthy(); 95 | } 96 | 97 | - (void)testDownloadFileCompletionSpecifiesURLInCompletionWithManagerDidFinishBlock { 98 | __block BOOL managerDownloadFinishedBlockExecuted = NO; 99 | __block BOOL completionBlockExecuted = NO; 100 | __block NSURL *downloadFilePath = nil; 101 | [self.manager setDownloadTaskDidFinishDownloadingBlock:^NSURL *(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location) { 102 | managerDownloadFinishedBlockExecuted = YES; 103 | NSURL *dirURL = [[[NSFileManager defaultManager] URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject]; 104 | return [dirURL URLByAppendingPathComponent:@"t1.file"]; 105 | }]; 106 | 107 | NSURLSessionDownloadTask *downloadTask = [self.manager downloadTaskWithRequest:[NSURLRequest requestWithURL:self.baseURL] 108 | progress:nil 109 | destination:nil 110 | completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { 111 | downloadFilePath = filePath; 112 | completionBlockExecuted = YES; 113 | }]; 114 | [downloadTask resume]; 115 | expect(completionBlockExecuted).will.equal(YES); 116 | expect(managerDownloadFinishedBlockExecuted).will.equal(YES); 117 | expect(downloadFilePath).willNot.beNil(); 118 | } 119 | 120 | - (void)testDownloadFileCompletionSpecifiesURLInCompletionBlock { 121 | __block BOOL destinationBlockExecuted = NO; 122 | __block BOOL completionBlockExecuted = NO; 123 | __block NSURL *downloadFilePath = nil; 124 | 125 | NSURLSessionDownloadTask *downloadTask = [self.manager downloadTaskWithRequest:[NSURLRequest requestWithURL:self.baseURL] 126 | progress:nil 127 | destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { 128 | destinationBlockExecuted = YES; 129 | NSURL *dirURL = [[[NSFileManager defaultManager] URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject]; 130 | return [dirURL URLByAppendingPathComponent:@"t1.file"]; 131 | } 132 | completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { 133 | downloadFilePath = filePath; 134 | completionBlockExecuted = YES; 135 | }]; 136 | [downloadTask resume]; 137 | expect(completionBlockExecuted).will.equal(YES); 138 | expect(destinationBlockExecuted).will.equal(YES); 139 | expect(downloadFilePath).willNot.beNil(); 140 | } 141 | 142 | 143 | 144 | @end 145 | --------------------------------------------------------------------------------