From 9c3eef7fcf1f5e18146fadca59af29c8ea932c19 Mon Sep 17 00:00:00 2001 From: Matthew DeTullio Date: Tue, 15 Mar 2016 17:24:28 -0400 Subject: [PATCH] Add AFNetworking project for ITs. https://github.com/AFNetworking/AFNetworking/tree/32547b02c986d82f4a2d76327c0107afde099719 --- .../projects/AFNetworking/.cocoadocs.yml | 7 + its/plugin/projects/AFNetworking/.gitignore | 29 + .../AFNetworking/AFNetworking.podspec | 79 + .../AFNetworking.xcodeproj/project.pbxproj | 1512 +++++++++++++ .../xcschemes/AFNetworking OS X.xcscheme | 105 + .../xcschemes/AFNetworking iOS.xcscheme | 119 + .../xcschemes/AFNetworking tvOS.xcscheme | 104 + .../xcschemes/AFNetworking watchOS.xcscheme | 80 + .../AFNetworking/AFHTTPSessionManager.h | 295 +++ .../AFNetworking/AFHTTPSessionManager.m | 361 +++ .../AFNetworkReachabilityManager.h | 206 ++ .../AFNetworkReachabilityManager.m | 263 +++ .../AFNetworking/AFNetworking/AFNetworking.h | 41 + .../AFNetworking/AFSecurityPolicy.h | 154 ++ .../AFNetworking/AFSecurityPolicy.m | 353 +++ .../AFNetworking/AFURLRequestSerialization.h | 479 ++++ .../AFNetworking/AFURLRequestSerialization.m | 1376 ++++++++++++ .../AFNetworking/AFURLResponseSerialization.h | 311 +++ .../AFNetworking/AFURLResponseSerialization.m | 803 +++++++ .../AFNetworking/AFURLSessionManager.h | 499 +++++ .../AFNetworking/AFURLSessionManager.m | 1244 ++++++++++ its/plugin/projects/AFNetworking/CHANGELOG.md | 1996 +++++++++++++++++ .../projects/AFNetworking/CONTRIBUTING.md | 96 + .../AFNetworking/Framework/AFNetworking.h | 66 + .../AFNetworking/Framework/Info.plist | 26 + .../AFNetworking/Framework/module.modulemap | 5 + its/plugin/projects/AFNetworking/LICENSE | 19 + its/plugin/projects/AFNetworking/README.md | 320 +++ .../projects/AFNetworking/Tests/Info.plist | 22 + .../ADN.net/ADNNetServerTrustChain/adn_0.cer | Bin 0 -> 1321 bytes .../ADN.net/ADNNetServerTrustChain/adn_1.cer | Bin 0 -> 1628 bytes .../ADN.net/ADNNetServerTrustChain/adn_2.cer | Bin 0 -> 969 bytes ...ifax_Secure_Certificate_Authority_Root.cer | Bin 0 -> 804 bytes .../Google.com/GeoTrust_Global_CA-cross.cer | Bin 0 -> 897 bytes .../Google.com/GeoTrust_Global_CA_Root.cer | Bin 0 -> 856 bytes .../googlecom_0.cer | Bin 0 -> 1965 bytes .../googlecom_1.cer | Bin 0 -> 1012 bytes .../googlecom_0.cer | Bin 0 -> 1965 bytes .../googlecom_1.cer | Bin 0 -> 1012 bytes .../googlecom_2.cer | Bin 0 -> 897 bytes .../Google.com/GoogleInternetAuthorityG2.cer | Bin 0 -> 1012 bytes .../Tests/Resources/Google.com/google.com.cer | Bin 0 -> 1965 bytes .../HTTPBin.org/AddTrust_External_CA_Root.cer | Bin 0 -> 1082 bytes .../COMODO_RSA_Certification_Authority.cer | Bin 0 -> 1400 bytes ...RSA_Domain_Validation_Secure_Server_CA.cer | Bin 0 -> 1548 bytes .../HTTPBinOrgServerTrustChain/httpbin_0.cer | Bin 0 -> 1363 bytes .../HTTPBinOrgServerTrustChain/httpbin_1.cer | Bin 0 -> 1548 bytes .../HTTPBinOrgServerTrustChain/httpbin_2.cer | Bin 0 -> 1400 bytes .../HTTPBinOrgServerTrustChain/httpbin_3.cer | Bin 0 -> 1082 bytes .../HTTPBin.org/httpbinorg_01192017.cer | Bin 0 -> 1363 bytes .../Tests/Resources/SelfSigned/AltName.cer | Bin 0 -> 766 bytes .../Tests/Resources/SelfSigned/NoDomains.cer | Bin 0 -> 747 bytes .../Tests/Resources/SelfSigned/foobar.com.cer | Bin 0 -> 747 bytes .../AFNetworking/Tests/Resources/logo.png | Bin 0 -> 14795 bytes .../AFNetworking/Tests/Tests-Prefix.pch | 9 + .../Tests/AFAutoPurgingImageCacheTests.m | 233 ++ .../Tests/AFCompoundResponseSerializerTests.m | 89 + .../Tests/AFHTTPRequestSerializationTests.m | 214 ++ .../Tests/AFHTTPResponseSerializationTests.m | 89 + .../Tests/Tests/AFHTTPSessionManagerTests.m | 538 +++++ .../Tests/Tests/AFImageDownloaderTests.m | 428 ++++ .../Tests/Tests/AFJSONSerializationTests.m | 171 ++ .../Tests/AFNetworkActivityManagerTests.m | 181 ++ .../Tests/AFNetworkReachabilityManagerTests.m | 124 + .../AFPropertyListResponseSerializerTests.m | 66 + .../Tests/Tests/AFSecurityPolicyTests.m | 654 ++++++ .../AFNetworking/Tests/Tests/AFTestCase.h | 33 + .../AFNetworking/Tests/Tests/AFTestCase.m | 47 + .../Tests/AFUIActivityIndicatorViewTests.m | 111 + .../Tests/Tests/AFUIButtonTests.m | 115 + .../Tests/Tests/AFUIImageViewTests.m | 155 ++ .../Tests/Tests/AFUIRefreshControlTests.m | 110 + .../Tests/Tests/AFUIWebViewTests.m | 85 + .../Tests/Tests/AFURLSessionManagerTests.m | 473 ++++ .../AFAutoPurgingImageCache.h | 149 ++ .../AFAutoPurgingImageCache.m | 201 ++ .../UIKit+AFNetworking/AFImageDownloader.h | 157 ++ .../UIKit+AFNetworking/AFImageDownloader.m | 382 ++++ .../AFNetworkActivityIndicatorManager.h | 103 + .../AFNetworkActivityIndicatorManager.m | 261 +++ .../UIActivityIndicatorView+AFNetworking.h | 48 + .../UIActivityIndicatorView+AFNetworking.m | 124 + .../UIButton+AFNetworking.h | 175 ++ .../UIButton+AFNetworking.m | 305 +++ .../UIKit+AFNetworking/UIImage+AFNetworking.h | 35 + .../UIImageView+AFNetworking.h | 109 + .../UIImageView+AFNetworking.m | 161 ++ .../UIKit+AFNetworking/UIKit+AFNetworking.h | 42 + .../UIProgressView+AFNetworking.h | 64 + .../UIProgressView+AFNetworking.m | 118 + .../UIRefreshControl+AFNetworking.h | 53 + .../UIRefreshControl+AFNetworking.m | 122 + .../UIWebView+AFNetworking.h | 80 + .../UIWebView+AFNetworking.m | 162 ++ .../projects/AFNetworking/fastlane/.env | 10 + .../AFNetworking/fastlane/.env.default | 15 + .../AFNetworking/fastlane/.env.deploy | 14 + .../AFNetworking/fastlane/.env.ios81_xcode7 | 3 + .../projects/AFNetworking/fastlane/.env.ios83 | 2 + .../projects/AFNetworking/fastlane/.env.ios84 | 2 + .../AFNetworking/fastlane/.env.ios90_xcode7 | 3 + .../AFNetworking/fastlane/.env.ios91_xcode71 | 3 + .../projects/AFNetworking/fastlane/.env.ios92 | 2 + .../AFNetworking/fastlane/.env.ios93_xcode73 | 3 + .../projects/AFNetworking/fastlane/.env.osx | 6 + .../AFNetworking/fastlane/.env.tvos90_xcode71 | 6 + .../AFNetworking/fastlane/.env.tvos91 | 6 + .../projects/AFNetworking/fastlane/Fastfile | 337 +++ .../projects/AFNetworking/fastlane/README.md | 196 ++ .../actions/af_build_carthage_frameworks.rb | 64 + .../actions/af_create_github_release.rb | 156 ++ .../actions/af_edit_github_release.rb | 161 ++ .../af_generate_github_milestone_changelog.rb | 225 ++ .../actions/af_get_github_milestone.rb | 129 ++ .../actions/af_insert_text_into_file.rb | 80 + .../fastlane/actions/af_pod_spec_lint.rb | 90 + .../actions/af_push_git_tags_to_remote.rb | 47 + .../actions/af_update_github_milestone.rb | 138 ++ .../af_upload_asset_for_github_release.rb | 134 ++ 119 files changed, 19578 insertions(+) create mode 100644 its/plugin/projects/AFNetworking/.cocoadocs.yml create mode 100644 its/plugin/projects/AFNetworking/.gitignore create mode 100644 its/plugin/projects/AFNetworking/AFNetworking.podspec create mode 100644 its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/project.pbxproj create mode 100644 its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking OS X.xcscheme create mode 100644 its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking iOS.xcscheme create mode 100644 its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking tvOS.xcscheme create mode 100644 its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking watchOS.xcscheme create mode 100644 its/plugin/projects/AFNetworking/AFNetworking/AFHTTPSessionManager.h create mode 100644 its/plugin/projects/AFNetworking/AFNetworking/AFHTTPSessionManager.m create mode 100644 its/plugin/projects/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h create mode 100644 its/plugin/projects/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m create mode 100644 its/plugin/projects/AFNetworking/AFNetworking/AFNetworking.h create mode 100644 its/plugin/projects/AFNetworking/AFNetworking/AFSecurityPolicy.h create mode 100644 its/plugin/projects/AFNetworking/AFNetworking/AFSecurityPolicy.m create mode 100644 its/plugin/projects/AFNetworking/AFNetworking/AFURLRequestSerialization.h create mode 100644 its/plugin/projects/AFNetworking/AFNetworking/AFURLRequestSerialization.m create mode 100644 its/plugin/projects/AFNetworking/AFNetworking/AFURLResponseSerialization.h create mode 100755 its/plugin/projects/AFNetworking/AFNetworking/AFURLResponseSerialization.m create mode 100644 its/plugin/projects/AFNetworking/AFNetworking/AFURLSessionManager.h create mode 100644 its/plugin/projects/AFNetworking/AFNetworking/AFURLSessionManager.m create mode 100644 its/plugin/projects/AFNetworking/CHANGELOG.md create mode 100644 its/plugin/projects/AFNetworking/CONTRIBUTING.md create mode 100644 its/plugin/projects/AFNetworking/Framework/AFNetworking.h create mode 100644 its/plugin/projects/AFNetworking/Framework/Info.plist create mode 100644 its/plugin/projects/AFNetworking/Framework/module.modulemap create mode 100644 its/plugin/projects/AFNetworking/LICENSE create mode 100644 its/plugin/projects/AFNetworking/README.md create mode 100644 its/plugin/projects/AFNetworking/Tests/Info.plist create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_0.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_1.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_2.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/Google.com/Equifax_Secure_Certificate_Authority_Root.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GeoTrust_Global_CA-cross.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GeoTrust_Global_CA_Root.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath1/googlecom_0.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath1/googlecom_1.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath2/googlecom_0.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath2/googlecom_1.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath2/googlecom_2.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleInternetAuthorityG2.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/Google.com/google.com.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/AddTrust_External_CA_Root.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/COMODO_RSA_Certification_Authority.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/COMODO_RSA_Domain_Validation_Secure_Server_CA.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_0.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_1.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_2.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_3.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/httpbinorg_01192017.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/SelfSigned/AltName.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/SelfSigned/NoDomains.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/SelfSigned/foobar.com.cer create mode 100644 its/plugin/projects/AFNetworking/Tests/Resources/logo.png create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests-Prefix.pch create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFAutoPurgingImageCacheTests.m create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFCompoundResponseSerializerTests.m create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPRequestSerializationTests.m create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPResponseSerializationTests.m create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPSessionManagerTests.m create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFImageDownloaderTests.m create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFJSONSerializationTests.m create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFNetworkActivityManagerTests.m create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFNetworkReachabilityManagerTests.m create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFPropertyListResponseSerializerTests.m create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFSecurityPolicyTests.m create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFTestCase.h create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFTestCase.m create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFUIActivityIndicatorViewTests.m create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFUIButtonTests.m create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFUIImageViewTests.m create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFUIRefreshControlTests.m create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFUIWebViewTests.m create mode 100644 its/plugin/projects/AFNetworking/Tests/Tests/AFURLSessionManagerTests.m create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h create mode 100644 its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m create mode 100644 its/plugin/projects/AFNetworking/fastlane/.env create mode 100644 its/plugin/projects/AFNetworking/fastlane/.env.default create mode 100644 its/plugin/projects/AFNetworking/fastlane/.env.deploy create mode 100644 its/plugin/projects/AFNetworking/fastlane/.env.ios81_xcode7 create mode 100644 its/plugin/projects/AFNetworking/fastlane/.env.ios83 create mode 100644 its/plugin/projects/AFNetworking/fastlane/.env.ios84 create mode 100644 its/plugin/projects/AFNetworking/fastlane/.env.ios90_xcode7 create mode 100644 its/plugin/projects/AFNetworking/fastlane/.env.ios91_xcode71 create mode 100644 its/plugin/projects/AFNetworking/fastlane/.env.ios92 create mode 100644 its/plugin/projects/AFNetworking/fastlane/.env.ios93_xcode73 create mode 100644 its/plugin/projects/AFNetworking/fastlane/.env.osx create mode 100644 its/plugin/projects/AFNetworking/fastlane/.env.tvos90_xcode71 create mode 100644 its/plugin/projects/AFNetworking/fastlane/.env.tvos91 create mode 100644 its/plugin/projects/AFNetworking/fastlane/Fastfile create mode 100644 its/plugin/projects/AFNetworking/fastlane/README.md create mode 100644 its/plugin/projects/AFNetworking/fastlane/actions/af_build_carthage_frameworks.rb create mode 100644 its/plugin/projects/AFNetworking/fastlane/actions/af_create_github_release.rb create mode 100644 its/plugin/projects/AFNetworking/fastlane/actions/af_edit_github_release.rb create mode 100644 its/plugin/projects/AFNetworking/fastlane/actions/af_generate_github_milestone_changelog.rb create mode 100644 its/plugin/projects/AFNetworking/fastlane/actions/af_get_github_milestone.rb create mode 100644 its/plugin/projects/AFNetworking/fastlane/actions/af_insert_text_into_file.rb create mode 100644 its/plugin/projects/AFNetworking/fastlane/actions/af_pod_spec_lint.rb create mode 100644 its/plugin/projects/AFNetworking/fastlane/actions/af_push_git_tags_to_remote.rb create mode 100644 its/plugin/projects/AFNetworking/fastlane/actions/af_update_github_milestone.rb create mode 100644 its/plugin/projects/AFNetworking/fastlane/actions/af_upload_asset_for_github_release.rb diff --git a/its/plugin/projects/AFNetworking/.cocoadocs.yml b/its/plugin/projects/AFNetworking/.cocoadocs.yml new file mode 100644 index 00000000..aaf16cb1 --- /dev/null +++ b/its/plugin/projects/AFNetworking/.cocoadocs.yml @@ -0,0 +1,7 @@ +highlight-color: "#F89915" +highlight-dark-color: "#E23B1B" +darker-color: "#D8A688" +darker-dark-color: "#E93D1C" +background-color: "#E9DFDB" +alt-link-color: "#E23B1B" +warning-color: "#E23B1B" diff --git a/its/plugin/projects/AFNetworking/.gitignore b/its/plugin/projects/AFNetworking/.gitignore new file mode 100644 index 00000000..ca205d04 --- /dev/null +++ b/its/plugin/projects/AFNetworking/.gitignore @@ -0,0 +1,29 @@ +# Xcode +.DS_Store +build/ +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +*.xcworkspace +!default.xcworkspace +xcuserdata +profile +*.moved-aside +DerivedData +.idea/ +Tests/Pods +Tests/Podfile.lock +Tests/AFNetworking Tests.xcodeproj/xcshareddata/xcschemes/ +AFNetworking.framework.zip + +# Fastlane +/fastlane/report.xml +/fastlane/.env*private* +fastlane/test-output/* + +Carthage/Build diff --git a/its/plugin/projects/AFNetworking/AFNetworking.podspec b/its/plugin/projects/AFNetworking/AFNetworking.podspec new file mode 100644 index 00000000..3241d77b --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking.podspec @@ -0,0 +1,79 @@ +Pod::Spec.new do |s| + s.name = 'AFNetworking' + s.version = '3.0.4' + s.license = 'MIT' + s.summary = 'A delightful iOS and OS X networking framework.' + s.homepage = 'https://github.com/AFNetworking/AFNetworking' + s.social_media_url = 'https://twitter.com/AFNetworking' + s.authors = { 'Mattt Thompson' => 'm@mattt.me' } + s.source = { :git => 'https://github.com/AFNetworking/AFNetworking.git', :tag => s.version, :submodules => true } + s.requires_arc = true + + s.public_header_files = 'AFNetworking/AFNetworking.h' + s.source_files = 'AFNetworking/AFNetworking.h' + + pch_AF = <<-EOS +#ifndef TARGET_OS_IOS + #define TARGET_OS_IOS TARGET_OS_IPHONE +#endif + +#ifndef TARGET_OS_WATCH + #define TARGET_OS_WATCH 0 +#endif + +#ifndef TARGET_OS_TV + #define TARGET_OS_TV 0 +#endif +EOS + s.prefix_header_contents = pch_AF + + s.ios.deployment_target = '7.0' + s.osx.deployment_target = '10.9' + s.watchos.deployment_target = '2.0' + s.tvos.deployment_target = '9.0' + + s.subspec 'Serialization' do |ss| + ss.source_files = 'AFNetworking/AFURL{Request,Response}Serialization.{h,m}' + ss.public_header_files = 'AFNetworking/AFURL{Request,Response}Serialization.h' + ss.watchos.frameworks = 'MobileCoreServices', 'CoreGraphics' + ss.ios.frameworks = 'MobileCoreServices', 'CoreGraphics' + ss.osx.frameworks = 'CoreServices' + end + + s.subspec 'Security' do |ss| + ss.source_files = 'AFNetworking/AFSecurityPolicy.{h,m}' + ss.public_header_files = 'AFNetworking/AFSecurityPolicy.h' + ss.frameworks = 'Security' + end + + s.subspec 'Reachability' do |ss| + ss.ios.deployment_target = '7.0' + ss.osx.deployment_target = '10.9' + ss.tvos.deployment_target = '9.0' + + ss.source_files = 'AFNetworking/AFNetworkReachabilityManager.{h,m}' + ss.public_header_files = 'AFNetworking/AFNetworkReachabilityManager.h' + + ss.frameworks = 'SystemConfiguration' + end + + s.subspec 'NSURLSession' do |ss| + ss.dependency 'AFNetworking/Serialization' + ss.ios.dependency 'AFNetworking/Reachability' + ss.osx.dependency 'AFNetworking/Reachability' + ss.tvos.dependency 'AFNetworking/Reachability' + ss.dependency 'AFNetworking/Security' + + ss.source_files = 'AFNetworking/AF{URL,HTTP}SessionManager.{h,m}' + ss.public_header_files = 'AFNetworking/AF{URL,HTTP}SessionManager.h' + end + + s.subspec 'UIKit' do |ss| + ss.ios.deployment_target = '7.0' + ss.tvos.deployment_target = '9.0' + ss.dependency 'AFNetworking/NSURLSession' + + ss.public_header_files = 'UIKit+AFNetworking/*.h' + ss.source_files = 'UIKit+AFNetworking' + end +end diff --git a/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/project.pbxproj b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/project.pbxproj new file mode 100644 index 00000000..337d8707 --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/project.pbxproj @@ -0,0 +1,1512 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 1FE783011C5857A100A73B7C /* httpbinorg_01192017.cer in Resources */ = {isa = PBXBuildFile; fileRef = 1FE783001C58579D00A73B7C /* httpbinorg_01192017.cer */; }; + 1FE783021C5857A100A73B7C /* httpbinorg_01192017.cer in Resources */ = {isa = PBXBuildFile; fileRef = 1FE783001C58579D00A73B7C /* httpbinorg_01192017.cer */; }; + 1FE783031C5857A200A73B7C /* httpbinorg_01192017.cer in Resources */ = {isa = PBXBuildFile; fileRef = 1FE783001C58579D00A73B7C /* httpbinorg_01192017.cer */; }; + 2960BAC31C1B2F1A00BA02F0 /* AFUIButtonTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 2960BAC21C1B2F1A00BA02F0 /* AFUIButtonTests.m */; }; + 297824A31BC2D69A0041C395 /* adn_0.cer in Resources */ = {isa = PBXBuildFile; fileRef = 297824A01BC2D69A0041C395 /* adn_0.cer */; }; + 297824A41BC2D69A0041C395 /* adn_0.cer in Resources */ = {isa = PBXBuildFile; fileRef = 297824A01BC2D69A0041C395 /* adn_0.cer */; }; + 297824A51BC2D69A0041C395 /* adn_1.cer in Resources */ = {isa = PBXBuildFile; fileRef = 297824A11BC2D69A0041C395 /* adn_1.cer */; }; + 297824A61BC2D69A0041C395 /* adn_1.cer in Resources */ = {isa = PBXBuildFile; fileRef = 297824A11BC2D69A0041C395 /* adn_1.cer */; }; + 297824A71BC2D69A0041C395 /* adn_2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 297824A21BC2D69A0041C395 /* adn_2.cer */; }; + 297824A81BC2D69A0041C395 /* adn_2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 297824A21BC2D69A0041C395 /* adn_2.cer */; }; + 297824AA1BC2DAD80041C395 /* AFAutoPurgingImageCacheTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C801BC2C88F00FD3B3E /* AFAutoPurgingImageCacheTests.m */; }; + 297824AB1BC2DB060041C395 /* AFNetworking.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 299522391BBF104D00859F49 /* AFNetworking.framework */; }; + 297824AC1BC2DB450041C395 /* AFImageDownloaderTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C841BC2C88F00FD3B3E /* AFImageDownloaderTests.m */; }; + 297824AD1BC2DBA40041C395 /* AFNetworkActivityManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C861BC2C88F00FD3B3E /* AFNetworkActivityManagerTests.m */; }; + 297824AE1BC2DBD80041C395 /* AFUIActivityIndicatorViewTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8C1BC2C88F00FD3B3E /* AFUIActivityIndicatorViewTests.m */; }; + 297824AF1BC2DBEF0041C395 /* AFUIRefreshControlTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8E1BC2C88F00FD3B3E /* AFUIRefreshControlTests.m */; }; + 297824B01BC2DC2D0041C395 /* AFUIImageViewTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8D1BC2C88F00FD3B3E /* AFUIImageViewTests.m */; }; + 2987B0AF1BC408A200179A4C /* AFNetworking.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2987B0A51BC408A200179A4C /* AFNetworking.framework */; }; + 2987B0BC1BC408D900179A4C /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522471BBF125A00859F49 /* AFHTTPSessionManager.m */; }; + 2987B0BD1BC408D900179A4C /* AFNetworkReachabilityManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224A1BBF125A00859F49 /* AFNetworkReachabilityManager.m */; }; + 2987B0BE1BC408D900179A4C /* AFSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224C1BBF125A00859F49 /* AFSecurityPolicy.m */; }; + 2987B0BF1BC408D900179A4C /* AFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224E1BBF125A00859F49 /* AFURLRequestSerialization.m */; }; + 2987B0C01BC408D900179A4C /* AFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522501BBF125A00859F49 /* AFURLResponseSerialization.m */; }; + 2987B0C11BC408D900179A4C /* AFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522521BBF125A00859F49 /* AFURLSessionManager.m */; }; + 2987B0C21BC408F900179A4C /* AFAutoPurgingImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522871BBF13C700859F49 /* AFAutoPurgingImageCache.m */; }; + 2987B0C31BC408F900179A4C /* AFImageDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522891BBF13C700859F49 /* AFImageDownloader.m */; }; + 2987B0C41BC408F900179A4C /* UIActivityIndicatorView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995228D1BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.m */; }; + 2987B0C51BC408F900179A4C /* UIButton+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522911BBF13C700859F49 /* UIButton+AFNetworking.m */; }; + 2987B0C61BC408F900179A4C /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522941BBF13C700859F49 /* UIImageView+AFNetworking.m */; }; + 2987B0C71BC408F900179A4C /* UIProgressView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522971BBF13C700859F49 /* UIProgressView+AFNetworking.m */; }; + 2987B0CA1BC40A7600179A4C /* AFHTTPRequestSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C811BC2C88F00FD3B3E /* AFHTTPRequestSerializationTests.m */; }; + 2987B0CB1BC40A7600179A4C /* AFHTTPResponseSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C821BC2C88F00FD3B3E /* AFHTTPResponseSerializationTests.m */; }; + 2987B0CC1BC40A7600179A4C /* AFHTTPSessionManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C831BC2C88F00FD3B3E /* AFHTTPSessionManagerTests.m */; }; + 2987B0CD1BC40A7600179A4C /* AFJSONSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C851BC2C88F00FD3B3E /* AFJSONSerializationTests.m */; }; + 2987B0CE1BC40A7600179A4C /* AFNetworkReachabilityManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C871BC2C88F00FD3B3E /* AFNetworkReachabilityManagerTests.m */; }; + 2987B0CF1BC40A7600179A4C /* AFPropertyListResponseSerializerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C881BC2C88F00FD3B3E /* AFPropertyListResponseSerializerTests.m */; }; + 2987B0D01BC40A7600179A4C /* AFSecurityPolicyTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C891BC2C88F00FD3B3E /* AFSecurityPolicyTests.m */; }; + 2987B0D11BC40A7600179A4C /* AFURLSessionManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8F1BC2C88F00FD3B3E /* AFURLSessionManagerTests.m */; }; + 2987B0D21BC40AD800179A4C /* AFTestCase.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8B1BC2C88F00FD3B3E /* AFTestCase.m */; }; + 2987B0D31BC40AE900179A4C /* adn_0.cer in Resources */ = {isa = PBXBuildFile; fileRef = 297824A01BC2D69A0041C395 /* adn_0.cer */; }; + 2987B0D41BC40AE900179A4C /* adn_1.cer in Resources */ = {isa = PBXBuildFile; fileRef = 297824A11BC2D69A0041C395 /* adn_1.cer */; }; + 2987B0D51BC40AE900179A4C /* adn_2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 297824A21BC2D69A0041C395 /* adn_2.cer */; }; + 2987B0D61BC40AEC00179A4C /* ADNNetServerTrustChain in Resources */ = {isa = PBXBuildFile; fileRef = 298D7CDF1BC2CB5A00FD3B3E /* ADNNetServerTrustChain */; }; + 2987B0D71BC40AF000179A4C /* HTTPBinOrgServerTrustChain in Resources */ = {isa = PBXBuildFile; fileRef = 298D7CE21BC2CB7C00FD3B3E /* HTTPBinOrgServerTrustChain */; }; + 2987B0D81BC40AF300179A4C /* AddTrust_External_CA_Root.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C6E1BC2C88F00FD3B3E /* AddTrust_External_CA_Root.cer */; }; + 2987B0D91BC40AF300179A4C /* COMODO_RSA_Certification_Authority.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C6F1BC2C88F00FD3B3E /* COMODO_RSA_Certification_Authority.cer */; }; + 2987B0DA1BC40AF300179A4C /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C701BC2C88F00FD3B3E /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer */; }; + 2987B0DC1BC40AF600179A4C /* logo.png in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C771BC2C88F00FD3B3E /* logo.png */; }; + 2987B0DD1BC40AFB00179A4C /* AltName.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C791BC2C88F00FD3B3E /* AltName.cer */; }; + 2987B0DE1BC40AFB00179A4C /* foobar.com.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C7A1BC2C88F00FD3B3E /* foobar.com.cer */; }; + 2987B0DF1BC40AFB00179A4C /* NoDomains.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C7B1BC2C88F00FD3B3E /* NoDomains.cer */; }; + 2987B0E01BC40B0900179A4C /* AFAutoPurgingImageCacheTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C801BC2C88F00FD3B3E /* AFAutoPurgingImageCacheTests.m */; }; + 2987B0E11BC40B0900179A4C /* AFImageDownloaderTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C841BC2C88F00FD3B3E /* AFImageDownloaderTests.m */; }; + 2987B0E31BC40B0900179A4C /* AFUIActivityIndicatorViewTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8C1BC2C88F00FD3B3E /* AFUIActivityIndicatorViewTests.m */; }; + 2987B0E41BC40B0900179A4C /* AFUIImageViewTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8D1BC2C88F00FD3B3E /* AFUIImageViewTests.m */; }; + 298D7C4F1BC2C7B200FD3B3E /* AFNetworking.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 299522771BBF136400859F49 /* AFNetworking.framework */; }; + 298D7C961BC2C94400FD3B3E /* AFTestCase.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8B1BC2C88F00FD3B3E /* AFTestCase.m */; }; + 298D7C971BC2C94500FD3B3E /* AFTestCase.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8B1BC2C88F00FD3B3E /* AFTestCase.m */; }; + 298D7C981BC2CA2500FD3B3E /* AFURLSessionManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8F1BC2C88F00FD3B3E /* AFURLSessionManagerTests.m */; }; + 298D7C991BC2CA2600FD3B3E /* AFURLSessionManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C8F1BC2C88F00FD3B3E /* AFURLSessionManagerTests.m */; }; + 298D7CB11BC2CA6E00FD3B3E /* AFHTTPRequestSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C811BC2C88F00FD3B3E /* AFHTTPRequestSerializationTests.m */; }; + 298D7CB21BC2CA6E00FD3B3E /* AFHTTPRequestSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C811BC2C88F00FD3B3E /* AFHTTPRequestSerializationTests.m */; }; + 298D7CB91BC2CA9800FD3B3E /* logo.png in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C771BC2C88F00FD3B3E /* logo.png */; }; + 298D7CBA1BC2CA9800FD3B3E /* logo.png in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C771BC2C88F00FD3B3E /* logo.png */; }; + 298D7CBB1BC2CA9C00FD3B3E /* AltName.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C791BC2C88F00FD3B3E /* AltName.cer */; }; + 298D7CBC1BC2CA9C00FD3B3E /* foobar.com.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C7A1BC2C88F00FD3B3E /* foobar.com.cer */; }; + 298D7CBD1BC2CA9C00FD3B3E /* NoDomains.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C7B1BC2C88F00FD3B3E /* NoDomains.cer */; }; + 298D7CBE1BC2CA9D00FD3B3E /* AltName.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C791BC2C88F00FD3B3E /* AltName.cer */; }; + 298D7CBF1BC2CA9D00FD3B3E /* foobar.com.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C7A1BC2C88F00FD3B3E /* foobar.com.cer */; }; + 298D7CC01BC2CA9D00FD3B3E /* NoDomains.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C7B1BC2C88F00FD3B3E /* NoDomains.cer */; }; + 298D7CC11BC2CAA100FD3B3E /* AddTrust_External_CA_Root.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C6E1BC2C88F00FD3B3E /* AddTrust_External_CA_Root.cer */; }; + 298D7CC21BC2CAA100FD3B3E /* COMODO_RSA_Certification_Authority.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C6F1BC2C88F00FD3B3E /* COMODO_RSA_Certification_Authority.cer */; }; + 298D7CC31BC2CAA100FD3B3E /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C701BC2C88F00FD3B3E /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer */; }; + 298D7CC51BC2CAA200FD3B3E /* AddTrust_External_CA_Root.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C6E1BC2C88F00FD3B3E /* AddTrust_External_CA_Root.cer */; }; + 298D7CC61BC2CAA200FD3B3E /* COMODO_RSA_Certification_Authority.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C6F1BC2C88F00FD3B3E /* COMODO_RSA_Certification_Authority.cer */; }; + 298D7CC71BC2CAA200FD3B3E /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer in Resources */ = {isa = PBXBuildFile; fileRef = 298D7C701BC2C88F00FD3B3E /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer */; }; + 298D7CD31BC2CAE800FD3B3E /* AFHTTPResponseSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C821BC2C88F00FD3B3E /* AFHTTPResponseSerializationTests.m */; }; + 298D7CD41BC2CAE900FD3B3E /* AFHTTPResponseSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C821BC2C88F00FD3B3E /* AFHTTPResponseSerializationTests.m */; }; + 298D7CD51BC2CAEC00FD3B3E /* AFHTTPSessionManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C831BC2C88F00FD3B3E /* AFHTTPSessionManagerTests.m */; }; + 298D7CD61BC2CAED00FD3B3E /* AFHTTPSessionManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C831BC2C88F00FD3B3E /* AFHTTPSessionManagerTests.m */; }; + 298D7CD71BC2CAEF00FD3B3E /* AFJSONSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C851BC2C88F00FD3B3E /* AFJSONSerializationTests.m */; }; + 298D7CD81BC2CAF000FD3B3E /* AFJSONSerializationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C851BC2C88F00FD3B3E /* AFJSONSerializationTests.m */; }; + 298D7CD91BC2CAF200FD3B3E /* AFNetworkReachabilityManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C871BC2C88F00FD3B3E /* AFNetworkReachabilityManagerTests.m */; }; + 298D7CDA1BC2CAF300FD3B3E /* AFNetworkReachabilityManagerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C871BC2C88F00FD3B3E /* AFNetworkReachabilityManagerTests.m */; }; + 298D7CDB1BC2CAF500FD3B3E /* AFPropertyListResponseSerializerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C881BC2C88F00FD3B3E /* AFPropertyListResponseSerializerTests.m */; }; + 298D7CDC1BC2CAF500FD3B3E /* AFPropertyListResponseSerializerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C881BC2C88F00FD3B3E /* AFPropertyListResponseSerializerTests.m */; }; + 298D7CDD1BC2CAF700FD3B3E /* AFSecurityPolicyTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C891BC2C88F00FD3B3E /* AFSecurityPolicyTests.m */; }; + 298D7CDE1BC2CAF800FD3B3E /* AFSecurityPolicyTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 298D7C891BC2C88F00FD3B3E /* AFSecurityPolicyTests.m */; }; + 298D7CE01BC2CB5A00FD3B3E /* ADNNetServerTrustChain in Resources */ = {isa = PBXBuildFile; fileRef = 298D7CDF1BC2CB5A00FD3B3E /* ADNNetServerTrustChain */; }; + 298D7CE11BC2CB5A00FD3B3E /* ADNNetServerTrustChain in Resources */ = {isa = PBXBuildFile; fileRef = 298D7CDF1BC2CB5A00FD3B3E /* ADNNetServerTrustChain */; }; + 298D7CE31BC2CB7C00FD3B3E /* HTTPBinOrgServerTrustChain in Resources */ = {isa = PBXBuildFile; fileRef = 298D7CE21BC2CB7C00FD3B3E /* HTTPBinOrgServerTrustChain */; }; + 298D7CE41BC2CB7C00FD3B3E /* HTTPBinOrgServerTrustChain in Resources */ = {isa = PBXBuildFile; fileRef = 298D7CE21BC2CB7C00FD3B3E /* HTTPBinOrgServerTrustChain */; }; + 2995223D1BBF104D00859F49 /* AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995223C1BBF104D00859F49 /* AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522531BBF125A00859F49 /* AFHTTPSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522461BBF125A00859F49 /* AFHTTPSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522541BBF125A00859F49 /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522471BBF125A00859F49 /* AFHTTPSessionManager.m */; }; + 299522561BBF125A00859F49 /* AFNetworkReachabilityManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522491BBF125A00859F49 /* AFNetworkReachabilityManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522571BBF125A00859F49 /* AFNetworkReachabilityManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224A1BBF125A00859F49 /* AFNetworkReachabilityManager.m */; }; + 299522581BBF125A00859F49 /* AFSecurityPolicy.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224B1BBF125A00859F49 /* AFSecurityPolicy.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522591BBF125A00859F49 /* AFSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224C1BBF125A00859F49 /* AFSecurityPolicy.m */; }; + 2995225A1BBF125A00859F49 /* AFURLRequestSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224D1BBF125A00859F49 /* AFURLRequestSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2995225B1BBF125A00859F49 /* AFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224E1BBF125A00859F49 /* AFURLRequestSerialization.m */; }; + 2995225C1BBF125A00859F49 /* AFURLResponseSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224F1BBF125A00859F49 /* AFURLResponseSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2995225D1BBF125A00859F49 /* AFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522501BBF125A00859F49 /* AFURLResponseSerialization.m */; }; + 2995225E1BBF125A00859F49 /* AFURLSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522511BBF125A00859F49 /* AFURLSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2995225F1BBF125A00859F49 /* AFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522521BBF125A00859F49 /* AFURLSessionManager.m */; }; + 2995226D1BBF133400859F49 /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522471BBF125A00859F49 /* AFHTTPSessionManager.m */; }; + 2995226E1BBF133400859F49 /* AFSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224C1BBF125A00859F49 /* AFSecurityPolicy.m */; }; + 2995226F1BBF133400859F49 /* AFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224E1BBF125A00859F49 /* AFURLRequestSerialization.m */; }; + 299522701BBF133400859F49 /* AFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522501BBF125A00859F49 /* AFURLResponseSerialization.m */; }; + 299522711BBF133400859F49 /* AFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522521BBF125A00859F49 /* AFURLSessionManager.m */; }; + 2995227F1BBF13A100859F49 /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522471BBF125A00859F49 /* AFHTTPSessionManager.m */; }; + 299522801BBF13A100859F49 /* AFNetworkReachabilityManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224A1BBF125A00859F49 /* AFNetworkReachabilityManager.m */; }; + 299522811BBF13A100859F49 /* AFSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224C1BBF125A00859F49 /* AFSecurityPolicy.m */; }; + 299522821BBF13A100859F49 /* AFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995224E1BBF125A00859F49 /* AFURLRequestSerialization.m */; }; + 299522831BBF13A100859F49 /* AFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522501BBF125A00859F49 /* AFURLResponseSerialization.m */; }; + 299522841BBF13A100859F49 /* AFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522521BBF125A00859F49 /* AFURLSessionManager.m */; }; + 2995229C1BBF13C700859F49 /* AFAutoPurgingImageCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522861BBF13C700859F49 /* AFAutoPurgingImageCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2995229D1BBF13C700859F49 /* AFAutoPurgingImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522871BBF13C700859F49 /* AFAutoPurgingImageCache.m */; }; + 2995229E1BBF13C700859F49 /* AFImageDownloader.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522881BBF13C700859F49 /* AFImageDownloader.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2995229F1BBF13C700859F49 /* AFImageDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522891BBF13C700859F49 /* AFImageDownloader.m */; }; + 299522A01BBF13C700859F49 /* AFNetworkActivityIndicatorManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995228A1BBF13C700859F49 /* AFNetworkActivityIndicatorManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522A11BBF13C700859F49 /* AFNetworkActivityIndicatorManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995228B1BBF13C700859F49 /* AFNetworkActivityIndicatorManager.m */; }; + 299522A21BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995228C1BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522A31BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995228D1BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.m */; }; + 299522A61BBF13C700859F49 /* UIButton+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522901BBF13C700859F49 /* UIButton+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522A71BBF13C700859F49 /* UIButton+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522911BBF13C700859F49 /* UIButton+AFNetworking.m */; }; + 299522A81BBF13C700859F49 /* UIImage+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522921BBF13C700859F49 /* UIImage+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522A91BBF13C700859F49 /* UIImageView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522931BBF13C700859F49 /* UIImageView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522AA1BBF13C700859F49 /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522941BBF13C700859F49 /* UIImageView+AFNetworking.m */; }; + 299522AC1BBF13C700859F49 /* UIProgressView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522961BBF13C700859F49 /* UIProgressView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522AD1BBF13C700859F49 /* UIProgressView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522971BBF13C700859F49 /* UIProgressView+AFNetworking.m */; }; + 299522AE1BBF13C700859F49 /* UIRefreshControl+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522981BBF13C700859F49 /* UIRefreshControl+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522AF1BBF13C700859F49 /* UIRefreshControl+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 299522991BBF13C700859F49 /* UIRefreshControl+AFNetworking.m */; }; + 299522B01BBF13C700859F49 /* UIWebView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995229A1BBF13C700859F49 /* UIWebView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 299522B11BBF13C700859F49 /* UIWebView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 2995229B1BBF13C700859F49 /* UIWebView+AFNetworking.m */; }; + 29D3413F1C20D46400A7D266 /* AFCompoundResponseSerializerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 29D3413E1C20D46400A7D266 /* AFCompoundResponseSerializerTests.m */; }; + 29D341401C20D46400A7D266 /* AFCompoundResponseSerializerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 29D3413E1C20D46400A7D266 /* AFCompoundResponseSerializerTests.m */; }; + 29D341411C20D46400A7D266 /* AFCompoundResponseSerializerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 29D3413E1C20D46400A7D266 /* AFCompoundResponseSerializerTests.m */; }; + 29D96E7A1BCC3D6000F571A5 /* AFHTTPSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522461BBF125A00859F49 /* AFHTTPSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E7C1BCC3D6000F571A5 /* AFSecurityPolicy.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224B1BBF125A00859F49 /* AFSecurityPolicy.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E7D1BCC3D6000F571A5 /* AFURLRequestSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224D1BBF125A00859F49 /* AFURLRequestSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E7E1BCC3D6000F571A5 /* AFURLResponseSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224F1BBF125A00859F49 /* AFURLResponseSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E7F1BCC3D6000F571A5 /* AFURLSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522511BBF125A00859F49 /* AFURLSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E801BCC3D6000F571A5 /* AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995223C1BBF104D00859F49 /* AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E811BCC3D7200F571A5 /* AFHTTPSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522461BBF125A00859F49 /* AFHTTPSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E821BCC3D7200F571A5 /* AFNetworkReachabilityManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522491BBF125A00859F49 /* AFNetworkReachabilityManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E831BCC3D7200F571A5 /* AFSecurityPolicy.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224B1BBF125A00859F49 /* AFSecurityPolicy.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E841BCC3D7200F571A5 /* AFURLRequestSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224D1BBF125A00859F49 /* AFURLRequestSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E851BCC3D7200F571A5 /* AFURLResponseSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224F1BBF125A00859F49 /* AFURLResponseSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E861BCC3D7200F571A5 /* AFURLSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522511BBF125A00859F49 /* AFURLSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E871BCC3D7200F571A5 /* AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995223C1BBF104D00859F49 /* AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E881BCC3D7D00F571A5 /* AFHTTPSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522461BBF125A00859F49 /* AFHTTPSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E891BCC3D7D00F571A5 /* AFNetworkReachabilityManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522491BBF125A00859F49 /* AFNetworkReachabilityManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E8A1BCC3D7D00F571A5 /* AFSecurityPolicy.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224B1BBF125A00859F49 /* AFSecurityPolicy.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E8B1BCC3D7D00F571A5 /* AFURLRequestSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224D1BBF125A00859F49 /* AFURLRequestSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E8C1BCC3D7D00F571A5 /* AFURLResponseSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995224F1BBF125A00859F49 /* AFURLResponseSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E8D1BCC3D7D00F571A5 /* AFURLSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522511BBF125A00859F49 /* AFURLSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E8E1BCC3D7D00F571A5 /* AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995223C1BBF104D00859F49 /* AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E941BCC406B00F571A5 /* AFAutoPurgingImageCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522861BBF13C700859F49 /* AFAutoPurgingImageCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E951BCC406B00F571A5 /* AFImageDownloader.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522881BBF13C700859F49 /* AFImageDownloader.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E961BCC406B00F571A5 /* UIActivityIndicatorView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 2995228C1BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E971BCC406B00F571A5 /* UIButton+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522901BBF13C700859F49 /* UIButton+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E981BCC406B00F571A5 /* UIImage+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522921BBF13C700859F49 /* UIImage+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E991BCC406B00F571A5 /* UIImageView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522931BBF13C700859F49 /* UIImageView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29D96E9A1BCC406B00F571A5 /* UIProgressView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 299522961BBF13C700859F49 /* UIProgressView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29F5EF031C47E64F008B976A /* AFUIWebViewTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 29F5EF021C47E64F008B976A /* AFUIWebViewTests.m */; }; + 5F4323BB1BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323B31BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer */; }; + 5F4323BC1BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323B31BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer */; }; + 5F4323BD1BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323B31BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer */; }; + 5F4323BE1BF63741003B8749 /* GeoTrust_Global_CA-cross.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323B41BF63741003B8749 /* GeoTrust_Global_CA-cross.cer */; }; + 5F4323BF1BF63741003B8749 /* GeoTrust_Global_CA-cross.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323B41BF63741003B8749 /* GeoTrust_Global_CA-cross.cer */; }; + 5F4323C01BF63741003B8749 /* GeoTrust_Global_CA-cross.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323B41BF63741003B8749 /* GeoTrust_Global_CA-cross.cer */; }; + 5F4323C11BF63741003B8749 /* google.com.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323B51BF63741003B8749 /* google.com.cer */; }; + 5F4323C21BF63741003B8749 /* google.com.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323B51BF63741003B8749 /* google.com.cer */; }; + 5F4323C31BF63741003B8749 /* google.com.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323B51BF63741003B8749 /* google.com.cer */; }; + 5F4323CD1BF63741003B8749 /* GoogleInternetAuthorityG2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323BA1BF63741003B8749 /* GoogleInternetAuthorityG2.cer */; }; + 5F4323CE1BF63741003B8749 /* GoogleInternetAuthorityG2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323BA1BF63741003B8749 /* GoogleInternetAuthorityG2.cer */; }; + 5F4323CF1BF63741003B8749 /* GoogleInternetAuthorityG2.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323BA1BF63741003B8749 /* GoogleInternetAuthorityG2.cer */; }; + 5F4323D51BF63CB0003B8749 /* GoogleComServerTrustChainPath1 in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323D41BF63CB0003B8749 /* GoogleComServerTrustChainPath1 */; }; + 5F4323D61BF63CB0003B8749 /* GoogleComServerTrustChainPath1 in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323D41BF63CB0003B8749 /* GoogleComServerTrustChainPath1 */; }; + 5F4323D71BF63CB0003B8749 /* GoogleComServerTrustChainPath1 in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323D41BF63CB0003B8749 /* GoogleComServerTrustChainPath1 */; }; + 5F4323D91BF63CBA003B8749 /* GoogleComServerTrustChainPath2 in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323D81BF63CBA003B8749 /* GoogleComServerTrustChainPath2 */; }; + 5F4323DA1BF63CBA003B8749 /* GoogleComServerTrustChainPath2 in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323D81BF63CBA003B8749 /* GoogleComServerTrustChainPath2 */; }; + 5F4323DB1BF63CBA003B8749 /* GoogleComServerTrustChainPath2 in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323D81BF63CBA003B8749 /* GoogleComServerTrustChainPath2 */; }; + 5F4323DD1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323DC1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer */; }; + 5F4323DE1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323DC1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer */; }; + 5F4323DF1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer in Resources */ = {isa = PBXBuildFile; fileRef = 5F4323DC1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 2987B0B01BC408A200179A4C /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 299522301BBF104D00859F49 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 2987B0A41BC408A200179A4C; + remoteInfo = "AFNetworking tvOS"; + }; + 298D7C411BC2C79500FD3B3E /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 299522301BBF104D00859F49 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 299522381BBF104D00859F49; + remoteInfo = "AFNetworking iOS"; + }; + 298D7C501BC2C7B200FD3B3E /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 299522301BBF104D00859F49 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 299522761BBF136400859F49; + remoteInfo = "AFNetworking OS X"; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 1FE783001C58579D00A73B7C /* httpbinorg_01192017.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = httpbinorg_01192017.cer; sourceTree = ""; }; + 2960BAC21C1B2F1A00BA02F0 /* AFUIButtonTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFUIButtonTests.m; sourceTree = ""; }; + 297824A01BC2D69A0041C395 /* adn_0.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = adn_0.cer; path = ADNNetServerTrustChain/adn_0.cer; sourceTree = ""; }; + 297824A11BC2D69A0041C395 /* adn_1.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = adn_1.cer; path = ADNNetServerTrustChain/adn_1.cer; sourceTree = ""; }; + 297824A21BC2D69A0041C395 /* adn_2.cer */ = {isa = PBXFileReference; lastKnownFileType = file; name = adn_2.cer; path = ADNNetServerTrustChain/adn_2.cer; sourceTree = ""; }; + 2987B0A51BC408A200179A4C /* AFNetworking.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = AFNetworking.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 2987B0AE1BC408A200179A4C /* AFNetworking tvOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "AFNetworking tvOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + 298D7C3B1BC2C79500FD3B3E /* AFNetworking iOS Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "AFNetworking iOS Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + 298D7C4A1BC2C7B200FD3B3E /* AFNetworking Mac OS X Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "AFNetworking Mac OS X Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + 298D7C6E1BC2C88F00FD3B3E /* AddTrust_External_CA_Root.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = AddTrust_External_CA_Root.cer; sourceTree = ""; }; + 298D7C6F1BC2C88F00FD3B3E /* COMODO_RSA_Certification_Authority.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = COMODO_RSA_Certification_Authority.cer; sourceTree = ""; }; + 298D7C701BC2C88F00FD3B3E /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = COMODO_RSA_Domain_Validation_Secure_Server_CA.cer; sourceTree = ""; }; + 298D7C771BC2C88F00FD3B3E /* logo.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = logo.png; sourceTree = ""; }; + 298D7C791BC2C88F00FD3B3E /* AltName.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = AltName.cer; sourceTree = ""; }; + 298D7C7A1BC2C88F00FD3B3E /* foobar.com.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = foobar.com.cer; sourceTree = ""; }; + 298D7C7B1BC2C88F00FD3B3E /* NoDomains.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = NoDomains.cer; sourceTree = ""; }; + 298D7C801BC2C88F00FD3B3E /* AFAutoPurgingImageCacheTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFAutoPurgingImageCacheTests.m; sourceTree = ""; }; + 298D7C811BC2C88F00FD3B3E /* AFHTTPRequestSerializationTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFHTTPRequestSerializationTests.m; sourceTree = ""; }; + 298D7C821BC2C88F00FD3B3E /* AFHTTPResponseSerializationTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFHTTPResponseSerializationTests.m; sourceTree = ""; }; + 298D7C831BC2C88F00FD3B3E /* AFHTTPSessionManagerTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFHTTPSessionManagerTests.m; sourceTree = ""; }; + 298D7C841BC2C88F00FD3B3E /* AFImageDownloaderTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFImageDownloaderTests.m; sourceTree = ""; }; + 298D7C851BC2C88F00FD3B3E /* AFJSONSerializationTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFJSONSerializationTests.m; sourceTree = ""; }; + 298D7C861BC2C88F00FD3B3E /* AFNetworkActivityManagerTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFNetworkActivityManagerTests.m; sourceTree = ""; }; + 298D7C871BC2C88F00FD3B3E /* AFNetworkReachabilityManagerTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFNetworkReachabilityManagerTests.m; sourceTree = ""; }; + 298D7C881BC2C88F00FD3B3E /* AFPropertyListResponseSerializerTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFPropertyListResponseSerializerTests.m; sourceTree = ""; }; + 298D7C891BC2C88F00FD3B3E /* AFSecurityPolicyTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFSecurityPolicyTests.m; sourceTree = ""; }; + 298D7C8A1BC2C88F00FD3B3E /* AFTestCase.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AFTestCase.h; sourceTree = ""; }; + 298D7C8B1BC2C88F00FD3B3E /* AFTestCase.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFTestCase.m; sourceTree = ""; }; + 298D7C8C1BC2C88F00FD3B3E /* AFUIActivityIndicatorViewTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFUIActivityIndicatorViewTests.m; sourceTree = ""; }; + 298D7C8D1BC2C88F00FD3B3E /* AFUIImageViewTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFUIImageViewTests.m; sourceTree = ""; }; + 298D7C8E1BC2C88F00FD3B3E /* AFUIRefreshControlTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFUIRefreshControlTests.m; sourceTree = ""; }; + 298D7C8F1BC2C88F00FD3B3E /* AFURLSessionManagerTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFURLSessionManagerTests.m; sourceTree = ""; }; + 298D7CDF1BC2CB5A00FD3B3E /* ADNNetServerTrustChain */ = {isa = PBXFileReference; lastKnownFileType = folder; path = ADNNetServerTrustChain; sourceTree = ""; }; + 298D7CE21BC2CB7C00FD3B3E /* HTTPBinOrgServerTrustChain */ = {isa = PBXFileReference; lastKnownFileType = folder; path = HTTPBinOrgServerTrustChain; sourceTree = ""; }; + 299522391BBF104D00859F49 /* AFNetworking.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = AFNetworking.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 2995223C1BBF104D00859F49 /* AFNetworking.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = AFNetworking.h; path = ../Framework/AFNetworking.h; sourceTree = ""; }; + 2995223E1BBF104D00859F49 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = ../Framework/Info.plist; sourceTree = ""; }; + 299522461BBF125A00859F49 /* AFHTTPSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPSessionManager.h; sourceTree = ""; }; + 299522471BBF125A00859F49 /* AFHTTPSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPSessionManager.m; sourceTree = ""; }; + 299522491BBF125A00859F49 /* AFNetworkReachabilityManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworkReachabilityManager.h; sourceTree = ""; }; + 2995224A1BBF125A00859F49 /* AFNetworkReachabilityManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFNetworkReachabilityManager.m; sourceTree = ""; }; + 2995224B1BBF125A00859F49 /* AFSecurityPolicy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFSecurityPolicy.h; sourceTree = ""; }; + 2995224C1BBF125A00859F49 /* AFSecurityPolicy.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFSecurityPolicy.m; sourceTree = ""; }; + 2995224D1BBF125A00859F49 /* AFURLRequestSerialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLRequestSerialization.h; sourceTree = ""; }; + 2995224E1BBF125A00859F49 /* AFURLRequestSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLRequestSerialization.m; sourceTree = ""; }; + 2995224F1BBF125A00859F49 /* AFURLResponseSerialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLResponseSerialization.h; sourceTree = ""; }; + 299522501BBF125A00859F49 /* AFURLResponseSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLResponseSerialization.m; sourceTree = ""; }; + 299522511BBF125A00859F49 /* AFURLSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLSessionManager.h; sourceTree = ""; }; + 299522521BBF125A00859F49 /* AFURLSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLSessionManager.m; sourceTree = ""; }; + 299522651BBF129200859F49 /* AFNetworking.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = AFNetworking.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 299522771BBF136400859F49 /* AFNetworking.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = AFNetworking.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 299522861BBF13C700859F49 /* AFAutoPurgingImageCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFAutoPurgingImageCache.h; sourceTree = ""; }; + 299522871BBF13C700859F49 /* AFAutoPurgingImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFAutoPurgingImageCache.m; sourceTree = ""; }; + 299522881BBF13C700859F49 /* AFImageDownloader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFImageDownloader.h; sourceTree = ""; }; + 299522891BBF13C700859F49 /* AFImageDownloader.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFImageDownloader.m; sourceTree = ""; }; + 2995228A1BBF13C700859F49 /* AFNetworkActivityIndicatorManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworkActivityIndicatorManager.h; sourceTree = ""; }; + 2995228B1BBF13C700859F49 /* AFNetworkActivityIndicatorManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFNetworkActivityIndicatorManager.m; sourceTree = ""; }; + 2995228C1BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIActivityIndicatorView+AFNetworking.h"; sourceTree = ""; }; + 2995228D1BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIActivityIndicatorView+AFNetworking.m"; sourceTree = ""; }; + 299522901BBF13C700859F49 /* UIButton+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIButton+AFNetworking.h"; sourceTree = ""; }; + 299522911BBF13C700859F49 /* UIButton+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIButton+AFNetworking.m"; sourceTree = ""; }; + 299522921BBF13C700859F49 /* UIImage+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImage+AFNetworking.h"; sourceTree = ""; }; + 299522931BBF13C700859F49 /* UIImageView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImageView+AFNetworking.h"; sourceTree = ""; }; + 299522941BBF13C700859F49 /* UIImageView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImageView+AFNetworking.m"; sourceTree = ""; }; + 299522951BBF13C700859F49 /* UIKit+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIKit+AFNetworking.h"; sourceTree = ""; }; + 299522961BBF13C700859F49 /* UIProgressView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIProgressView+AFNetworking.h"; sourceTree = ""; }; + 299522971BBF13C700859F49 /* UIProgressView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIProgressView+AFNetworking.m"; sourceTree = ""; }; + 299522981BBF13C700859F49 /* UIRefreshControl+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIRefreshControl+AFNetworking.h"; sourceTree = ""; }; + 299522991BBF13C700859F49 /* UIRefreshControl+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIRefreshControl+AFNetworking.m"; sourceTree = ""; }; + 2995229A1BBF13C700859F49 /* UIWebView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIWebView+AFNetworking.h"; sourceTree = ""; }; + 2995229B1BBF13C700859F49 /* UIWebView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIWebView+AFNetworking.m"; sourceTree = ""; }; + 29D3413E1C20D46400A7D266 /* AFCompoundResponseSerializerTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFCompoundResponseSerializerTests.m; sourceTree = ""; }; + 29F5EF021C47E64F008B976A /* AFUIWebViewTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFUIWebViewTests.m; sourceTree = ""; }; + 5F4323B31BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = Equifax_Secure_Certificate_Authority_Root.cer; sourceTree = ""; }; + 5F4323B41BF63741003B8749 /* GeoTrust_Global_CA-cross.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = "GeoTrust_Global_CA-cross.cer"; sourceTree = ""; }; + 5F4323B51BF63741003B8749 /* google.com.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = google.com.cer; sourceTree = ""; }; + 5F4323BA1BF63741003B8749 /* GoogleInternetAuthorityG2.cer */ = {isa = PBXFileReference; lastKnownFileType = file; path = GoogleInternetAuthorityG2.cer; sourceTree = ""; }; + 5F4323D41BF63CB0003B8749 /* GoogleComServerTrustChainPath1 */ = {isa = PBXFileReference; lastKnownFileType = folder; path = GoogleComServerTrustChainPath1; sourceTree = ""; }; + 5F4323D81BF63CBA003B8749 /* GoogleComServerTrustChainPath2 */ = {isa = PBXFileReference; lastKnownFileType = folder; path = GoogleComServerTrustChainPath2; sourceTree = ""; }; + 5F4323DC1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = GeoTrust_Global_CA_Root.cer; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 2987B0A11BC408A200179A4C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2987B0AB1BC408A200179A4C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2987B0AF1BC408A200179A4C /* AFNetworking.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 298D7C381BC2C79500FD3B3E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 297824AB1BC2DB060041C395 /* AFNetworking.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 298D7C471BC2C7B200FD3B3E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 298D7C4F1BC2C7B200FD3B3E /* AFNetworking.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522351BBF104D00859F49 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522611BBF129200859F49 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522731BBF136400859F49 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 298D7C561BC2C88F00FD3B3E /* Tests */ = { + isa = PBXGroup; + children = ( + 298D7C671BC2C88F00FD3B3E /* Resources */, + 298D7C7F1BC2C88F00FD3B3E /* Tests */, + ); + path = Tests; + sourceTree = ""; + }; + 298D7C671BC2C88F00FD3B3E /* Resources */ = { + isa = PBXGroup; + children = ( + 298D7C681BC2C88F00FD3B3E /* ADN.net */, + 298D7C6D1BC2C88F00FD3B3E /* HTTPBin.org */, + 298D7C771BC2C88F00FD3B3E /* logo.png */, + 298D7C781BC2C88F00FD3B3E /* SelfSigned */, + 5F4323B21BF63741003B8749 /* Google.com */, + ); + path = Resources; + sourceTree = ""; + }; + 298D7C681BC2C88F00FD3B3E /* ADN.net */ = { + isa = PBXGroup; + children = ( + 297824A01BC2D69A0041C395 /* adn_0.cer */, + 297824A11BC2D69A0041C395 /* adn_1.cer */, + 297824A21BC2D69A0041C395 /* adn_2.cer */, + 298D7CDF1BC2CB5A00FD3B3E /* ADNNetServerTrustChain */, + ); + path = ADN.net; + sourceTree = ""; + }; + 298D7C6D1BC2C88F00FD3B3E /* HTTPBin.org */ = { + isa = PBXGroup; + children = ( + 298D7CE21BC2CB7C00FD3B3E /* HTTPBinOrgServerTrustChain */, + 298D7C6E1BC2C88F00FD3B3E /* AddTrust_External_CA_Root.cer */, + 298D7C6F1BC2C88F00FD3B3E /* COMODO_RSA_Certification_Authority.cer */, + 298D7C701BC2C88F00FD3B3E /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer */, + 1FE783001C58579D00A73B7C /* httpbinorg_01192017.cer */, + ); + path = HTTPBin.org; + sourceTree = ""; + }; + 298D7C781BC2C88F00FD3B3E /* SelfSigned */ = { + isa = PBXGroup; + children = ( + 298D7C791BC2C88F00FD3B3E /* AltName.cer */, + 298D7C7A1BC2C88F00FD3B3E /* foobar.com.cer */, + 298D7C7B1BC2C88F00FD3B3E /* NoDomains.cer */, + ); + path = SelfSigned; + sourceTree = ""; + }; + 298D7C7F1BC2C88F00FD3B3E /* Tests */ = { + isa = PBXGroup; + children = ( + 298D7CD21BC2CAD500FD3B3E /* AFNetworking UIKit Tests */, + 298D7CD11BC2CABE00FD3B3E /* AFNetworking Tests */, + 298D7C8A1BC2C88F00FD3B3E /* AFTestCase.h */, + 298D7C8B1BC2C88F00FD3B3E /* AFTestCase.m */, + ); + path = Tests; + sourceTree = ""; + }; + 298D7CD11BC2CABE00FD3B3E /* AFNetworking Tests */ = { + isa = PBXGroup; + children = ( + 298D7C811BC2C88F00FD3B3E /* AFHTTPRequestSerializationTests.m */, + 298D7C821BC2C88F00FD3B3E /* AFHTTPResponseSerializationTests.m */, + 298D7C831BC2C88F00FD3B3E /* AFHTTPSessionManagerTests.m */, + 298D7C851BC2C88F00FD3B3E /* AFJSONSerializationTests.m */, + 298D7C881BC2C88F00FD3B3E /* AFPropertyListResponseSerializerTests.m */, + 29D3413E1C20D46400A7D266 /* AFCompoundResponseSerializerTests.m */, + 298D7C871BC2C88F00FD3B3E /* AFNetworkReachabilityManagerTests.m */, + 298D7C891BC2C88F00FD3B3E /* AFSecurityPolicyTests.m */, + 298D7C8F1BC2C88F00FD3B3E /* AFURLSessionManagerTests.m */, + ); + name = "AFNetworking Tests"; + sourceTree = ""; + }; + 298D7CD21BC2CAD500FD3B3E /* AFNetworking UIKit Tests */ = { + isa = PBXGroup; + children = ( + 298D7C801BC2C88F00FD3B3E /* AFAutoPurgingImageCacheTests.m */, + 298D7C841BC2C88F00FD3B3E /* AFImageDownloaderTests.m */, + 298D7C861BC2C88F00FD3B3E /* AFNetworkActivityManagerTests.m */, + 298D7C8C1BC2C88F00FD3B3E /* AFUIActivityIndicatorViewTests.m */, + 298D7C8D1BC2C88F00FD3B3E /* AFUIImageViewTests.m */, + 298D7C8E1BC2C88F00FD3B3E /* AFUIRefreshControlTests.m */, + 2960BAC21C1B2F1A00BA02F0 /* AFUIButtonTests.m */, + 29F5EF021C47E64F008B976A /* AFUIWebViewTests.m */, + ); + name = "AFNetworking UIKit Tests"; + sourceTree = ""; + }; + 2995222F1BBF104D00859F49 = { + isa = PBXGroup; + children = ( + 299522451BBF125A00859F49 /* AFNetworking */, + 299522851BBF13C700859F49 /* UIKit+AFNetworking */, + 2995223B1BBF104D00859F49 /* Supporting Files */, + 298D7C561BC2C88F00FD3B3E /* Tests */, + 2995223A1BBF104D00859F49 /* Products */, + ); + indentWidth = 4; + sourceTree = ""; + tabWidth = 4; + usesTabs = 0; + }; + 2995223A1BBF104D00859F49 /* Products */ = { + isa = PBXGroup; + children = ( + 299522391BBF104D00859F49 /* AFNetworking.framework */, + 299522651BBF129200859F49 /* AFNetworking.framework */, + 299522771BBF136400859F49 /* AFNetworking.framework */, + 298D7C3B1BC2C79500FD3B3E /* AFNetworking iOS Tests.xctest */, + 298D7C4A1BC2C7B200FD3B3E /* AFNetworking Mac OS X Tests.xctest */, + 2987B0A51BC408A200179A4C /* AFNetworking.framework */, + 2987B0AE1BC408A200179A4C /* AFNetworking tvOS Tests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 2995223B1BBF104D00859F49 /* Supporting Files */ = { + isa = PBXGroup; + children = ( + 2995223C1BBF104D00859F49 /* AFNetworking.h */, + 2995223E1BBF104D00859F49 /* Info.plist */, + ); + name = "Supporting Files"; + path = AFNetworking; + sourceTree = ""; + }; + 299522451BBF125A00859F49 /* AFNetworking */ = { + isa = PBXGroup; + children = ( + 299522461BBF125A00859F49 /* AFHTTPSessionManager.h */, + 299522471BBF125A00859F49 /* AFHTTPSessionManager.m */, + 299522491BBF125A00859F49 /* AFNetworkReachabilityManager.h */, + 2995224A1BBF125A00859F49 /* AFNetworkReachabilityManager.m */, + 2995224B1BBF125A00859F49 /* AFSecurityPolicy.h */, + 2995224C1BBF125A00859F49 /* AFSecurityPolicy.m */, + 2995224D1BBF125A00859F49 /* AFURLRequestSerialization.h */, + 2995224E1BBF125A00859F49 /* AFURLRequestSerialization.m */, + 2995224F1BBF125A00859F49 /* AFURLResponseSerialization.h */, + 299522501BBF125A00859F49 /* AFURLResponseSerialization.m */, + 299522511BBF125A00859F49 /* AFURLSessionManager.h */, + 299522521BBF125A00859F49 /* AFURLSessionManager.m */, + ); + path = AFNetworking; + sourceTree = ""; + }; + 299522851BBF13C700859F49 /* UIKit+AFNetworking */ = { + isa = PBXGroup; + children = ( + 299522861BBF13C700859F49 /* AFAutoPurgingImageCache.h */, + 299522871BBF13C700859F49 /* AFAutoPurgingImageCache.m */, + 299522881BBF13C700859F49 /* AFImageDownloader.h */, + 299522891BBF13C700859F49 /* AFImageDownloader.m */, + 2995228A1BBF13C700859F49 /* AFNetworkActivityIndicatorManager.h */, + 2995228B1BBF13C700859F49 /* AFNetworkActivityIndicatorManager.m */, + 2995228C1BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.h */, + 2995228D1BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.m */, + 299522901BBF13C700859F49 /* UIButton+AFNetworking.h */, + 299522911BBF13C700859F49 /* UIButton+AFNetworking.m */, + 299522921BBF13C700859F49 /* UIImage+AFNetworking.h */, + 299522931BBF13C700859F49 /* UIImageView+AFNetworking.h */, + 299522941BBF13C700859F49 /* UIImageView+AFNetworking.m */, + 299522951BBF13C700859F49 /* UIKit+AFNetworking.h */, + 299522961BBF13C700859F49 /* UIProgressView+AFNetworking.h */, + 299522971BBF13C700859F49 /* UIProgressView+AFNetworking.m */, + 299522981BBF13C700859F49 /* UIRefreshControl+AFNetworking.h */, + 299522991BBF13C700859F49 /* UIRefreshControl+AFNetworking.m */, + 2995229A1BBF13C700859F49 /* UIWebView+AFNetworking.h */, + 2995229B1BBF13C700859F49 /* UIWebView+AFNetworking.m */, + ); + path = "UIKit+AFNetworking"; + sourceTree = ""; + }; + 5F4323B21BF63741003B8749 /* Google.com */ = { + isa = PBXGroup; + children = ( + 5F4323D41BF63CB0003B8749 /* GoogleComServerTrustChainPath1 */, + 5F4323D81BF63CBA003B8749 /* GoogleComServerTrustChainPath2 */, + 5F4323B31BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer */, + 5F4323DC1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer */, + 5F4323B41BF63741003B8749 /* GeoTrust_Global_CA-cross.cer */, + 5F4323BA1BF63741003B8749 /* GoogleInternetAuthorityG2.cer */, + 5F4323B51BF63741003B8749 /* google.com.cer */, + ); + path = Google.com; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 2987B0A21BC408A200179A4C /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 29D96E881BCC3D7D00F571A5 /* AFHTTPSessionManager.h in Headers */, + 29D96E891BCC3D7D00F571A5 /* AFNetworkReachabilityManager.h in Headers */, + 29D96E8A1BCC3D7D00F571A5 /* AFSecurityPolicy.h in Headers */, + 29D96E8B1BCC3D7D00F571A5 /* AFURLRequestSerialization.h in Headers */, + 29D96E8C1BCC3D7D00F571A5 /* AFURLResponseSerialization.h in Headers */, + 29D96E8D1BCC3D7D00F571A5 /* AFURLSessionManager.h in Headers */, + 29D96E941BCC406B00F571A5 /* AFAutoPurgingImageCache.h in Headers */, + 29D96E951BCC406B00F571A5 /* AFImageDownloader.h in Headers */, + 29D96E961BCC406B00F571A5 /* UIActivityIndicatorView+AFNetworking.h in Headers */, + 29D96E971BCC406B00F571A5 /* UIButton+AFNetworking.h in Headers */, + 29D96E981BCC406B00F571A5 /* UIImage+AFNetworking.h in Headers */, + 29D96E991BCC406B00F571A5 /* UIImageView+AFNetworking.h in Headers */, + 29D96E9A1BCC406B00F571A5 /* UIProgressView+AFNetworking.h in Headers */, + 29D96E8E1BCC3D7D00F571A5 /* AFNetworking.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522361BBF104D00859F49 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 2995225A1BBF125A00859F49 /* AFURLRequestSerialization.h in Headers */, + 299522A81BBF13C700859F49 /* UIImage+AFNetworking.h in Headers */, + 299522531BBF125A00859F49 /* AFHTTPSessionManager.h in Headers */, + 2995229C1BBF13C700859F49 /* AFAutoPurgingImageCache.h in Headers */, + 299522581BBF125A00859F49 /* AFSecurityPolicy.h in Headers */, + 299522561BBF125A00859F49 /* AFNetworkReachabilityManager.h in Headers */, + 299522A91BBF13C700859F49 /* UIImageView+AFNetworking.h in Headers */, + 2995229E1BBF13C700859F49 /* AFImageDownloader.h in Headers */, + 2995225E1BBF125A00859F49 /* AFURLSessionManager.h in Headers */, + 2995225C1BBF125A00859F49 /* AFURLResponseSerialization.h in Headers */, + 299522A21BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.h in Headers */, + 2995223D1BBF104D00859F49 /* AFNetworking.h in Headers */, + 299522B01BBF13C700859F49 /* UIWebView+AFNetworking.h in Headers */, + 299522AC1BBF13C700859F49 /* UIProgressView+AFNetworking.h in Headers */, + 299522A61BBF13C700859F49 /* UIButton+AFNetworking.h in Headers */, + 299522A01BBF13C700859F49 /* AFNetworkActivityIndicatorManager.h in Headers */, + 299522AE1BBF13C700859F49 /* UIRefreshControl+AFNetworking.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522621BBF129200859F49 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 29D96E7A1BCC3D6000F571A5 /* AFHTTPSessionManager.h in Headers */, + 29D96E7C1BCC3D6000F571A5 /* AFSecurityPolicy.h in Headers */, + 29D96E7D1BCC3D6000F571A5 /* AFURLRequestSerialization.h in Headers */, + 29D96E7E1BCC3D6000F571A5 /* AFURLResponseSerialization.h in Headers */, + 29D96E7F1BCC3D6000F571A5 /* AFURLSessionManager.h in Headers */, + 29D96E801BCC3D6000F571A5 /* AFNetworking.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522741BBF136400859F49 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 29D96E811BCC3D7200F571A5 /* AFHTTPSessionManager.h in Headers */, + 29D96E821BCC3D7200F571A5 /* AFNetworkReachabilityManager.h in Headers */, + 29D96E831BCC3D7200F571A5 /* AFSecurityPolicy.h in Headers */, + 29D96E841BCC3D7200F571A5 /* AFURLRequestSerialization.h in Headers */, + 29D96E851BCC3D7200F571A5 /* AFURLResponseSerialization.h in Headers */, + 29D96E861BCC3D7200F571A5 /* AFURLSessionManager.h in Headers */, + 29D96E871BCC3D7200F571A5 /* AFNetworking.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 2987B0A41BC408A200179A4C /* AFNetworking tvOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2987B0BA1BC408A200179A4C /* Build configuration list for PBXNativeTarget "AFNetworking tvOS" */; + buildPhases = ( + 2987B0A01BC408A200179A4C /* Sources */, + 2987B0A11BC408A200179A4C /* Frameworks */, + 2987B0A21BC408A200179A4C /* Headers */, + 2987B0A31BC408A200179A4C /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "AFNetworking tvOS"; + productName = "AFNetworking tvOS"; + productReference = 2987B0A51BC408A200179A4C /* AFNetworking.framework */; + productType = "com.apple.product-type.framework"; + }; + 2987B0AD1BC408A200179A4C /* AFNetworking tvOS Tests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2987B0BB1BC408A200179A4C /* Build configuration list for PBXNativeTarget "AFNetworking tvOS Tests" */; + buildPhases = ( + 2987B0AA1BC408A200179A4C /* Sources */, + 2987B0AB1BC408A200179A4C /* Frameworks */, + 2987B0AC1BC408A200179A4C /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 2987B0B11BC408A200179A4C /* PBXTargetDependency */, + ); + name = "AFNetworking tvOS Tests"; + productName = "AFNetworking tvOSTests"; + productReference = 2987B0AE1BC408A200179A4C /* AFNetworking tvOS Tests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 298D7C3A1BC2C79500FD3B3E /* AFNetworking iOS Tests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 298D7C451BC2C79600FD3B3E /* Build configuration list for PBXNativeTarget "AFNetworking iOS Tests" */; + buildPhases = ( + 298D7C371BC2C79500FD3B3E /* Sources */, + 298D7C381BC2C79500FD3B3E /* Frameworks */, + 298D7C391BC2C79500FD3B3E /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 298D7C421BC2C79500FD3B3E /* PBXTargetDependency */, + ); + name = "AFNetworking iOS Tests"; + productName = "AFNetworking iOS Tests"; + productReference = 298D7C3B1BC2C79500FD3B3E /* AFNetworking iOS Tests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 298D7C491BC2C7B200FD3B3E /* AFNetworking Mac OS X Tests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 298D7C521BC2C7B200FD3B3E /* Build configuration list for PBXNativeTarget "AFNetworking Mac OS X Tests" */; + buildPhases = ( + 298D7C461BC2C7B200FD3B3E /* Sources */, + 298D7C471BC2C7B200FD3B3E /* Frameworks */, + 298D7C481BC2C7B200FD3B3E /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 298D7C511BC2C7B200FD3B3E /* PBXTargetDependency */, + ); + name = "AFNetworking Mac OS X Tests"; + productName = "AFNetworking Mac OS X Tests"; + productReference = 298D7C4A1BC2C7B200FD3B3E /* AFNetworking Mac OS X Tests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 299522381BBF104D00859F49 /* AFNetworking iOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 299522411BBF104D00859F49 /* Build configuration list for PBXNativeTarget "AFNetworking iOS" */; + buildPhases = ( + 299522341BBF104D00859F49 /* Sources */, + 299522351BBF104D00859F49 /* Frameworks */, + 299522361BBF104D00859F49 /* Headers */, + 299522371BBF104D00859F49 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "AFNetworking iOS"; + productName = AFNetworking; + productReference = 299522391BBF104D00859F49 /* AFNetworking.framework */; + productType = "com.apple.product-type.framework"; + }; + 299522641BBF129200859F49 /* AFNetworking watchOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2995226A1BBF129200859F49 /* Build configuration list for PBXNativeTarget "AFNetworking watchOS" */; + buildPhases = ( + 299522601BBF129200859F49 /* Sources */, + 299522611BBF129200859F49 /* Frameworks */, + 299522621BBF129200859F49 /* Headers */, + 299522631BBF129200859F49 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "AFNetworking watchOS"; + productName = "AFNetworking watchOS"; + productReference = 299522651BBF129200859F49 /* AFNetworking.framework */; + productType = "com.apple.product-type.framework"; + }; + 299522761BBF136400859F49 /* AFNetworking OS X */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2995227C1BBF136400859F49 /* Build configuration list for PBXNativeTarget "AFNetworking OS X" */; + buildPhases = ( + 299522721BBF136400859F49 /* Sources */, + 299522731BBF136400859F49 /* Frameworks */, + 299522741BBF136400859F49 /* Headers */, + 299522751BBF136400859F49 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "AFNetworking OS X"; + productName = "AFNetworking OS X"; + productReference = 299522771BBF136400859F49 /* AFNetworking.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 299522301BBF104D00859F49 /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0700; + ORGANIZATIONNAME = AFNetworking; + TargetAttributes = { + 2987B0A41BC408A200179A4C = { + CreatedOnToolsVersion = 7.1; + }; + 2987B0AD1BC408A200179A4C = { + CreatedOnToolsVersion = 7.1; + }; + 298D7C3A1BC2C79500FD3B3E = { + CreatedOnToolsVersion = 7.0.1; + }; + 298D7C491BC2C7B200FD3B3E = { + CreatedOnToolsVersion = 7.0.1; + }; + 299522381BBF104D00859F49 = { + CreatedOnToolsVersion = 7.0.1; + }; + 299522641BBF129200859F49 = { + CreatedOnToolsVersion = 7.0.1; + }; + 299522761BBF136400859F49 = { + CreatedOnToolsVersion = 7.0.1; + }; + }; + }; + buildConfigurationList = 299522331BBF104D00859F49 /* Build configuration list for PBXProject "AFNetworking" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 2995222F1BBF104D00859F49; + productRefGroup = 2995223A1BBF104D00859F49 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 299522381BBF104D00859F49 /* AFNetworking iOS */, + 299522641BBF129200859F49 /* AFNetworking watchOS */, + 299522761BBF136400859F49 /* AFNetworking OS X */, + 2987B0A41BC408A200179A4C /* AFNetworking tvOS */, + 298D7C3A1BC2C79500FD3B3E /* AFNetworking iOS Tests */, + 298D7C491BC2C7B200FD3B3E /* AFNetworking Mac OS X Tests */, + 2987B0AD1BC408A200179A4C /* AFNetworking tvOS Tests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 2987B0A31BC408A200179A4C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2987B0AC1BC408A200179A4C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2987B0DE1BC40AFB00179A4C /* foobar.com.cer in Resources */, + 2987B0D61BC40AEC00179A4C /* ADNNetServerTrustChain in Resources */, + 2987B0D91BC40AF300179A4C /* COMODO_RSA_Certification_Authority.cer in Resources */, + 2987B0DF1BC40AFB00179A4C /* NoDomains.cer in Resources */, + 2987B0D41BC40AE900179A4C /* adn_1.cer in Resources */, + 2987B0DD1BC40AFB00179A4C /* AltName.cer in Resources */, + 2987B0D71BC40AF000179A4C /* HTTPBinOrgServerTrustChain in Resources */, + 2987B0D31BC40AE900179A4C /* adn_0.cer in Resources */, + 2987B0DC1BC40AF600179A4C /* logo.png in Resources */, + 2987B0D81BC40AF300179A4C /* AddTrust_External_CA_Root.cer in Resources */, + 2987B0D51BC40AE900179A4C /* adn_2.cer in Resources */, + 2987B0DA1BC40AF300179A4C /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer in Resources */, + 5F4323D71BF63CB0003B8749 /* GoogleComServerTrustChainPath1 in Resources */, + 5F4323DB1BF63CBA003B8749 /* GoogleComServerTrustChainPath2 in Resources */, + 5F4323BD1BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer in Resources */, + 5F4323DF1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer in Resources */, + 1FE783031C5857A200A73B7C /* httpbinorg_01192017.cer in Resources */, + 5F4323C01BF63741003B8749 /* GeoTrust_Global_CA-cross.cer in Resources */, + 5F4323CF1BF63741003B8749 /* GoogleInternetAuthorityG2.cer in Resources */, + 5F4323C31BF63741003B8749 /* google.com.cer in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 298D7C391BC2C79500FD3B3E /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 298D7CC51BC2CAA200FD3B3E /* AddTrust_External_CA_Root.cer in Resources */, + 298D7CBF1BC2CA9D00FD3B3E /* foobar.com.cer in Resources */, + 298D7CBA1BC2CA9800FD3B3E /* logo.png in Resources */, + 298D7CC61BC2CAA200FD3B3E /* COMODO_RSA_Certification_Authority.cer in Resources */, + 297824A31BC2D69A0041C395 /* adn_0.cer in Resources */, + 298D7CC71BC2CAA200FD3B3E /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer in Resources */, + 298D7CE31BC2CB7C00FD3B3E /* HTTPBinOrgServerTrustChain in Resources */, + 297824A71BC2D69A0041C395 /* adn_2.cer in Resources */, + 297824A51BC2D69A0041C395 /* adn_1.cer in Resources */, + 298D7CC01BC2CA9D00FD3B3E /* NoDomains.cer in Resources */, + 298D7CE01BC2CB5A00FD3B3E /* ADNNetServerTrustChain in Resources */, + 298D7CBE1BC2CA9D00FD3B3E /* AltName.cer in Resources */, + 5F4323D51BF63CB0003B8749 /* GoogleComServerTrustChainPath1 in Resources */, + 5F4323D91BF63CBA003B8749 /* GoogleComServerTrustChainPath2 in Resources */, + 5F4323BB1BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer in Resources */, + 5F4323DD1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer in Resources */, + 1FE783011C5857A100A73B7C /* httpbinorg_01192017.cer in Resources */, + 5F4323BE1BF63741003B8749 /* GeoTrust_Global_CA-cross.cer in Resources */, + 5F4323CD1BF63741003B8749 /* GoogleInternetAuthorityG2.cer in Resources */, + 5F4323C11BF63741003B8749 /* google.com.cer in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 298D7C481BC2C7B200FD3B3E /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 298D7CC11BC2CAA100FD3B3E /* AddTrust_External_CA_Root.cer in Resources */, + 298D7CBC1BC2CA9C00FD3B3E /* foobar.com.cer in Resources */, + 298D7CB91BC2CA9800FD3B3E /* logo.png in Resources */, + 298D7CC21BC2CAA100FD3B3E /* COMODO_RSA_Certification_Authority.cer in Resources */, + 297824A41BC2D69A0041C395 /* adn_0.cer in Resources */, + 298D7CC31BC2CAA100FD3B3E /* COMODO_RSA_Domain_Validation_Secure_Server_CA.cer in Resources */, + 298D7CE41BC2CB7C00FD3B3E /* HTTPBinOrgServerTrustChain in Resources */, + 297824A81BC2D69A0041C395 /* adn_2.cer in Resources */, + 297824A61BC2D69A0041C395 /* adn_1.cer in Resources */, + 298D7CBD1BC2CA9C00FD3B3E /* NoDomains.cer in Resources */, + 298D7CE11BC2CB5A00FD3B3E /* ADNNetServerTrustChain in Resources */, + 298D7CBB1BC2CA9C00FD3B3E /* AltName.cer in Resources */, + 5F4323D61BF63CB0003B8749 /* GoogleComServerTrustChainPath1 in Resources */, + 5F4323DA1BF63CBA003B8749 /* GoogleComServerTrustChainPath2 in Resources */, + 5F4323BC1BF63741003B8749 /* Equifax_Secure_Certificate_Authority_Root.cer in Resources */, + 5F4323CE1BF63741003B8749 /* GoogleInternetAuthorityG2.cer in Resources */, + 1FE783021C5857A100A73B7C /* httpbinorg_01192017.cer in Resources */, + 5F4323DE1BF63CCC003B8749 /* GeoTrust_Global_CA_Root.cer in Resources */, + 5F4323BF1BF63741003B8749 /* GeoTrust_Global_CA-cross.cer in Resources */, + 5F4323C21BF63741003B8749 /* google.com.cer in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522371BBF104D00859F49 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522631BBF129200859F49 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522751BBF136400859F49 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 2987B0A01BC408A200179A4C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2987B0BD1BC408D900179A4C /* AFNetworkReachabilityManager.m in Sources */, + 2987B0BE1BC408D900179A4C /* AFSecurityPolicy.m in Sources */, + 2987B0BC1BC408D900179A4C /* AFHTTPSessionManager.m in Sources */, + 2987B0C11BC408D900179A4C /* AFURLSessionManager.m in Sources */, + 2987B0C71BC408F900179A4C /* UIProgressView+AFNetworking.m in Sources */, + 2987B0BF1BC408D900179A4C /* AFURLRequestSerialization.m in Sources */, + 2987B0C21BC408F900179A4C /* AFAutoPurgingImageCache.m in Sources */, + 2987B0C51BC408F900179A4C /* UIButton+AFNetworking.m in Sources */, + 2987B0C41BC408F900179A4C /* UIActivityIndicatorView+AFNetworking.m in Sources */, + 2987B0C01BC408D900179A4C /* AFURLResponseSerialization.m in Sources */, + 2987B0C61BC408F900179A4C /* UIImageView+AFNetworking.m in Sources */, + 2987B0C31BC408F900179A4C /* AFImageDownloader.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2987B0AA1BC408A200179A4C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2987B0CC1BC40A7600179A4C /* AFHTTPSessionManagerTests.m in Sources */, + 2987B0E41BC40B0900179A4C /* AFUIImageViewTests.m in Sources */, + 2987B0D11BC40A7600179A4C /* AFURLSessionManagerTests.m in Sources */, + 2987B0E31BC40B0900179A4C /* AFUIActivityIndicatorViewTests.m in Sources */, + 2987B0D01BC40A7600179A4C /* AFSecurityPolicyTests.m in Sources */, + 2987B0CB1BC40A7600179A4C /* AFHTTPResponseSerializationTests.m in Sources */, + 2987B0CE1BC40A7600179A4C /* AFNetworkReachabilityManagerTests.m in Sources */, + 2987B0E01BC40B0900179A4C /* AFAutoPurgingImageCacheTests.m in Sources */, + 2987B0CA1BC40A7600179A4C /* AFHTTPRequestSerializationTests.m in Sources */, + 29D341411C20D46400A7D266 /* AFCompoundResponseSerializerTests.m in Sources */, + 2987B0E11BC40B0900179A4C /* AFImageDownloaderTests.m in Sources */, + 2987B0CF1BC40A7600179A4C /* AFPropertyListResponseSerializerTests.m in Sources */, + 2987B0D21BC40AD800179A4C /* AFTestCase.m in Sources */, + 2987B0CD1BC40A7600179A4C /* AFJSONSerializationTests.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 298D7C371BC2C79500FD3B3E /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 29D3413F1C20D46400A7D266 /* AFCompoundResponseSerializerTests.m in Sources */, + 2960BAC31C1B2F1A00BA02F0 /* AFUIButtonTests.m in Sources */, + 298D7C961BC2C94400FD3B3E /* AFTestCase.m in Sources */, + 298D7CB11BC2CA6E00FD3B3E /* AFHTTPRequestSerializationTests.m in Sources */, + 297824AE1BC2DBD80041C395 /* AFUIActivityIndicatorViewTests.m in Sources */, + 297824AD1BC2DBA40041C395 /* AFNetworkActivityManagerTests.m in Sources */, + 298D7CDD1BC2CAF700FD3B3E /* AFSecurityPolicyTests.m in Sources */, + 298D7CD31BC2CAE800FD3B3E /* AFHTTPResponseSerializationTests.m in Sources */, + 297824B01BC2DC2D0041C395 /* AFUIImageViewTests.m in Sources */, + 297824AF1BC2DBEF0041C395 /* AFUIRefreshControlTests.m in Sources */, + 298D7CD91BC2CAF200FD3B3E /* AFNetworkReachabilityManagerTests.m in Sources */, + 297824AA1BC2DAD80041C395 /* AFAutoPurgingImageCacheTests.m in Sources */, + 298D7C981BC2CA2500FD3B3E /* AFURLSessionManagerTests.m in Sources */, + 297824AC1BC2DB450041C395 /* AFImageDownloaderTests.m in Sources */, + 29F5EF031C47E64F008B976A /* AFUIWebViewTests.m in Sources */, + 298D7CD51BC2CAEC00FD3B3E /* AFHTTPSessionManagerTests.m in Sources */, + 298D7CD71BC2CAEF00FD3B3E /* AFJSONSerializationTests.m in Sources */, + 298D7CDB1BC2CAF500FD3B3E /* AFPropertyListResponseSerializerTests.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 298D7C461BC2C7B200FD3B3E /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 298D7CD41BC2CAE900FD3B3E /* AFHTTPResponseSerializationTests.m in Sources */, + 29D341401C20D46400A7D266 /* AFCompoundResponseSerializerTests.m in Sources */, + 298D7CB21BC2CA6E00FD3B3E /* AFHTTPRequestSerializationTests.m in Sources */, + 298D7CDE1BC2CAF800FD3B3E /* AFSecurityPolicyTests.m in Sources */, + 298D7C971BC2C94500FD3B3E /* AFTestCase.m in Sources */, + 298D7CD81BC2CAF000FD3B3E /* AFJSONSerializationTests.m in Sources */, + 298D7CDC1BC2CAF500FD3B3E /* AFPropertyListResponseSerializerTests.m in Sources */, + 298D7CD61BC2CAED00FD3B3E /* AFHTTPSessionManagerTests.m in Sources */, + 298D7CDA1BC2CAF300FD3B3E /* AFNetworkReachabilityManagerTests.m in Sources */, + 298D7C991BC2CA2600FD3B3E /* AFURLSessionManagerTests.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522341BBF104D00859F49 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 299522AD1BBF13C700859F49 /* UIProgressView+AFNetworking.m in Sources */, + 299522571BBF125A00859F49 /* AFNetworkReachabilityManager.m in Sources */, + 299522AF1BBF13C700859F49 /* UIRefreshControl+AFNetworking.m in Sources */, + 299522AA1BBF13C700859F49 /* UIImageView+AFNetworking.m in Sources */, + 299522B11BBF13C700859F49 /* UIWebView+AFNetworking.m in Sources */, + 299522591BBF125A00859F49 /* AFSecurityPolicy.m in Sources */, + 299522A71BBF13C700859F49 /* UIButton+AFNetworking.m in Sources */, + 299522541BBF125A00859F49 /* AFHTTPSessionManager.m in Sources */, + 2995225F1BBF125A00859F49 /* AFURLSessionManager.m in Sources */, + 2995225B1BBF125A00859F49 /* AFURLRequestSerialization.m in Sources */, + 2995229D1BBF13C700859F49 /* AFAutoPurgingImageCache.m in Sources */, + 299522A31BBF13C700859F49 /* UIActivityIndicatorView+AFNetworking.m in Sources */, + 2995225D1BBF125A00859F49 /* AFURLResponseSerialization.m in Sources */, + 2995229F1BBF13C700859F49 /* AFImageDownloader.m in Sources */, + 299522A11BBF13C700859F49 /* AFNetworkActivityIndicatorManager.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522601BBF129200859F49 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 299522711BBF133400859F49 /* AFURLSessionManager.m in Sources */, + 2995226F1BBF133400859F49 /* AFURLRequestSerialization.m in Sources */, + 2995226E1BBF133400859F49 /* AFSecurityPolicy.m in Sources */, + 299522701BBF133400859F49 /* AFURLResponseSerialization.m in Sources */, + 2995226D1BBF133400859F49 /* AFHTTPSessionManager.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 299522721BBF136400859F49 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 299522801BBF13A100859F49 /* AFNetworkReachabilityManager.m in Sources */, + 299522811BBF13A100859F49 /* AFSecurityPolicy.m in Sources */, + 2995227F1BBF13A100859F49 /* AFHTTPSessionManager.m in Sources */, + 299522841BBF13A100859F49 /* AFURLSessionManager.m in Sources */, + 299522821BBF13A100859F49 /* AFURLRequestSerialization.m in Sources */, + 299522831BBF13A100859F49 /* AFURLResponseSerialization.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 2987B0B11BC408A200179A4C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 2987B0A41BC408A200179A4C /* AFNetworking tvOS */; + targetProxy = 2987B0B01BC408A200179A4C /* PBXContainerItemProxy */; + }; + 298D7C421BC2C79500FD3B3E /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 299522381BBF104D00859F49 /* AFNetworking iOS */; + targetProxy = 298D7C411BC2C79500FD3B3E /* PBXContainerItemProxy */; + }; + 298D7C511BC2C7B200FD3B3E /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 299522761BBF136400859F49 /* AFNetworking OS X */; + targetProxy = 298D7C501BC2C7B200FD3B3E /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 2987B0B61BC408A200179A4C /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BITCODE_GENERATION_MODE = marker; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = ./Framework/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.alamofire.AFNetworking; + PRODUCT_NAME = AFNetworking; + SDKROOT = appletvos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = 3; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Debug; + }; + 2987B0B71BC408A200179A4C /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BITCODE_GENERATION_MODE = bitcode; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = ./Framework/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.alamofire.AFNetworking; + PRODUCT_NAME = AFNetworking; + SDKROOT = appletvos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = 3; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Release; + }; + 2987B0B81BC408A200179A4C /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + INFOPLIST_FILE = ./Tests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.alamofire.AFNetworking-tvOSTests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = appletvos; + TVOS_DEPLOYMENT_TARGET = 9.0; + }; + name = Debug; + }; + 2987B0B91BC408A200179A4C /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + INFOPLIST_FILE = ./Tests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.alamofire.AFNetworking-tvOSTests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = appletvos; + TVOS_DEPLOYMENT_TARGET = 9.0; + }; + name = Release; + }; + 298D7C431BC2C79500FD3B3E /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_IDENTITY = "iPhone Developer"; + GCC_PREFIX_HEADER = "$(PROJECT_DIR)/Tests/Tests-Prefix.pch"; + INFOPLIST_FILE = ./Tests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.alamofire.AFNetworking-iOS-Tests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 298D7C441BC2C79500FD3B3E /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_IDENTITY = "iPhone Developer"; + GCC_PREFIX_HEADER = "$(PROJECT_DIR)/Tests/Tests-Prefix.pch"; + INFOPLIST_FILE = ./Tests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.alamofire.AFNetworking-iOS-Tests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; + 298D7C531BC2C7B200FD3B3E /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + COMBINE_HIDPI_IMAGES = YES; + GCC_PREFIX_HEADER = "$(PROJECT_DIR)/Tests/Tests-Prefix.pch"; + INFOPLIST_FILE = ./Tests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.9; + PRODUCT_BUNDLE_IDENTIFIER = "com.alamofire.AFNetworking-Mac-OS-X-Tests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = macosx; + }; + name = Debug; + }; + 298D7C541BC2C7B200FD3B3E /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + COMBINE_HIDPI_IMAGES = YES; + GCC_PREFIX_HEADER = "$(PROJECT_DIR)/Tests/Tests-Prefix.pch"; + INFOPLIST_FILE = ./Tests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.9; + PRODUCT_BUNDLE_IDENTIFIER = "com.alamofire.AFNetworking-Mac-OS-X-Tests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = macosx; + }; + name = Release; + }; + 2995223F1BBF104D00859F49 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MACOSX_DEPLOYMENT_TARGET = 10.9; + MODULEMAP_FILE = "$(PROJECT_DIR)/Framework/module.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + TVOS_DEPLOYMENT_TARGET = 9.0; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Debug; + }; + 299522401BBF104D00859F49 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MACOSX_DEPLOYMENT_TARGET = 10.9; + MODULEMAP_FILE = "$(PROJECT_DIR)/Framework/module.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + TVOS_DEPLOYMENT_TARGET = 9.0; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Release; + }; + 299522421BBF104D00859F49 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BITCODE_GENERATION_MODE = marker; + CODE_SIGN_IDENTITY = "iPhone Developer"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_WARN_SHADOW = YES; + INFOPLIST_FILE = ./Framework/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.alamofire.AFNetworking; + PRODUCT_NAME = AFNetworking; + SKIP_INSTALL = YES; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Debug; + }; + 299522431BBF104D00859F49 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BITCODE_GENERATION_MODE = bitcode; + CODE_SIGN_IDENTITY = "iPhone Developer"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_WARN_SHADOW = YES; + INFOPLIST_FILE = ./Framework/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.alamofire.AFNetworking; + PRODUCT_NAME = AFNetworking; + SKIP_INSTALL = YES; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Release; + }; + 2995226B1BBF129200859F49 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BITCODE_GENERATION_MODE = marker; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = ./Framework/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.alamofire.AFNetworking-watchOS"; + PRODUCT_NAME = AFNetworking; + SDKROOT = watchos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = 4; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Debug; + }; + 2995226C1BBF129200859F49 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BITCODE_GENERATION_MODE = bitcode; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = ./Framework/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.alamofire.AFNetworking-watchOS"; + PRODUCT_NAME = AFNetworking; + SDKROOT = watchos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = 4; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Release; + }; + 2995227D1BBF136400859F49 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BITCODE_GENERATION_MODE = marker; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + COMBINE_HIDPI_IMAGES = YES; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + FRAMEWORK_VERSION = A; + INFOPLIST_FILE = ./Framework/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.9; + PRODUCT_BUNDLE_IDENTIFIER = com.alamofire.AFNetworking; + PRODUCT_NAME = AFNetworking; + SDKROOT = macosx; + SKIP_INSTALL = YES; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Debug; + }; + 2995227E1BBF136400859F49 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BITCODE_GENERATION_MODE = bitcode; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + COMBINE_HIDPI_IMAGES = YES; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + FRAMEWORK_VERSION = A; + INFOPLIST_FILE = ./Framework/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.9; + PRODUCT_BUNDLE_IDENTIFIER = com.alamofire.AFNetworking; + PRODUCT_NAME = AFNetworking; + SDKROOT = macosx; + SKIP_INSTALL = YES; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 2987B0BA1BC408A200179A4C /* Build configuration list for PBXNativeTarget "AFNetworking tvOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2987B0B61BC408A200179A4C /* Debug */, + 2987B0B71BC408A200179A4C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2987B0BB1BC408A200179A4C /* Build configuration list for PBXNativeTarget "AFNetworking tvOS Tests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2987B0B81BC408A200179A4C /* Debug */, + 2987B0B91BC408A200179A4C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 298D7C451BC2C79600FD3B3E /* Build configuration list for PBXNativeTarget "AFNetworking iOS Tests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 298D7C431BC2C79500FD3B3E /* Debug */, + 298D7C441BC2C79500FD3B3E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 298D7C521BC2C7B200FD3B3E /* Build configuration list for PBXNativeTarget "AFNetworking Mac OS X Tests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 298D7C531BC2C7B200FD3B3E /* Debug */, + 298D7C541BC2C7B200FD3B3E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 299522331BBF104D00859F49 /* Build configuration list for PBXProject "AFNetworking" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2995223F1BBF104D00859F49 /* Debug */, + 299522401BBF104D00859F49 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 299522411BBF104D00859F49 /* Build configuration list for PBXNativeTarget "AFNetworking iOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 299522421BBF104D00859F49 /* Debug */, + 299522431BBF104D00859F49 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2995226A1BBF129200859F49 /* Build configuration list for PBXNativeTarget "AFNetworking watchOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2995226B1BBF129200859F49 /* Debug */, + 2995226C1BBF129200859F49 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2995227C1BBF136400859F49 /* Build configuration list for PBXNativeTarget "AFNetworking OS X" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2995227D1BBF136400859F49 /* Debug */, + 2995227E1BBF136400859F49 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 299522301BBF104D00859F49 /* Project object */; +} diff --git a/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking OS X.xcscheme b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking OS X.xcscheme new file mode 100644 index 00000000..04cfe1e6 --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking OS X.xcscheme @@ -0,0 +1,105 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking iOS.xcscheme b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking iOS.xcscheme new file mode 100644 index 00000000..e4eb272f --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking iOS.xcscheme @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking tvOS.xcscheme b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking tvOS.xcscheme new file mode 100644 index 00000000..23072b32 --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking tvOS.xcscheme @@ -0,0 +1,104 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking watchOS.xcscheme b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking watchOS.xcscheme new file mode 100644 index 00000000..7f3f3ef6 --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking.xcodeproj/xcshareddata/xcschemes/AFNetworking watchOS.xcscheme @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFHTTPSessionManager.h b/its/plugin/projects/AFNetworking/AFNetworking/AFHTTPSessionManager.h new file mode 100644 index 00000000..61e1042c --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFHTTPSessionManager.h @@ -0,0 +1,295 @@ +// AFHTTPSessionManager.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#if !TARGET_OS_WATCH +#import +#endif +#import + +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV +#import +#else +#import +#endif + +#import "AFURLSessionManager.h" + +/** + `AFHTTPSessionManager` is a subclass of `AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths. + + ## Subclassing Notes + + Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application. + + For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect. + + ## Methods to Override + + To change the behavior of all data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:completionHandler:`. + + ## Serialization + + Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to ``. + + Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `` + + ## URL Construction Using Relative Paths + + For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`. + + Below are a few examples of how `baseURL` and relative paths interact: + + NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"]; + [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo + [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz + [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo + [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo + [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/ + [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/ + + Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash. + + @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. + */ + +NS_ASSUME_NONNULL_BEGIN + +@interface AFHTTPSessionManager : AFURLSessionManager + +/** + The URL used to construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods. + */ +@property (readonly, nonatomic, strong, nullable) NSURL *baseURL; + +/** + Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies. + + @warning `requestSerializer` must not be `nil`. + */ +@property (nonatomic, strong) AFHTTPRequestSerializer * requestSerializer; + +/** + Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`. + + @warning `responseSerializer` must not be `nil`. + */ +@property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Creates and returns an `AFHTTPSessionManager` object. + */ ++ (instancetype)manager; + +/** + Initializes an `AFHTTPSessionManager` object with the specified base URL. + + @param url The base URL for the HTTP client. + + @return The newly-initialized HTTP client + */ +- (instancetype)initWithBaseURL:(nullable NSURL *)url; + +/** + Initializes an `AFHTTPSessionManager` object with the specified base URL. + + This is the designated initializer. + + @param url The base URL for the HTTP client. + @param configuration The configuration used to create the managed session. + + @return The newly-initialized HTTP client + */ +- (instancetype)initWithBaseURL:(nullable NSURL *)url + sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; + +///--------------------------- +/// @name Making HTTP Requests +///--------------------------- + +/** + Creates and runs an `NSURLSessionDataTask` with a `GET` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; + + +/** + Creates and runs an `NSURLSessionDataTask` with a `GET` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param progress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(nullable id)parameters + progress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `HEAD` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes a single arguments: the data task. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; + +/** + Creates and runs an `NSURLSessionDataTask` with a `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param progress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + progress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + constructingBodyWithBlock:(nullable void (^)(id formData))block + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; + +/** + Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. + @param progress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + constructingBodyWithBlock:(nullable void (^)(id formData))block + progress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `PUT` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `PATCH` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `DELETE` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +@end + +NS_ASSUME_NONNULL_END diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFHTTPSessionManager.m b/its/plugin/projects/AFNetworking/AFNetworking/AFHTTPSessionManager.m new file mode 100644 index 00000000..249631bc --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFHTTPSessionManager.m @@ -0,0 +1,361 @@ +// AFHTTPSessionManager.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFHTTPSessionManager.h" + +#import "AFURLRequestSerialization.h" +#import "AFURLResponseSerialization.h" + +#import +#import +#import + +#import +#import +#import +#import +#import + +#if TARGET_OS_IOS || TARGET_OS_TV +#import +#elif TARGET_OS_WATCH +#import +#endif + +@interface AFHTTPSessionManager () +@property (readwrite, nonatomic, strong) NSURL *baseURL; +@end + +@implementation AFHTTPSessionManager +@dynamic responseSerializer; + ++ (instancetype)manager { + return [[[self class] alloc] initWithBaseURL:nil]; +} + +- (instancetype)init { + return [self initWithBaseURL:nil]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url { + return [self initWithBaseURL:url sessionConfiguration:nil]; +} + +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { + return [self initWithBaseURL:nil sessionConfiguration:configuration]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url + sessionConfiguration:(NSURLSessionConfiguration *)configuration +{ + self = [super initWithSessionConfiguration:configuration]; + if (!self) { + return nil; + } + + // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected + if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) { + url = [url URLByAppendingPathComponent:@""]; + } + + self.baseURL = url; + + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + self.responseSerializer = [AFJSONResponseSerializer serializer]; + + return self; +} + +#pragma mark - + +- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { + NSParameterAssert(requestSerializer); + + _requestSerializer = requestSerializer; +} + +- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { + NSParameterAssert(responseSerializer); + + [super setResponseSerializer:responseSerializer]; +} + +#pragma mark - + +- (NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + + return [self GET:URLString parameters:parameters progress:nil success:success failure:failure]; +} + +- (NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(id)parameters + progress:(void (^)(NSProgress * _Nonnull))downloadProgress + success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success + failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure +{ + + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET" + URLString:URLString + parameters:parameters + uploadProgress:nil + downloadProgress:downloadProgress + success:success + failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)HEAD:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, __unused id responseObject) { + if (success) { + success(task); + } + } failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + return [self POST:URLString parameters:parameters progress:nil success:success failure:failure]; +} + +- (NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(id)parameters + progress:(void (^)(NSProgress * _Nonnull))uploadProgress + success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success + failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + constructingBodyWithBlock:(nullable void (^)(id _Nonnull))block + success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure +{ + return [self POST:URLString parameters:parameters constructingBodyWithBlock:block progress:nil success:success failure:failure]; +} + +- (NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(id)parameters + constructingBodyWithBlock:(void (^)(id formData))block + progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSError *serializationError = nil; + NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError]; + if (serializationError) { + if (failure) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ + failure(nil, serializationError); + }); +#pragma clang diagnostic pop + } + + return nil; + } + + __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { + if (error) { + if (failure) { + failure(task, error); + } + } else { + if (success) { + success(task, responseObject); + } + } + }]; + + [task resume]; + + return task; +} + +- (NSURLSessionDataTask *)PUT:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)PATCH:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)DELETE:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(id)parameters + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress + success:(void (^)(NSURLSessionDataTask *, id))success + failure:(void (^)(NSURLSessionDataTask *, NSError *))failure +{ + NSError *serializationError = nil; + NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError]; + if (serializationError) { + if (failure) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ + failure(nil, serializationError); + }); +#pragma clang diagnostic pop + } + + return nil; + } + + __block NSURLSessionDataTask *dataTask = nil; + dataTask = [self dataTaskWithRequest:request + uploadProgress:uploadProgress + downloadProgress:downloadProgress + completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { + if (error) { + if (failure) { + failure(dataTask, error); + } + } else { + if (success) { + success(dataTask, responseObject); + } + } + }]; + + return dataTask; +} + +#pragma mark - NSObject + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue]; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))]; + NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; + if (!configuration) { + NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"]; + if (configurationIdentifier) { +#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1100) + configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier]; +#else + configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:configurationIdentifier]; +#endif + } + } + + self = [self initWithBaseURL:baseURL sessionConfiguration:configuration]; + if (!self) { + return nil; + } + + self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))]; + self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; + AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))]; + if (decodedPolicy) { + self.securityPolicy = decodedPolicy; + } + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))]; + if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) { + [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"]; + } else { + [coder encodeObject:self.session.configuration.identifier forKey:@"identifier"]; + } + [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))]; + [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; + [coder encodeObject:self.securityPolicy forKey:NSStringFromSelector(@selector(securityPolicy))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration]; + + HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone]; + HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone]; + HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone]; + return HTTPClient; +} + +@end diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h b/its/plugin/projects/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h new file mode 100644 index 00000000..88d9181f --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h @@ -0,0 +1,206 @@ +// AFNetworkReachabilityManager.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#if !TARGET_OS_WATCH +#import + +typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { + AFNetworkReachabilityStatusUnknown = -1, + AFNetworkReachabilityStatusNotReachable = 0, + AFNetworkReachabilityStatusReachableViaWWAN = 1, + AFNetworkReachabilityStatusReachableViaWiFi = 2, +}; + +NS_ASSUME_NONNULL_BEGIN + +/** + `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. + + Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability. + + See Apple's Reachability Sample Code (https://developer.apple.com/library/ios/samplecode/reachability/) + + @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined. + */ +@interface AFNetworkReachabilityManager : NSObject + +/** + The current network reachability status. + */ +@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; + +/** + Whether or not the network is currently reachable. + */ +@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable; + +/** + Whether or not the network is currently reachable via WWAN. + */ +@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN; + +/** + Whether or not the network is currently reachable via WiFi. + */ +@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Returns the shared network reachability manager. + */ ++ (instancetype)sharedManager; + +/** + Creates and returns a network reachability manager with the default socket address. + + @return An initialized network reachability manager, actively monitoring the default socket address. + */ ++ (instancetype)manager; + +/** + Creates and returns a network reachability manager for the specified domain. + + @param domain The domain used to evaluate network reachability. + + @return An initialized network reachability manager, actively monitoring the specified domain. + */ ++ (instancetype)managerForDomain:(NSString *)domain; + +/** + Creates and returns a network reachability manager for the socket address. + + @param address The socket address (`sockaddr_in6`) used to evaluate network reachability. + + @return An initialized network reachability manager, actively monitoring the specified socket address. + */ ++ (instancetype)managerForAddress:(const void *)address; + +/** + Initializes an instance of a network reachability manager from the specified reachability object. + + @param reachability The reachability object to monitor. + + @return An initialized network reachability manager, actively monitoring the specified reachability. + */ +- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER; + +///-------------------------------------------------- +/// @name Starting & Stopping Reachability Monitoring +///-------------------------------------------------- + +/** + Starts monitoring for changes in network reachability status. + */ +- (void)startMonitoring; + +/** + Stops monitoring for changes in network reachability status. + */ +- (void)stopMonitoring; + +///------------------------------------------------- +/// @name Getting Localized Reachability Description +///------------------------------------------------- + +/** + Returns a localized string representation of the current network reachability status. + */ +- (NSString *)localizedNetworkReachabilityStatusString; + +///--------------------------------------------------- +/// @name Setting Network Reachability Change Callback +///--------------------------------------------------- + +/** + Sets a callback to be executed when the network availability of the `baseURL` host changes. + + @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`. + */ +- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block; + +@end + +///---------------- +/// @name Constants +///---------------- + +/** + ## Network Reachability + + The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses. + + enum { + AFNetworkReachabilityStatusUnknown, + AFNetworkReachabilityStatusNotReachable, + AFNetworkReachabilityStatusReachableViaWWAN, + AFNetworkReachabilityStatusReachableViaWiFi, + } + + `AFNetworkReachabilityStatusUnknown` + The `baseURL` host reachability is not known. + + `AFNetworkReachabilityStatusNotReachable` + The `baseURL` host cannot be reached. + + `AFNetworkReachabilityStatusReachableViaWWAN` + The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS. + + `AFNetworkReachabilityStatusReachableViaWiFi` + The `baseURL` host can be reached via a Wi-Fi connection. + + ### Keys for Notification UserInfo Dictionary + + Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification. + + `AFNetworkingReachabilityNotificationStatusItem` + A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification. + The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status. + */ + +///-------------------- +/// @name Notifications +///-------------------- + +/** + Posted when network reachability changes. + This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability. + + @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import ` to the header prefix of the project (`Prefix.pch`). + */ +FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification; +FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem; + +///-------------------- +/// @name Functions +///-------------------- + +/** + Returns a localized string representation of an `AFNetworkReachabilityStatus` value. + */ +FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); + +NS_ASSUME_NONNULL_END +#endif diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m b/its/plugin/projects/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m new file mode 100644 index 00000000..d39b81bc --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m @@ -0,0 +1,263 @@ +// AFNetworkReachabilityManager.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFNetworkReachabilityManager.h" +#if !TARGET_OS_WATCH + +#import +#import +#import +#import +#import + +NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change"; +NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem"; + +typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status); + +NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) { + switch (status) { + case AFNetworkReachabilityStatusNotReachable: + return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil); + case AFNetworkReachabilityStatusReachableViaWWAN: + return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil); + case AFNetworkReachabilityStatusReachableViaWiFi: + return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil); + case AFNetworkReachabilityStatusUnknown: + default: + return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil); + } +} + +static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) { + BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0); + BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0); + BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)); + BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0); + BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction)); + + AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown; + if (isNetworkReachable == NO) { + status = AFNetworkReachabilityStatusNotReachable; + } +#if TARGET_OS_IPHONE + else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) { + status = AFNetworkReachabilityStatusReachableViaWWAN; + } +#endif + else { + status = AFNetworkReachabilityStatusReachableViaWiFi; + } + + return status; +} + +/** + * Queue a status change notification for the main thread. + * + * This is done to ensure that the notifications are received in the same order + * as they are sent. If notifications are sent directly, it is possible that + * a queued notification (for an earlier status condition) is processed after + * the later update, resulting in the listener being left in the wrong state. + */ +static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusBlock block) { + AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); + dispatch_async(dispatch_get_main_queue(), ^{ + if (block) { + block(status); + } + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) }; + [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo]; + }); +} + +static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) { + AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusBlock)info); +} + + +static const void * AFNetworkReachabilityRetainCallback(const void *info) { + return Block_copy(info); +} + +static void AFNetworkReachabilityReleaseCallback(const void *info) { + if (info) { + Block_release(info); + } +} + +@interface AFNetworkReachabilityManager () +@property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability; +@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; +@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock; +@end + +@implementation AFNetworkReachabilityManager + ++ (instancetype)sharedManager { + static AFNetworkReachabilityManager *_sharedManager = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _sharedManager = [self manager]; + }); + + return _sharedManager; +} + ++ (instancetype)managerForDomain:(NSString *)domain { + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]); + + AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; + + CFRelease(reachability); + + return manager; +} + ++ (instancetype)managerForAddress:(const void *)address { + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address); + AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; + + CFRelease(reachability); + + return manager; +} + ++ (instancetype)manager +{ +#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + struct sockaddr_in6 address; + bzero(&address, sizeof(address)); + address.sin6_len = sizeof(address); + address.sin6_family = AF_INET6; +#else + struct sockaddr_in address; + bzero(&address, sizeof(address)); + address.sin_len = sizeof(address); + address.sin_family = AF_INET; +#endif + return [self managerForAddress:&address]; +} + +- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability { + self = [super init]; + if (!self) { + return nil; + } + + _networkReachability = CFRetain(reachability); + self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; + + return self; +} + +- (instancetype)init NS_UNAVAILABLE +{ + return nil; +} + +- (void)dealloc { + [self stopMonitoring]; + + if (_networkReachability != NULL) { + CFRelease(_networkReachability); + } +} + +#pragma mark - + +- (BOOL)isReachable { + return [self isReachableViaWWAN] || [self isReachableViaWiFi]; +} + +- (BOOL)isReachableViaWWAN { + return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN; +} + +- (BOOL)isReachableViaWiFi { + return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi; +} + +#pragma mark - + +- (void)startMonitoring { + [self stopMonitoring]; + + if (!self.networkReachability) { + return; + } + + __weak __typeof(self)weakSelf = self; + AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + + strongSelf.networkReachabilityStatus = status; + if (strongSelf.networkReachabilityStatusBlock) { + strongSelf.networkReachabilityStatusBlock(status); + } + + }; + + SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; + SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context); + SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); + + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ + SCNetworkReachabilityFlags flags; + if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) { + AFPostReachabilityStatusChange(flags, callback); + } + }); +} + +- (void)stopMonitoring { + if (!self.networkReachability) { + return; + } + + SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); +} + +#pragma mark - + +- (NSString *)localizedNetworkReachabilityStatusString { + return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus); +} + +#pragma mark - + +- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block { + self.networkReachabilityStatusBlock = block; +} + +#pragma mark - NSKeyValueObserving + ++ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key { + if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) { + return [NSSet setWithObject:@"networkReachabilityStatus"]; + } + + return [super keyPathsForValuesAffectingValueForKey:key]; +} + +@end +#endif diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFNetworking.h b/its/plugin/projects/AFNetworking/AFNetworking/AFNetworking.h new file mode 100644 index 00000000..e2fb2f44 --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFNetworking.h @@ -0,0 +1,41 @@ +// AFNetworking.h +// +// Copyright (c) 2013 AFNetworking (http://afnetworking.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import +#import + +#ifndef _AFNETWORKING_ + #define _AFNETWORKING_ + + #import "AFURLRequestSerialization.h" + #import "AFURLResponseSerialization.h" + #import "AFSecurityPolicy.h" + +#if !TARGET_OS_WATCH + #import "AFNetworkReachabilityManager.h" +#endif + + #import "AFURLSessionManager.h" + #import "AFHTTPSessionManager.h" + +#endif /* _AFNETWORKING_ */ diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFSecurityPolicy.h b/its/plugin/projects/AFNetworking/AFNetworking/AFSecurityPolicy.h new file mode 100644 index 00000000..de3ce924 --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFSecurityPolicy.h @@ -0,0 +1,154 @@ +// AFSecurityPolicy.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import + +typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { + AFSSLPinningModeNone, + AFSSLPinningModePublicKey, + AFSSLPinningModeCertificate, +}; + +/** + `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. + + 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. + */ + +NS_ASSUME_NONNULL_BEGIN + +@interface AFSecurityPolicy : NSObject + +/** + The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`. + */ +@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode; + +/** + 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 target compiling AFNetworking. Note that if you are using AFNetworking as embedded framework, no certificates will be pinned by default. Use `certificatesInBundle` to load certificates from your target, and then create a new policy by calling `policyWithPinningMode:withPinnedCertificates`. + + Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches. + */ +@property (nonatomic, strong, nullable) NSSet *pinnedCertificates; + +/** + Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. + */ +@property (nonatomic, assign) BOOL allowInvalidCertificates; + +/** + Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`. + */ +@property (nonatomic, assign) BOOL validatesDomainName; + +///----------------------------------------- +/// @name Getting Certificates from the Bundle +///----------------------------------------- + +/** + Returns any certificates included in the bundle. If you are using AFNetworking as an embedded framework, you must use this method to find the certificates you have included in your app bundle, and use them when creating your security policy by calling `policyWithPinningMode:withPinnedCertificates`. + + @return The certificates included in the given bundle. + */ ++ (NSSet *)certificatesInBundle:(NSBundle *)bundle; + +///----------------------------------------- +/// @name Getting Specific Security Policies +///----------------------------------------- + +/** + 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. + + @return The default security policy. + */ ++ (instancetype)defaultPolicy; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Creates and returns a security policy with the specified pinning mode. + + @param pinningMode The SSL pinning mode. + + @return A new security policy. + */ ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode; + +/** + Creates and returns a security policy with the specified pinning mode. + + @param pinningMode The SSL pinning mode. + @param pinnedCertificates The certificates to pin against. + + @return A new security policy. + */ ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates; + +///------------------------------ +/// @name Evaluating Server Trust +///------------------------------ + +/** + Whether or not the specified server trust should be accepted, based on the security policy. + + This method should be used when responding to an authentication challenge from a server. + + @param serverTrust The X.509 certificate trust of the server. + @param domain The domain of serverTrust. If `nil`, the domain will not be validated. + + @return Whether or not to trust the server. + */ +- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust + forDomain:(nullable NSString *)domain; + +@end + +NS_ASSUME_NONNULL_END + +///---------------- +/// @name Constants +///---------------- + +/** + ## SSL Pinning Modes + + The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes. + + enum { + AFSSLPinningModeNone, + AFSSLPinningModePublicKey, + AFSSLPinningModeCertificate, + } + + `AFSSLPinningModeNone` + Do not used pinned certificates to validate servers. + + `AFSSLPinningModePublicKey` + Validate host certificates against public keys of pinned certificates. + + `AFSSLPinningModeCertificate` + Validate host certificates against pinned certificates. +*/ diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFSecurityPolicy.m b/its/plugin/projects/AFNetworking/AFNetworking/AFSecurityPolicy.m new file mode 100644 index 00000000..2ec602bd --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFSecurityPolicy.m @@ -0,0 +1,353 @@ +// AFSecurityPolicy.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFSecurityPolicy.h" + +#import + +#if !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV +static NSData * AFSecKeyGetData(SecKeyRef key) { + CFDataRef data = NULL; + + __Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out); + + return (__bridge_transfer NSData *)data; + +_out: + if (data) { + CFRelease(data); + } + + return nil; +} +#endif + +static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) { +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV + return [(__bridge id)key1 isEqual:(__bridge id)key2]; +#else + return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)]; +#endif +} + +static id AFPublicKeyForCertificate(NSData *certificate) { + id allowedPublicKey = nil; + SecCertificateRef allowedCertificate; + SecCertificateRef allowedCertificates[1]; + CFArrayRef tempCertificates = nil; + SecPolicyRef policy = nil; + SecTrustRef allowedTrust = nil; + SecTrustResultType result; + + allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate); + __Require_Quiet(allowedCertificate != NULL, _out); + + allowedCertificates[0] = allowedCertificate; + tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL); + + policy = SecPolicyCreateBasicX509(); + __Require_noErr_Quiet(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out); + __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out); + + allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust); + +_out: + if (allowedTrust) { + CFRelease(allowedTrust); + } + + if (policy) { + CFRelease(policy); + } + + if (tempCertificates) { + CFRelease(tempCertificates); + } + + if (allowedCertificate) { + CFRelease(allowedCertificate); + } + + return allowedPublicKey; +} + +static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) { + BOOL isValid = NO; + SecTrustResultType result; + __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out); + + isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed); + +_out: + return isValid; +} + +static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) { + CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); + NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; + + for (CFIndex i = 0; i < certificateCount; i++) { + SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); + [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]; + } + + return [NSArray arrayWithArray:trustChain]; +} + +static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { + SecPolicyRef policy = SecPolicyCreateBasicX509(); + CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); + NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; + for (CFIndex i = 0; i < certificateCount; i++) { + SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); + + SecCertificateRef someCertificates[] = {certificate}; + CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL); + + SecTrustRef trust; + __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out); + + SecTrustResultType result; + __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out); + + [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)]; + + _out: + if (trust) { + CFRelease(trust); + } + + if (certificates) { + CFRelease(certificates); + } + + continue; + } + CFRelease(policy); + + return [NSArray arrayWithArray:trustChain]; +} + +#pragma mark - + +@interface AFSecurityPolicy() +@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode; +@property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys; +@end + +@implementation AFSecurityPolicy + ++ (NSSet *)certificatesInBundle:(NSBundle *)bundle { + NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; + + NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]]; + for (NSString *path in paths) { + NSData *certificateData = [NSData dataWithContentsOfFile:path]; + [certificates addObject:certificateData]; + } + + return [NSSet setWithSet:certificates]; +} + ++ (NSSet *)defaultPinnedCertificates { + static NSSet *_defaultPinnedCertificates = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSBundle *bundle = [NSBundle bundleForClass:[self class]]; + _defaultPinnedCertificates = [self certificatesInBundle:bundle]; + }); + + return _defaultPinnedCertificates; +} + ++ (instancetype)defaultPolicy { + AFSecurityPolicy *securityPolicy = [[self alloc] init]; + securityPolicy.SSLPinningMode = AFSSLPinningModeNone; + + return securityPolicy; +} + ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode { + return [self policyWithPinningMode:pinningMode withPinnedCertificates:[self defaultPinnedCertificates]]; +} + ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates { + AFSecurityPolicy *securityPolicy = [[self alloc] init]; + securityPolicy.SSLPinningMode = pinningMode; + + [securityPolicy setPinnedCertificates:pinnedCertificates]; + + return securityPolicy; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.validatesDomainName = YES; + + return self; +} + +- (void)setPinnedCertificates:(NSSet *)pinnedCertificates { + _pinnedCertificates = pinnedCertificates; + + if (self.pinnedCertificates) { + NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]]; + for (NSData *certificate in self.pinnedCertificates) { + id publicKey = AFPublicKeyForCertificate(certificate); + if (!publicKey) { + continue; + } + [mutablePinnedPublicKeys addObject:publicKey]; + } + self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys]; + } else { + self.pinnedPublicKeys = nil; + } +} + +#pragma mark - + +- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust + forDomain:(NSString *)domain +{ + if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) { + // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html + // According to the docs, you should only trust your provided certs for evaluation. + // Pinned certificates are added to the trust. Without pinned certificates, + // there is nothing to evaluate against. + // + // From Apple Docs: + // "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors). + // Instead, add your own (self-signed) CA certificate to the list of trusted anchors." + NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning."); + return NO; + } + + NSMutableArray *policies = [NSMutableArray array]; + if (self.validatesDomainName) { + [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)]; + } else { + [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()]; + } + + SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies); + + if (self.SSLPinningMode == AFSSLPinningModeNone) { + return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust); + } else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) { + return NO; + } + + switch (self.SSLPinningMode) { + case AFSSLPinningModeNone: + default: + return NO; + case AFSSLPinningModeCertificate: { + NSMutableArray *pinnedCertificates = [NSMutableArray array]; + for (NSData *certificateData in self.pinnedCertificates) { + [pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)]; + } + SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates); + + if (!AFServerTrustIsValid(serverTrust)) { + return NO; + } + + // obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA) + NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); + + for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) { + if ([self.pinnedCertificates containsObject:trustChainCertificate]) { + return YES; + } + } + + return NO; + } + case AFSSLPinningModePublicKey: { + NSUInteger trustedPublicKeyCount = 0; + NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust); + + for (id trustChainPublicKey in publicKeys) { + for (id pinnedPublicKey in self.pinnedPublicKeys) { + if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) { + trustedPublicKeyCount += 1; + } + } + } + return trustedPublicKeyCount > 0; + } + } + + return NO; +} + +#pragma mark - NSKeyValueObserving + ++ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys { + return [NSSet setWithObject:@"pinnedCertificates"]; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + + self = [self init]; + if (!self) { + return nil; + } + + self.SSLPinningMode = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(SSLPinningMode))] unsignedIntegerValue]; + self.allowInvalidCertificates = [decoder decodeBoolForKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; + self.validatesDomainName = [decoder decodeBoolForKey:NSStringFromSelector(@selector(validatesDomainName))]; + self.pinnedCertificates = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(pinnedCertificates))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:[NSNumber numberWithUnsignedInteger:self.SSLPinningMode] forKey:NSStringFromSelector(@selector(SSLPinningMode))]; + [coder encodeBool:self.allowInvalidCertificates forKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; + [coder encodeBool:self.validatesDomainName forKey:NSStringFromSelector(@selector(validatesDomainName))]; + [coder encodeObject:self.pinnedCertificates forKey:NSStringFromSelector(@selector(pinnedCertificates))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init]; + securityPolicy.SSLPinningMode = self.SSLPinningMode; + securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates; + securityPolicy.validatesDomainName = self.validatesDomainName; + securityPolicy.pinnedCertificates = [self.pinnedCertificates copyWithZone:zone]; + + return securityPolicy; +} + +@end diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFURLRequestSerialization.h b/its/plugin/projects/AFNetworking/AFNetworking/AFURLRequestSerialization.h new file mode 100644 index 00000000..a6f179bf --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFURLRequestSerialization.h @@ -0,0 +1,479 @@ +// AFURLRequestSerialization.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import + +#if TARGET_OS_IOS || TARGET_OS_TV +#import +#elif TARGET_OS_WATCH +#import +#endif + +NS_ASSUME_NONNULL_BEGIN + +/** + Returns a percent-escaped string following RFC 3986 for a query string key or value. + RFC 3986 states that the following characters are "reserved" characters. + - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + should be percent-escaped in the query string. + + @param string The string to be percent-escaped. + + @return The percent-escaped string. + */ +FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string); + +/** + A helper method to generate encoded url query parameters for appending to the end of a URL. + + @param parameters A dictionary of key/values to be encoded. + + @return A url encoded query string + */ +FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameters); + +/** + The `AFURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary. + + For example, a JSON request serializer may set the HTTP body of the request to a JSON representation, and set the `Content-Type` HTTP header field value to `application/json`. + */ +@protocol AFURLRequestSerialization + +/** + Returns a request with the specified parameters encoded into a copy of the original request. + + @param request The original request. + @param parameters The parameters to be encoded. + @param error The error that occurred while attempting to encode the request parameters. + + @return A serialized request. + */ +- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(nullable id)parameters + error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; + +@end + +#pragma mark - + +/** + + */ +typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) { + AFHTTPRequestQueryStringDefaultStyle = 0, +}; + +@protocol AFMultipartFormData; + +/** + `AFHTTPRequestSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation. + + Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior. + */ +@interface AFHTTPRequestSerializer : NSObject + +/** + The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default. + */ +@property (nonatomic, assign) NSStringEncoding stringEncoding; + +/** + Whether created requests can use the device’s cellular radio (if present). `YES` by default. + + @see NSMutableURLRequest -setAllowsCellularAccess: + */ +@property (nonatomic, assign) BOOL allowsCellularAccess; + +/** + The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default. + + @see NSMutableURLRequest -setCachePolicy: + */ +@property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy; + +/** + Whether created requests should use the default cookie handling. `YES` by default. + + @see NSMutableURLRequest -setHTTPShouldHandleCookies: + */ +@property (nonatomic, assign) BOOL HTTPShouldHandleCookies; + +/** + Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default + + @see NSMutableURLRequest -setHTTPShouldUsePipelining: + */ +@property (nonatomic, assign) BOOL HTTPShouldUsePipelining; + +/** + The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default. + + @see NSMutableURLRequest -setNetworkServiceType: + */ +@property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType; + +/** + The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds. + + @see NSMutableURLRequest -setTimeoutInterval: + */ +@property (nonatomic, assign) NSTimeInterval timeoutInterval; + +///--------------------------------------- +/// @name Configuring HTTP Request Headers +///--------------------------------------- + +/** + Default HTTP header field values to be applied to serialized requests. By default, these include the following: + + - `Accept-Language` with the contents of `NSLocale +preferredLanguages` + - `User-Agent` with the contents of various bundle identifiers and OS designations + + @discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *HTTPRequestHeaders; + +/** + Creates and returns a serializer with default configuration. + */ ++ (instancetype)serializer; + +/** + Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header. + + @param field The HTTP header to set a default value for + @param value The value set as default for the specified header, or `nil` + */ +- (void)setValue:(nullable NSString *)value +forHTTPHeaderField:(NSString *)field; + +/** + Returns the value for the HTTP headers set in the request serializer. + + @param field The HTTP header to retrieve the default value for + + @return The value set as default for the specified header, or `nil` + */ +- (nullable NSString *)valueForHTTPHeaderField:(NSString *)field; + +/** + Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header. + + @param username The HTTP basic auth username + @param password The HTTP basic auth password + */ +- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username + password:(NSString *)password; + +/** + Clears any existing value for the "Authorization" HTTP header. + */ +- (void)clearAuthorizationHeader; + +///------------------------------------------------------- +/// @name Configuring Query String Parameter Serialization +///------------------------------------------------------- + +/** + HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default. + */ +@property (nonatomic, strong) NSSet *HTTPMethodsEncodingParametersInURI; + +/** + Set the method of query string serialization according to one of the pre-defined styles. + + @param style The serialization style. + + @see AFHTTPRequestQueryStringSerializationStyle + */ +- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style; + +/** + Set the a custom method of query string serialization according to the specified block. + + @param block A block that defines a process of encoding parameters into a query string. This block returns the query string and takes three arguments: the request, the parameters to encode, and the error that occurred when attempting to encode parameters for the given request. + */ +- (void)setQueryStringSerializationWithBlock:(nullable NSString * (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block; + +///------------------------------- +/// @name Creating Request Objects +///------------------------------- + +/** + Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string. + + If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body. + + @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`. + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body. + @param error The error that occurred while constructing the request. + + @return An `NSMutableURLRequest` object. + */ +- (NSMutableURLRequest *)requestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(nullable id)parameters + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Creates an `NSMutableURLRequest` object with the specified HTTP method and URLString, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2 + + Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream. + + @param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`. + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded and set in the request HTTP body. + @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. + @param error The error that occurred while constructing the request. + + @return An `NSMutableURLRequest` object + */ +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(nullable NSDictionary *)parameters + constructingBodyWithBlock:(nullable void (^)(id formData))block + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Creates an `NSMutableURLRequest` by removing the `HTTPBodyStream` from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished. + + @param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`. + @param fileURL The file URL to write multipart form contents to. + @param handler A handler block to execute. + + @discussion There is a bug in `NSURLSessionTask` that causes requests to not send a `Content-Length` header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:`, or any other request with an `HTTPBodyStream`, writes the contents to the specified file and returns a copy of the original request with the `HTTPBodyStream` property set to `nil`. From here, the file can either be passed to `AFURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:`, or have its contents read into an `NSData` that's assigned to the `HTTPBody` property of the request. + + @see https://github.com/AFNetworking/AFNetworking/issues/1398 + */ +- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request + writingStreamContentsToFile:(NSURL *)fileURL + completionHandler:(nullable void (^)(NSError * _Nullable error))handler; + +@end + +#pragma mark - + +/** + The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`. + */ +@protocol AFMultipartFormData + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary. + + The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively. + + @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + @param error If an error occurs, upon return contains an `NSError` object that describes the problem. + + @return `YES` if the file data was successfully appended, otherwise `NO`. + */ +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. + + @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`. + @param mimeType The declared MIME type of the file data. This parameter must not be `nil`. + @param error If an error occurs, upon return contains an `NSError` object that describes the problem. + + @return `YES` if the file data was successfully appended otherwise `NO`. + */ +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary. + + @param inputStream The input stream to be appended to the form data + @param name The name to be associated with the specified input stream. This parameter must not be `nil`. + @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`. + @param length The length of the specified input stream in bytes. + @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. + */ +- (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream + name:(NSString *)name + fileName:(NSString *)fileName + length:(int64_t)length + mimeType:(NSString *)mimeType; + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. + + @param data The data to be encoded and appended to the form data. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + @param fileName The filename to be associated with the specified data. This parameter must not be `nil`. + @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. + */ +- (void)appendPartWithFileData:(NSData *)data + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType; + +/** + Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary. + + @param data The data to be encoded and appended to the form data. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + */ + +- (void)appendPartWithFormData:(NSData *)data + name:(NSString *)name; + + +/** + Appends HTTP headers, followed by the encoded data and the multipart form boundary. + + @param headers The HTTP headers to be appended to the form data. + @param body The data to be encoded and appended to the form data. This parameter must not be `nil`. + */ +- (void)appendPartWithHeaders:(nullable NSDictionary *)headers + body:(NSData *)body; + +/** + Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream. + + When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over `NSURLConnection`. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth. + + @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb. + @param delay Duration of delay each time a packet is read. By default, no delay is set. + */ +- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes + delay:(NSTimeInterval)delay; + +@end + +#pragma mark - + +/** + `AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`. + */ +@interface AFJSONRequestSerializer : AFHTTPRequestSerializer + +/** + Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default. + */ +@property (nonatomic, assign) NSJSONWritingOptions writingOptions; + +/** + Creates and returns a JSON serializer with specified reading and writing options. + + @param writingOptions The specified JSON writing options. + */ ++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions; + +@end + +#pragma mark - + +/** + `AFPropertyListRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSPropertyListSerializer`, setting the `Content-Type` of the encoded request to `application/x-plist`. + */ +@interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer + +/** + The property list format. Possible values are described in "NSPropertyListFormat". + */ +@property (nonatomic, assign) NSPropertyListFormat format; + +/** + @warning The `writeOptions` property is currently unused. + */ +@property (nonatomic, assign) NSPropertyListWriteOptions writeOptions; + +/** + Creates and returns a property list serializer with a specified format, read options, and write options. + + @param format The property list format. + @param writeOptions The property list write options. + + @warning The `writeOptions` property is currently unused. + */ ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + writeOptions:(NSPropertyListWriteOptions)writeOptions; + +@end + +#pragma mark - + +///---------------- +/// @name Constants +///---------------- + +/** + ## Error Domains + + The following error domain is predefined. + + - `NSString * const AFURLRequestSerializationErrorDomain` + + ### Constants + + `AFURLRequestSerializationErrorDomain` + AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain; + +/** + ## User info dictionary keys + + These keys may exist in the user info dictionary, in addition to those defined for NSError. + + - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey` + + ### Constants + + `AFNetworkingOperationFailingURLRequestErrorKey` + The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey; + +/** + ## Throttling Bandwidth for HTTP Request Input Streams + + @see -throttleBandwidthWithPacketSize:delay: + + ### Constants + + `kAFUploadStream3GSuggestedPacketSize` + Maximum packet size, in number of bytes. Equal to 16kb. + + `kAFUploadStream3GSuggestedDelay` + Duration of delay each time a packet is read. Equal to 0.2 seconds. + */ +FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize; +FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay; + +NS_ASSUME_NONNULL_END diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFURLRequestSerialization.m b/its/plugin/projects/AFNetworking/AFNetworking/AFURLRequestSerialization.m new file mode 100644 index 00000000..086e6747 --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFURLRequestSerialization.m @@ -0,0 +1,1376 @@ +// AFURLRequestSerialization.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFURLRequestSerialization.h" + +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV +#import +#else +#import +#endif + +NSString * const AFURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request"; +NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response"; + +typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id parameters, NSError *__autoreleasing *error); + +/** + Returns a percent-escaped string following RFC 3986 for a query string key or value. + RFC 3986 states that the following characters are "reserved" characters. + - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + should be percent-escaped in the query string. + - parameter string: The string to be percent-escaped. + - returns: The percent-escaped string. + */ +NSString * AFPercentEscapedStringFromString(NSString *string) { + static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4 + static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;="; + + NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; + [allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]]; + + // FIXME: https://github.com/AFNetworking/AFNetworking/pull/3028 + // return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + + static NSUInteger const batchSize = 50; + + NSUInteger index = 0; + NSMutableString *escaped = @"".mutableCopy; + + while (index < string.length) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wgnu" + NSUInteger length = MIN(string.length - index, batchSize); +#pragma GCC diagnostic pop + NSRange range = NSMakeRange(index, length); + + // To avoid breaking up character sequences such as 👴🏻👮🏽 + range = [string rangeOfComposedCharacterSequencesForRange:range]; + + NSString *substring = [string substringWithRange:range]; + NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + [escaped appendString:encoded]; + + index += range.length; + } + + return escaped; +} + +#pragma mark - + +@interface AFQueryStringPair : NSObject +@property (readwrite, nonatomic, strong) id field; +@property (readwrite, nonatomic, strong) id value; + +- (instancetype)initWithField:(id)field value:(id)value; + +- (NSString *)URLEncodedStringValue; +@end + +@implementation AFQueryStringPair + +- (instancetype)initWithField:(id)field value:(id)value { + self = [super init]; + if (!self) { + return nil; + } + + self.field = field; + self.value = value; + + return self; +} + +- (NSString *)URLEncodedStringValue { + if (!self.value || [self.value isEqual:[NSNull null]]) { + return AFPercentEscapedStringFromString([self.field description]); + } else { + return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedStringFromString([self.field description]), AFPercentEscapedStringFromString([self.value description])]; + } +} + +@end + +#pragma mark - + +FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary); +FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value); + +NSString * AFQueryStringFromParameters(NSDictionary *parameters) { + NSMutableArray *mutablePairs = [NSMutableArray array]; + for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { + [mutablePairs addObject:[pair URLEncodedStringValue]]; + } + + return [mutablePairs componentsJoinedByString:@"&"]; +} + +NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) { + return AFQueryStringPairsFromKeyAndValue(nil, dictionary); +} + +NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) { + NSMutableArray *mutableQueryStringComponents = [NSMutableArray array]; + + NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)]; + + if ([value isKindOfClass:[NSDictionary class]]) { + NSDictionary *dictionary = value; + // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries + for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { + id nestedValue = dictionary[nestedKey]; + if (nestedValue) { + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)]; + } + } + } else if ([value isKindOfClass:[NSArray class]]) { + NSArray *array = value; + for (id nestedValue in array) { + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)]; + } + } else if ([value isKindOfClass:[NSSet class]]) { + NSSet *set = value; + for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)]; + } + } else { + [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]]; + } + + return mutableQueryStringComponents; +} + +#pragma mark - + +@interface AFStreamingMultipartFormData : NSObject +- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest + stringEncoding:(NSStringEncoding)encoding; + +- (NSMutableURLRequest *)requestByFinalizingMultipartFormData; +@end + +#pragma mark - + +static NSArray * AFHTTPRequestSerializerObservedKeyPaths() { + static NSArray *_AFHTTPRequestSerializerObservedKeyPaths = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))]; + }); + + return _AFHTTPRequestSerializerObservedKeyPaths; +} + +static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerObserverContext; + +@interface AFHTTPRequestSerializer () +@property (readwrite, nonatomic, strong) NSMutableSet *mutableObservedChangedKeyPaths; +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders; +@property (readwrite, nonatomic, assign) AFHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle; +@property (readwrite, nonatomic, copy) AFQueryStringSerializationBlock queryStringSerialization; +@end + +@implementation AFHTTPRequestSerializer + ++ (instancetype)serializer { + return [[self alloc] init]; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.stringEncoding = NSUTF8StringEncoding; + + self.mutableHTTPRequestHeaders = [NSMutableDictionary dictionary]; + + // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 + NSMutableArray *acceptLanguagesComponents = [NSMutableArray array]; + [[NSLocale preferredLanguages] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + float q = 1.0f - (idx * 0.1f); + [acceptLanguagesComponents addObject:[NSString stringWithFormat:@"%@;q=%0.1g", obj, q]]; + *stop = q <= 0.5f; + }]; + [self setValue:[acceptLanguagesComponents componentsJoinedByString:@", "] forHTTPHeaderField:@"Accept-Language"]; + + NSString *userAgent = nil; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" +#if TARGET_OS_IOS + // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 + userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; +#elif TARGET_OS_WATCH + // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 + userAgent = [NSString stringWithFormat:@"%@/%@ (%@; watchOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[WKInterfaceDevice currentDevice] model], [[WKInterfaceDevice currentDevice] systemVersion], [[WKInterfaceDevice currentDevice] screenScale]]; +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) + userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]]; +#endif +#pragma clang diagnostic pop + if (userAgent) { + if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) { + NSMutableString *mutableUserAgent = [userAgent mutableCopy]; + if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) { + userAgent = mutableUserAgent; + } + } + [self setValue:userAgent forHTTPHeaderField:@"User-Agent"]; + } + + // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html + self.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil]; + + self.mutableObservedChangedKeyPaths = [NSMutableSet set]; + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { + if ([self respondsToSelector:NSSelectorFromString(keyPath)]) { + [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext]; + } + } + + return self; +} + +- (void)dealloc { + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { + if ([self respondsToSelector:NSSelectorFromString(keyPath)]) { + [self removeObserver:self forKeyPath:keyPath context:AFHTTPRequestSerializerObserverContext]; + } + } +} + +#pragma mark - + +// Workarounds for crashing behavior using Key-Value Observing with XCTest +// See https://github.com/AFNetworking/AFNetworking/issues/2523 + +- (void)setAllowsCellularAccess:(BOOL)allowsCellularAccess { + [self willChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))]; + _allowsCellularAccess = allowsCellularAccess; + [self didChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))]; +} + +- (void)setCachePolicy:(NSURLRequestCachePolicy)cachePolicy { + [self willChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))]; + _cachePolicy = cachePolicy; + [self didChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))]; +} + +- (void)setHTTPShouldHandleCookies:(BOOL)HTTPShouldHandleCookies { + [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))]; + _HTTPShouldHandleCookies = HTTPShouldHandleCookies; + [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))]; +} + +- (void)setHTTPShouldUsePipelining:(BOOL)HTTPShouldUsePipelining { + [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))]; + _HTTPShouldUsePipelining = HTTPShouldUsePipelining; + [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))]; +} + +- (void)setNetworkServiceType:(NSURLRequestNetworkServiceType)networkServiceType { + [self willChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))]; + _networkServiceType = networkServiceType; + [self didChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))]; +} + +- (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval { + [self willChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))]; + _timeoutInterval = timeoutInterval; + [self didChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))]; +} + +#pragma mark - + +- (NSDictionary *)HTTPRequestHeaders { + return [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders]; +} + +- (void)setValue:(NSString *)value +forHTTPHeaderField:(NSString *)field +{ + [self.mutableHTTPRequestHeaders setValue:value forKey:field]; +} + +- (NSString *)valueForHTTPHeaderField:(NSString *)field { + return [self.mutableHTTPRequestHeaders valueForKey:field]; +} + +- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username + password:(NSString *)password +{ + NSData *basicAuthCredentials = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding]; + NSString *base64AuthCredentials = [basicAuthCredentials base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0]; + [self setValue:[NSString stringWithFormat:@"Basic %@", base64AuthCredentials] forHTTPHeaderField:@"Authorization"]; +} + +- (void)clearAuthorizationHeader { + [self.mutableHTTPRequestHeaders removeObjectForKey:@"Authorization"]; +} + +#pragma mark - + +- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style { + self.queryStringSerializationStyle = style; + self.queryStringSerialization = nil; +} + +- (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, id, NSError *__autoreleasing *))block { + self.queryStringSerialization = block; +} + +#pragma mark - + +- (NSMutableURLRequest *)requestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(method); + NSParameterAssert(URLString); + + NSURL *url = [NSURL URLWithString:URLString]; + + NSParameterAssert(url); + + NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url]; + mutableRequest.HTTPMethod = method; + + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { + if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) { + [mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath]; + } + } + + mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy]; + + return mutableRequest; +} + +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(NSDictionary *)parameters + constructingBodyWithBlock:(void (^)(id formData))block + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(method); + NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]); + + NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error]; + + __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding]; + + if (parameters) { + for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { + NSData *data = nil; + if ([pair.value isKindOfClass:[NSData class]]) { + data = pair.value; + } else if ([pair.value isEqual:[NSNull null]]) { + data = [NSData data]; + } else { + data = [[pair.value description] dataUsingEncoding:self.stringEncoding]; + } + + if (data) { + [formData appendPartWithFormData:data name:[pair.field description]]; + } + } + } + + if (block) { + block(formData); + } + + return [formData requestByFinalizingMultipartFormData]; +} + +- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request + writingStreamContentsToFile:(NSURL *)fileURL + completionHandler:(void (^)(NSError *error))handler +{ + NSParameterAssert(request.HTTPBodyStream); + NSParameterAssert([fileURL isFileURL]); + + NSInputStream *inputStream = request.HTTPBodyStream; + NSOutputStream *outputStream = [[NSOutputStream alloc] initWithURL:fileURL append:NO]; + __block NSError *error = nil; + + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + + [inputStream open]; + [outputStream open]; + + while ([inputStream hasBytesAvailable] && [outputStream hasSpaceAvailable]) { + uint8_t buffer[1024]; + + NSInteger bytesRead = [inputStream read:buffer maxLength:1024]; + if (inputStream.streamError || bytesRead < 0) { + error = inputStream.streamError; + break; + } + + NSInteger bytesWritten = [outputStream write:buffer maxLength:(NSUInteger)bytesRead]; + if (outputStream.streamError || bytesWritten < 0) { + error = outputStream.streamError; + break; + } + + if (bytesRead == 0 && bytesWritten == 0) { + break; + } + } + + [outputStream close]; + [inputStream close]; + + if (handler) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler(error); + }); + } + }); + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + mutableRequest.HTTPBodyStream = nil; + + return mutableRequest; +} + +#pragma mark - AFURLRequestSerialization + +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(request); + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { + if (![request valueForHTTPHeaderField:field]) { + [mutableRequest setValue:value forHTTPHeaderField:field]; + } + }]; + + NSString *query = nil; + if (parameters) { + if (self.queryStringSerialization) { + NSError *serializationError; + query = self.queryStringSerialization(request, parameters, &serializationError); + + if (serializationError) { + if (error) { + *error = serializationError; + } + + return nil; + } + } else { + switch (self.queryStringSerializationStyle) { + case AFHTTPRequestQueryStringDefaultStyle: + query = AFQueryStringFromParameters(parameters); + break; + } + } + } + + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + if (query) { + mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]]; + } + } else { + // #2864: an empty string is a valid x-www-form-urlencoded payload + if (!query) { + query = @""; + } + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { + [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; + } + [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]]; + } + + return mutableRequest; +} + +#pragma mark - NSKeyValueObserving + ++ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key { + if ([AFHTTPRequestSerializerObservedKeyPaths() containsObject:key]) { + return NO; + } + + return [super automaticallyNotifiesObserversForKey:key]; +} + +- (void)observeValueForKeyPath:(NSString *)keyPath + ofObject:(__unused id)object + change:(NSDictionary *)change + context:(void *)context +{ + if (context == AFHTTPRequestSerializerObserverContext) { + if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) { + [self.mutableObservedChangedKeyPaths removeObject:keyPath]; + } else { + [self.mutableObservedChangedKeyPaths addObject:keyPath]; + } + } +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [self init]; + if (!self) { + return nil; + } + + self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy]; + self.queryStringSerializationStyle = (AFHTTPRequestQueryStringSerializationStyle)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))]; + [coder encodeInteger:self.queryStringSerializationStyle forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone]; + serializer.queryStringSerializationStyle = self.queryStringSerializationStyle; + serializer.queryStringSerialization = self.queryStringSerialization; + + return serializer; +} + +@end + +#pragma mark - + +static NSString * AFCreateMultipartFormBoundary() { + return [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()]; +} + +static NSString * const kAFMultipartFormCRLF = @"\r\n"; + +static inline NSString * AFMultipartFormInitialBoundary(NSString *boundary) { + return [NSString stringWithFormat:@"--%@%@", boundary, kAFMultipartFormCRLF]; +} + +static inline NSString * AFMultipartFormEncapsulationBoundary(NSString *boundary) { + return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF]; +} + +static inline NSString * AFMultipartFormFinalBoundary(NSString *boundary) { + return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF]; +} + +static inline NSString * AFContentTypeForPathExtension(NSString *extension) { + NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL); + NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType); + if (!contentType) { + return @"application/octet-stream"; + } else { + return contentType; + } +} + +NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16; +NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2; + +@interface AFHTTPBodyPart : NSObject +@property (nonatomic, assign) NSStringEncoding stringEncoding; +@property (nonatomic, strong) NSDictionary *headers; +@property (nonatomic, copy) NSString *boundary; +@property (nonatomic, strong) id body; +@property (nonatomic, assign) unsigned long long bodyContentLength; +@property (nonatomic, strong) NSInputStream *inputStream; + +@property (nonatomic, assign) BOOL hasInitialBoundary; +@property (nonatomic, assign) BOOL hasFinalBoundary; + +@property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable; +@property (readonly, nonatomic, assign) unsigned long long contentLength; + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length; +@end + +@interface AFMultipartBodyStream : NSInputStream +@property (nonatomic, assign) NSUInteger numberOfBytesInPacket; +@property (nonatomic, assign) NSTimeInterval delay; +@property (nonatomic, strong) NSInputStream *inputStream; +@property (readonly, nonatomic, assign) unsigned long long contentLength; +@property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty; + +- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding; +- (void)setInitialAndFinalBoundaries; +- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart; +@end + +#pragma mark - + +@interface AFStreamingMultipartFormData () +@property (readwrite, nonatomic, copy) NSMutableURLRequest *request; +@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding; +@property (readwrite, nonatomic, copy) NSString *boundary; +@property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream; +@end + +@implementation AFStreamingMultipartFormData + +- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest + stringEncoding:(NSStringEncoding)encoding +{ + self = [super init]; + if (!self) { + return nil; + } + + self.request = urlRequest; + self.stringEncoding = encoding; + self.boundary = AFCreateMultipartFormBoundary(); + self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding]; + + return self; +} + +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + error:(NSError * __autoreleasing *)error +{ + NSParameterAssert(fileURL); + NSParameterAssert(name); + + NSString *fileName = [fileURL lastPathComponent]; + NSString *mimeType = AFContentTypeForPathExtension([fileURL pathExtension]); + + return [self appendPartWithFileURL:fileURL name:name fileName:fileName mimeType:mimeType error:error]; +} + +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType + error:(NSError * __autoreleasing *)error +{ + NSParameterAssert(fileURL); + NSParameterAssert(name); + NSParameterAssert(fileName); + NSParameterAssert(mimeType); + + if (![fileURL isFileURL]) { + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil)}; + if (error) { + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; + } + + return NO; + } else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) { + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil)}; + if (error) { + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; + } + + return NO; + } + + NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:error]; + if (!fileAttributes) { + return NO; + } + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; + [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; + + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = mutableHeaders; + bodyPart.boundary = self.boundary; + bodyPart.body = fileURL; + bodyPart.bodyContentLength = [fileAttributes[NSFileSize] unsignedLongLongValue]; + [self.bodyStream appendHTTPBodyPart:bodyPart]; + + return YES; +} + +- (void)appendPartWithInputStream:(NSInputStream *)inputStream + name:(NSString *)name + fileName:(NSString *)fileName + length:(int64_t)length + mimeType:(NSString *)mimeType +{ + NSParameterAssert(name); + NSParameterAssert(fileName); + NSParameterAssert(mimeType); + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; + [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; + + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = mutableHeaders; + bodyPart.boundary = self.boundary; + bodyPart.body = inputStream; + + bodyPart.bodyContentLength = (unsigned long long)length; + + [self.bodyStream appendHTTPBodyPart:bodyPart]; +} + +- (void)appendPartWithFileData:(NSData *)data + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType +{ + NSParameterAssert(name); + NSParameterAssert(fileName); + NSParameterAssert(mimeType); + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; + [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; + + [self appendPartWithHeaders:mutableHeaders body:data]; +} + +- (void)appendPartWithFormData:(NSData *)data + name:(NSString *)name +{ + NSParameterAssert(name); + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"]; + + [self appendPartWithHeaders:mutableHeaders body:data]; +} + +- (void)appendPartWithHeaders:(NSDictionary *)headers + body:(NSData *)body +{ + NSParameterAssert(body); + + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = headers; + bodyPart.boundary = self.boundary; + bodyPart.bodyContentLength = [body length]; + bodyPart.body = body; + + [self.bodyStream appendHTTPBodyPart:bodyPart]; +} + +- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes + delay:(NSTimeInterval)delay +{ + self.bodyStream.numberOfBytesInPacket = numberOfBytes; + self.bodyStream.delay = delay; +} + +- (NSMutableURLRequest *)requestByFinalizingMultipartFormData { + if ([self.bodyStream isEmpty]) { + return self.request; + } + + // Reset the initial and final boundaries to ensure correct Content-Length + [self.bodyStream setInitialAndFinalBoundaries]; + [self.request setHTTPBodyStream:self.bodyStream]; + + [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", self.boundary] forHTTPHeaderField:@"Content-Type"]; + [self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"]; + + return self.request; +} + +@end + +#pragma mark - + +@interface NSStream () +@property (readwrite) NSStreamStatus streamStatus; +@property (readwrite, copy) NSError *streamError; +@end + +@interface AFMultipartBodyStream () +@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding; +@property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts; +@property (readwrite, nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator; +@property (readwrite, nonatomic, strong) AFHTTPBodyPart *currentHTTPBodyPart; +@property (readwrite, nonatomic, strong) NSOutputStream *outputStream; +@property (readwrite, nonatomic, strong) NSMutableData *buffer; +@end + +@implementation AFMultipartBodyStream +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wimplicit-atomic-properties" +#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1100) +@synthesize delegate; +#endif +@synthesize streamStatus; +@synthesize streamError; +#pragma clang diagnostic pop + +- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding { + self = [super init]; + if (!self) { + return nil; + } + + self.stringEncoding = encoding; + self.HTTPBodyParts = [NSMutableArray array]; + self.numberOfBytesInPacket = NSIntegerMax; + + return self; +} + +- (void)setInitialAndFinalBoundaries { + if ([self.HTTPBodyParts count] > 0) { + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { + bodyPart.hasInitialBoundary = NO; + bodyPart.hasFinalBoundary = NO; + } + + [[self.HTTPBodyParts firstObject] setHasInitialBoundary:YES]; + [[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES]; + } +} + +- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart { + [self.HTTPBodyParts addObject:bodyPart]; +} + +- (BOOL)isEmpty { + return [self.HTTPBodyParts count] == 0; +} + +#pragma mark - NSInputStream + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length +{ + if ([self streamStatus] == NSStreamStatusClosed) { + return 0; + } + + NSInteger totalNumberOfBytesRead = 0; + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) { + if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) { + if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) { + break; + } + } else { + NSUInteger maxLength = MIN(length, self.numberOfBytesInPacket) - (NSUInteger)totalNumberOfBytesRead; + NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength]; + if (numberOfBytesRead == -1) { + self.streamError = self.currentHTTPBodyPart.inputStream.streamError; + break; + } else { + totalNumberOfBytesRead += numberOfBytesRead; + + if (self.delay > 0.0f) { + [NSThread sleepForTimeInterval:self.delay]; + } + } + } + } +#pragma clang diagnostic pop + + return totalNumberOfBytesRead; +} + +- (BOOL)getBuffer:(__unused uint8_t **)buffer + length:(__unused NSUInteger *)len +{ + return NO; +} + +- (BOOL)hasBytesAvailable { + return [self streamStatus] == NSStreamStatusOpen; +} + +#pragma mark - NSStream + +- (void)open { + if (self.streamStatus == NSStreamStatusOpen) { + return; + } + + self.streamStatus = NSStreamStatusOpen; + + [self setInitialAndFinalBoundaries]; + self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator]; +} + +- (void)close { + self.streamStatus = NSStreamStatusClosed; +} + +- (id)propertyForKey:(__unused NSString *)key { + return nil; +} + +- (BOOL)setProperty:(__unused id)property + forKey:(__unused NSString *)key +{ + return NO; +} + +- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop + forMode:(__unused NSString *)mode +{} + +- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop + forMode:(__unused NSString *)mode +{} + +- (unsigned long long)contentLength { + unsigned long long length = 0; + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { + length += [bodyPart contentLength]; + } + + return length; +} + +#pragma mark - Undocumented CFReadStream Bridged Methods + +- (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop + forMode:(__unused CFStringRef)aMode +{} + +- (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop + forMode:(__unused CFStringRef)aMode +{} + +- (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags + callback:(__unused CFReadStreamClientCallBack)inCallback + context:(__unused CFStreamClientContext *)inContext { + return NO; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding]; + + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { + [bodyStreamCopy appendHTTPBodyPart:[bodyPart copy]]; + } + + [bodyStreamCopy setInitialAndFinalBoundaries]; + + return bodyStreamCopy; +} + +@end + +#pragma mark - + +typedef enum { + AFEncapsulationBoundaryPhase = 1, + AFHeaderPhase = 2, + AFBodyPhase = 3, + AFFinalBoundaryPhase = 4, +} AFHTTPBodyPartReadPhase; + +@interface AFHTTPBodyPart () { + AFHTTPBodyPartReadPhase _phase; + NSInputStream *_inputStream; + unsigned long long _phaseReadOffset; +} + +- (BOOL)transitionToNextPhase; +- (NSInteger)readData:(NSData *)data + intoBuffer:(uint8_t *)buffer + maxLength:(NSUInteger)length; +@end + +@implementation AFHTTPBodyPart + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + [self transitionToNextPhase]; + + return self; +} + +- (void)dealloc { + if (_inputStream) { + [_inputStream close]; + _inputStream = nil; + } +} + +- (NSInputStream *)inputStream { + if (!_inputStream) { + if ([self.body isKindOfClass:[NSData class]]) { + _inputStream = [NSInputStream inputStreamWithData:self.body]; + } else if ([self.body isKindOfClass:[NSURL class]]) { + _inputStream = [NSInputStream inputStreamWithURL:self.body]; + } else if ([self.body isKindOfClass:[NSInputStream class]]) { + _inputStream = self.body; + } else { + _inputStream = [NSInputStream inputStreamWithData:[NSData data]]; + } + } + + return _inputStream; +} + +- (NSString *)stringForHeaders { + NSMutableString *headerString = [NSMutableString string]; + for (NSString *field in [self.headers allKeys]) { + [headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]]; + } + [headerString appendString:kAFMultipartFormCRLF]; + + return [NSString stringWithString:headerString]; +} + +- (unsigned long long)contentLength { + unsigned long long length = 0; + + NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding]; + length += [encapsulationBoundaryData length]; + + NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; + length += [headersData length]; + + length += _bodyContentLength; + + NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]); + length += [closingBoundaryData length]; + + return length; +} + +- (BOOL)hasBytesAvailable { + // Allows `read:maxLength:` to be called again if `AFMultipartFormFinalBoundary` doesn't fit into the available buffer + if (_phase == AFFinalBoundaryPhase) { + return YES; + } + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcovered-switch-default" + switch (self.inputStream.streamStatus) { + case NSStreamStatusNotOpen: + case NSStreamStatusOpening: + case NSStreamStatusOpen: + case NSStreamStatusReading: + case NSStreamStatusWriting: + return YES; + case NSStreamStatusAtEnd: + case NSStreamStatusClosed: + case NSStreamStatusError: + default: + return NO; + } +#pragma clang diagnostic pop +} + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length +{ + NSInteger totalNumberOfBytesRead = 0; + + if (_phase == AFEncapsulationBoundaryPhase) { + NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding]; + totalNumberOfBytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + } + + if (_phase == AFHeaderPhase) { + NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; + totalNumberOfBytesRead += [self readData:headersData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + } + + if (_phase == AFBodyPhase) { + NSInteger numberOfBytesRead = 0; + + numberOfBytesRead = [self.inputStream read:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + if (numberOfBytesRead == -1) { + return -1; + } else { + totalNumberOfBytesRead += numberOfBytesRead; + + if ([self.inputStream streamStatus] >= NSStreamStatusAtEnd) { + [self transitionToNextPhase]; + } + } + } + + if (_phase == AFFinalBoundaryPhase) { + NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]); + totalNumberOfBytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + } + + return totalNumberOfBytesRead; +} + +- (NSInteger)readData:(NSData *)data + intoBuffer:(uint8_t *)buffer + maxLength:(NSUInteger)length +{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length)); + [data getBytes:buffer range:range]; +#pragma clang diagnostic pop + + _phaseReadOffset += range.length; + + if (((NSUInteger)_phaseReadOffset) >= [data length]) { + [self transitionToNextPhase]; + } + + return (NSInteger)range.length; +} + +- (BOOL)transitionToNextPhase { + if (![[NSThread currentThread] isMainThread]) { + dispatch_sync(dispatch_get_main_queue(), ^{ + [self transitionToNextPhase]; + }); + return YES; + } + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcovered-switch-default" + switch (_phase) { + case AFEncapsulationBoundaryPhase: + _phase = AFHeaderPhase; + break; + case AFHeaderPhase: + [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; + [self.inputStream open]; + _phase = AFBodyPhase; + break; + case AFBodyPhase: + [self.inputStream close]; + _phase = AFFinalBoundaryPhase; + break; + case AFFinalBoundaryPhase: + default: + _phase = AFEncapsulationBoundaryPhase; + break; + } + _phaseReadOffset = 0; +#pragma clang diagnostic pop + + return YES; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init]; + + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = self.headers; + bodyPart.bodyContentLength = self.bodyContentLength; + bodyPart.body = self.body; + bodyPart.boundary = self.boundary; + + return bodyPart; +} + +@end + +#pragma mark - + +@implementation AFJSONRequestSerializer + ++ (instancetype)serializer { + return [self serializerWithWritingOptions:(NSJSONWritingOptions)0]; +} + ++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions +{ + AFJSONRequestSerializer *serializer = [[self alloc] init]; + serializer.writingOptions = writingOptions; + + return serializer; +} + +#pragma mark - AFURLRequestSerialization + +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(request); + + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + return [super requestBySerializingRequest:request withParameters:parameters error:error]; + } + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { + if (![request valueForHTTPHeaderField:field]) { + [mutableRequest setValue:value forHTTPHeaderField:field]; + } + }]; + + if (parameters) { + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { + [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; + } + + [mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]]; + } + + return mutableRequest; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.writingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writingOptions))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeInteger:self.writingOptions forKey:NSStringFromSelector(@selector(writingOptions))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFJSONRequestSerializer *serializer = [super copyWithZone:zone]; + serializer.writingOptions = self.writingOptions; + + return serializer; +} + +@end + +#pragma mark - + +@implementation AFPropertyListRequestSerializer + ++ (instancetype)serializer { + return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 writeOptions:0]; +} + ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + writeOptions:(NSPropertyListWriteOptions)writeOptions +{ + AFPropertyListRequestSerializer *serializer = [[self alloc] init]; + serializer.format = format; + serializer.writeOptions = writeOptions; + + return serializer; +} + +#pragma mark - AFURLRequestSerializer + +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(request); + + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + return [super requestBySerializingRequest:request withParameters:parameters error:error]; + } + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { + if (![request valueForHTTPHeaderField:field]) { + [mutableRequest setValue:value forHTTPHeaderField:field]; + } + }]; + + if (parameters) { + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { + [mutableRequest setValue:@"application/x-plist" forHTTPHeaderField:@"Content-Type"]; + } + + [mutableRequest setHTTPBody:[NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error]]; + } + + return mutableRequest; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; + self.writeOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writeOptions))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeInteger:self.format forKey:NSStringFromSelector(@selector(format))]; + [coder encodeObject:@(self.writeOptions) forKey:NSStringFromSelector(@selector(writeOptions))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone]; + serializer.format = self.format; + serializer.writeOptions = self.writeOptions; + + return serializer; +} + +@end diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFURLResponseSerialization.h b/its/plugin/projects/AFNetworking/AFNetworking/AFURLResponseSerialization.h new file mode 100644 index 00000000..c1357aed --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFURLResponseSerialization.h @@ -0,0 +1,311 @@ +// AFURLResponseSerialization.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data. + + For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object. + */ +@protocol AFURLResponseSerialization + +/** + The response object decoded from the data associated with a specified response. + + @param response The response to be processed. + @param data The response data to be decoded. + @param error The error that occurred while attempting to decode the response data. + + @return The object decoded from the specified response data. + */ +- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response + data:(nullable NSData *)data + error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; + +@end + +#pragma mark - + +/** + `AFHTTPResponseSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation. + + Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior. + */ +@interface AFHTTPResponseSerializer : NSObject + +- (instancetype)init; + +/** + The string encoding used to serialize data received from the server, when no string encoding is specified by the response. `NSUTF8StringEncoding` by default. + */ +@property (nonatomic, assign) NSStringEncoding stringEncoding; + +/** + Creates and returns a serializer with default configuration. + */ ++ (instancetype)serializer; + +///----------------------------------------- +/// @name Configuring Response Serialization +///----------------------------------------- + +/** + The acceptable HTTP status codes for responses. When non-`nil`, responses with status codes not contained by the set will result in an error during validation. + + See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html + */ +@property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes; + +/** + The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation. + */ +@property (nonatomic, copy, nullable) NSSet *acceptableContentTypes; + +/** + Validates the specified response and data. + + In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks. + + @param response The response to be validated. + @param data The data associated with the response. + @param error The error that occurred while attempting to validate the response. + + @return `YES` if the response is valid, otherwise `NO`. + */ +- (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response + data:(nullable NSData *)data + error:(NSError * _Nullable __autoreleasing *)error; + +@end + +#pragma mark - + + +/** + `AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses. + + By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types: + + - `application/json` + - `text/json` + - `text/javascript` + */ +@interface AFJSONResponseSerializer : AFHTTPResponseSerializer + +- (instancetype)init; + +/** + Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. + */ +@property (nonatomic, assign) NSJSONReadingOptions readingOptions; + +/** + Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`. + */ +@property (nonatomic, assign) BOOL removesKeysWithNullValues; + +/** + Creates and returns a JSON serializer with specified reading and writing options. + + @param readingOptions The specified JSON reading options. + */ ++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions; + +@end + +#pragma mark - + +/** + `AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects. + + By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: + + - `application/xml` + - `text/xml` + */ +@interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer + +@end + +#pragma mark - + +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED + +/** + `AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. + + By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: + + - `application/xml` + - `text/xml` + */ +@interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer + +- (instancetype)init; + +/** + Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. + */ +@property (nonatomic, assign) NSUInteger options; + +/** + Creates and returns an XML document serializer with the specified options. + + @param mask The XML document options. + */ ++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask; + +@end + +#endif + +#pragma mark - + +/** + `AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. + + By default, `AFPropertyListResponseSerializer` accepts the following MIME types: + + - `application/x-plist` + */ +@interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer + +- (instancetype)init; + +/** + The property list format. Possible values are described in "NSPropertyListFormat". + */ +@property (nonatomic, assign) NSPropertyListFormat format; + +/** + The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions." + */ +@property (nonatomic, assign) NSPropertyListReadOptions readOptions; + +/** + Creates and returns a property list serializer with a specified format, read options, and write options. + + @param format The property list format. + @param readOptions The property list reading options. + */ ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + readOptions:(NSPropertyListReadOptions)readOptions; + +@end + +#pragma mark - + +/** + `AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses. + + By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage: + + - `image/tiff` + - `image/jpeg` + - `image/gif` + - `image/png` + - `image/ico` + - `image/x-icon` + - `image/bmp` + - `image/x-bmp` + - `image/x-xbitmap` + - `image/x-win-bitmap` + */ +@interface AFImageResponseSerializer : AFHTTPResponseSerializer + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH +/** + The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. + */ +@property (nonatomic, assign) CGFloat imageScale; + +/** + Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default. + */ +@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage; +#endif + +@end + +#pragma mark - + +/** + `AFCompoundSerializer` is a subclass of `AFHTTPResponseSerializer` that delegates the response serialization to the first `AFHTTPResponseSerializer` object that returns an object for `responseObjectForResponse:data:error:`, falling back on the default behavior of `AFHTTPResponseSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer. + */ +@interface AFCompoundResponseSerializer : AFHTTPResponseSerializer + +/** + The component response serializers. + */ +@property (readonly, nonatomic, copy) NSArray > *responseSerializers; + +/** + Creates and returns a compound serializer comprised of the specified response serializers. + + @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`. + */ ++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray > *)responseSerializers; + +@end + +///---------------- +/// @name Constants +///---------------- + +/** + ## Error Domains + + The following error domain is predefined. + + - `NSString * const AFURLResponseSerializationErrorDomain` + + ### Constants + + `AFURLResponseSerializationErrorDomain` + AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain; + +/** + ## User info dictionary keys + + These keys may exist in the user info dictionary, in addition to those defined for NSError. + + - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey` + - `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey` + + ### Constants + + `AFNetworkingOperationFailingURLResponseErrorKey` + The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. + + `AFNetworkingOperationFailingURLResponseDataErrorKey` + The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey; + +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey; + +NS_ASSUME_NONNULL_END diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFURLResponseSerialization.m b/its/plugin/projects/AFNetworking/AFNetworking/AFURLResponseSerialization.m new file mode 100755 index 00000000..1402e8d3 --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFURLResponseSerialization.m @@ -0,0 +1,803 @@ +// AFURLResponseSerialization.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFURLResponseSerialization.h" + +#import + +#if TARGET_OS_IOS +#import +#elif TARGET_OS_WATCH +#import +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) +#import +#endif + +NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response"; +NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response"; +NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data"; + +static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) { + if (!error) { + return underlyingError; + } + + if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) { + return error; + } + + NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy]; + mutableUserInfo[NSUnderlyingErrorKey] = underlyingError; + + return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo]; +} + +static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) { + if ([error.domain isEqualToString:domain] && error.code == code) { + return YES; + } else if (error.userInfo[NSUnderlyingErrorKey]) { + return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain); + } + + return NO; +} + +static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) { + if ([JSONObject isKindOfClass:[NSArray class]]) { + NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]]; + for (id value in (NSArray *)JSONObject) { + [mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)]; + } + + return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray]; + } else if ([JSONObject isKindOfClass:[NSDictionary class]]) { + NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject]; + for (id key in [(NSDictionary *)JSONObject allKeys]) { + id value = (NSDictionary *)JSONObject[key]; + if (!value || [value isEqual:[NSNull null]]) { + [mutableDictionary removeObjectForKey:key]; + } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) { + mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions); + } + } + + return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary]; + } + + return JSONObject; +} + +@implementation AFHTTPResponseSerializer + ++ (instancetype)serializer { + return [[self alloc] init]; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.stringEncoding = NSUTF8StringEncoding; + + self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; + self.acceptableContentTypes = nil; + + return self; +} + +#pragma mark - + +- (BOOL)validateResponse:(NSHTTPURLResponse *)response + data:(NSData *)data + error:(NSError * __autoreleasing *)error +{ + BOOL responseIsValid = YES; + NSError *validationError = nil; + + if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) { + if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]]) { + if ([data length] > 0 && [response URL]) { + NSMutableDictionary *mutableUserInfo = [@{ + NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]], + NSURLErrorFailingURLErrorKey:[response URL], + AFNetworkingOperationFailingURLResponseErrorKey: response, + } mutableCopy]; + if (data) { + mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data; + } + + validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError); + } + + responseIsValid = NO; + } + + if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) { + NSMutableDictionary *mutableUserInfo = [@{ + NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode], + NSURLErrorFailingURLErrorKey:[response URL], + AFNetworkingOperationFailingURLResponseErrorKey: response, + } mutableCopy]; + + if (data) { + mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data; + } + + validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError); + + responseIsValid = NO; + } + } + + if (error && !responseIsValid) { + *error = validationError; + } + + return responseIsValid; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + [self validateResponse:(NSHTTPURLResponse *)response data:data error:error]; + + return data; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [self init]; + if (!self) { + return nil; + } + + self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; + self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; + [coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone]; + serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone]; + + return serializer; +} + +@end + +#pragma mark - + +@implementation AFJSONResponseSerializer + ++ (instancetype)serializer { + return [self serializerWithReadingOptions:(NSJSONReadingOptions)0]; +} + ++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions { + AFJSONResponseSerializer *serializer = [[self alloc] init]; + serializer.readingOptions = readingOptions; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + id responseObject = nil; + NSError *serializationError = nil; + // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization. + // See https://github.com/rails/rails/issues/1742 + BOOL isSpace = [data isEqualToData:[NSData dataWithBytes:" " length:1]]; + if (data.length > 0 && !isSpace) { + responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError]; + } else { + return nil; + } + + if (self.removesKeysWithNullValues && responseObject) { + responseObject = AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions); + } + + if (error) { + *error = AFErrorWithUnderlyingError(serializationError, *error); + } + + return responseObject; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue]; + self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))]; + [coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.readingOptions = self.readingOptions; + serializer.removesKeysWithNullValues = self.removesKeysWithNullValues; + + return serializer; +} + +@end + +#pragma mark - + +@implementation AFXMLParserResponseSerializer + ++ (instancetype)serializer { + AFXMLParserResponseSerializer *serializer = [[self alloc] init]; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSHTTPURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + return [[NSXMLParser alloc] initWithData:data]; +} + +@end + +#pragma mark - + +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED + +@implementation AFXMLDocumentResponseSerializer + ++ (instancetype)serializer { + return [self serializerWithXMLDocumentOptions:0]; +} + ++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask { + AFXMLDocumentResponseSerializer *serializer = [[self alloc] init]; + serializer.options = mask; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + NSError *serializationError = nil; + NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError]; + + if (error) { + *error = AFErrorWithUnderlyingError(serializationError, *error); + } + + return document; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFXMLDocumentResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.options = self.options; + + return serializer; +} + +@end + +#endif + +#pragma mark - + +@implementation AFPropertyListResponseSerializer + ++ (instancetype)serializer { + return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0]; +} + ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + readOptions:(NSPropertyListReadOptions)readOptions +{ + AFPropertyListResponseSerializer *serializer = [[self alloc] init]; + serializer.format = format; + serializer.readOptions = readOptions; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + id responseObject; + NSError *serializationError = nil; + + if (data) { + responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError]; + } + + if (error) { + *error = AFErrorWithUnderlyingError(serializationError, *error); + } + + return responseObject; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; + self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))]; + [coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.format = self.format; + serializer.readOptions = self.readOptions; + + return serializer; +} + +@end + +#pragma mark - + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH +#import +#import + +@interface UIImage (AFNetworkingSafeImageLoading) ++ (UIImage *)af_safeImageWithData:(NSData *)data; +@end + +static NSLock* imageLock = nil; + +@implementation UIImage (AFNetworkingSafeImageLoading) + ++ (UIImage *)af_safeImageWithData:(NSData *)data { + UIImage* image = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + imageLock = [[NSLock alloc] init]; + }); + + [imageLock lock]; + image = [UIImage imageWithData:data]; + [imageLock unlock]; + return image; +} + +@end + +static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) { + UIImage *image = [UIImage af_safeImageWithData:data]; + if (image.images) { + return image; + } + + return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation]; +} + +static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) { + if (!data || [data length] == 0) { + return nil; + } + + CGImageRef imageRef = NULL; + CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data); + + if ([response.MIMEType isEqualToString:@"image/png"]) { + imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); + } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) { + imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); + + if (imageRef) { + CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef); + CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace); + + // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to AFImageWithDataAtScale + if (imageColorSpaceModel == kCGColorSpaceModelCMYK) { + CGImageRelease(imageRef); + imageRef = NULL; + } + } + } + + CGDataProviderRelease(dataProvider); + + UIImage *image = AFImageWithDataAtScale(data, scale); + if (!imageRef) { + if (image.images || !image) { + return image; + } + + imageRef = CGImageCreateCopy([image CGImage]); + if (!imageRef) { + return nil; + } + } + + size_t width = CGImageGetWidth(imageRef); + size_t height = CGImageGetHeight(imageRef); + size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef); + + if (width * height > 1024 * 1024 || bitsPerComponent > 8) { + CGImageRelease(imageRef); + + return image; + } + + // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate + size_t bytesPerRow = 0; + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace); + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); + + if (colorSpaceModel == kCGColorSpaceModelRGB) { + uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask); +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wassign-enum" + if (alpha == kCGImageAlphaNone) { + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + bitmapInfo |= kCGImageAlphaNoneSkipFirst; + } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) { + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + bitmapInfo |= kCGImageAlphaPremultipliedFirst; + } +#pragma clang diagnostic pop + } + + CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo); + + CGColorSpaceRelease(colorSpace); + + if (!context) { + CGImageRelease(imageRef); + + return image; + } + + CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef); + CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context); + + CGContextRelease(context); + + UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation]; + + CGImageRelease(inflatedImageRef); + CGImageRelease(imageRef); + + return inflatedImage; +} +#endif + + +@implementation AFImageResponseSerializer + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil]; + +#if TARGET_OS_IOS || TARGET_OS_TV + self.imageScale = [[UIScreen mainScreen] scale]; + self.automaticallyInflatesResponseImage = YES; +#elif TARGET_OS_WATCH + self.imageScale = [[WKInterfaceDevice currentDevice] screenScale]; + self.automaticallyInflatesResponseImage = YES; +#endif + + return self; +} + +#pragma mark - AFURLResponseSerializer + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + if (self.automaticallyInflatesResponseImage) { + return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale); + } else { + return AFImageWithDataAtScale(data, self.imageScale); + } +#else + // Ensure that the image is set to it's correct pixel width and height + NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data]; + NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])]; + [image addRepresentation:bitimage]; + + return image; +#endif + + return nil; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))]; +#if CGFLOAT_IS_DOUBLE + self.imageScale = [imageScale doubleValue]; +#else + self.imageScale = [imageScale floatValue]; +#endif + + self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; +#endif + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))]; + [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; +#endif +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + serializer.imageScale = self.imageScale; + serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage; +#endif + + return serializer; +} + +@end + +#pragma mark - + +@interface AFCompoundResponseSerializer () +@property (readwrite, nonatomic, copy) NSArray *responseSerializers; +@end + +@implementation AFCompoundResponseSerializer + ++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers { + AFCompoundResponseSerializer *serializer = [[self alloc] init]; + serializer.responseSerializers = responseSerializers; + + return serializer; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + for (id serializer in self.responseSerializers) { + if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) { + continue; + } + + NSError *serializerError = nil; + id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError]; + if (responseObject) { + if (error) { + *error = AFErrorWithUnderlyingError(serializerError, *error); + } + + return responseObject; + } + } + + return [super responseObjectForResponse:response data:data error:error]; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.responseSerializers = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(responseSerializers))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.responseSerializers = self.responseSerializers; + + return serializer; +} + +@end diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFURLSessionManager.h b/its/plugin/projects/AFNetworking/AFNetworking/AFURLSessionManager.h new file mode 100644 index 00000000..691e80c8 --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFURLSessionManager.h @@ -0,0 +1,499 @@ +// AFURLSessionManager.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + + +#import + +#import "AFURLResponseSerialization.h" +#import "AFURLRequestSerialization.h" +#import "AFSecurityPolicy.h" +#if !TARGET_OS_WATCH +#import "AFNetworkReachabilityManager.h" +#endif + +/** + `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. + + ## Subclassing Notes + + This is the base class for `AFHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `AFURLSessionManager` specifically for HTTP, consider subclassing `AFHTTPSessionManager` instead. + + ## NSURLSession & NSURLSessionTask Delegate Methods + + `AFURLSessionManager` implements the following delegate methods: + + ### `NSURLSessionDelegate` + + - `URLSession:didBecomeInvalidWithError:` + - `URLSession:didReceiveChallenge:completionHandler:` + - `URLSessionDidFinishEventsForBackgroundURLSession:` + + ### `NSURLSessionTaskDelegate` + + - `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:` + - `URLSession:task:didReceiveChallenge:completionHandler:` + - `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:` + - `URLSession:task:didCompleteWithError:` + + ### `NSURLSessionDataDelegate` + + - `URLSession:dataTask:didReceiveResponse:completionHandler:` + - `URLSession:dataTask:didBecomeDownloadTask:` + - `URLSession:dataTask:didReceiveData:` + - `URLSession:dataTask:willCacheResponse:completionHandler:` + + ### `NSURLSessionDownloadDelegate` + + - `URLSession:downloadTask:didFinishDownloadingToURL:` + - `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:` + - `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:` + + If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. + + ## Network Reachability Monitoring + + Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details. + + ## NSCoding Caveats + + - Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`. + + ## NSCopying Caveats + + - `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original. + - Operation copies do not include any delegate callback blocks, as they often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ session manager when copied. + + @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. + */ + +NS_ASSUME_NONNULL_BEGIN + +@interface AFURLSessionManager : NSObject + +/** + The managed session. + */ +@property (readonly, nonatomic, strong) NSURLSession *session; + +/** + The operation queue on which delegate callbacks are run. + */ +@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue; + +/** + Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`. + + @warning `responseSerializer` must not be `nil`. + */ +@property (nonatomic, strong) id responseSerializer; + +///------------------------------- +/// @name Managing Security Policy +///------------------------------- + +/** + The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. + */ +@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; + +#if !TARGET_OS_WATCH +///-------------------------------------- +/// @name Monitoring Network Reachability +///-------------------------------------- + +/** + The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default. + */ +@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; +#endif + +///---------------------------- +/// @name Getting Session Tasks +///---------------------------- + +/** + The data, upload, and download tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *tasks; + +/** + The data tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *dataTasks; + +/** + The upload tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *uploadTasks; + +/** + The download tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *downloadTasks; + +///------------------------------- +/// @name Managing Callback Queues +///------------------------------- + +/** + The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. + */ +@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; + +/** + The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. + */ +@property (nonatomic, strong, nullable) dispatch_group_t completionGroup; + +///--------------------------------- +/// @name Working Around System Bugs +///--------------------------------- + +/** + Whether to attempt to retry creation of upload tasks for background sessions when initial call returns `nil`. `NO` by default. + + @bug As of iOS 7.0, there is a bug where upload tasks created for background tasks are sometimes `nil`. As a workaround, if this property is `YES`, AFNetworking will follow Apple's recommendation to try creating the task again. + + @see https://github.com/AFNetworking/AFNetworking/issues/1675 + */ +@property (nonatomic, assign) BOOL attemptsToRecreateUploadTasksForBackgroundSessions; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Creates and returns a manager for a session created with the specified configuration. This is the designated initializer. + + @param configuration The configuration used to create the managed session. + + @return A manager for a newly-created session. + */ +- (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; + +/** + Invalidates the managed session, optionally canceling pending tasks. + + @param cancelPendingTasks Whether or not to cancel pending tasks. + */ +- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks; + +///------------------------- +/// @name Running Data Tasks +///------------------------- + +/** + Creates an `NSURLSessionDataTask` with the specified request. + + @param request The HTTP request for the request. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +/** + Creates an `NSURLSessionDataTask` with the specified request. + + @param request The HTTP request for the request. + @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param downloadProgress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +///--------------------------- +/// @name Running Upload Tasks +///--------------------------- + +/** + Creates an `NSURLSessionUploadTask` with the specified request for a local file. + + @param request The HTTP request for the request. + @param fileURL A URL to the local file to be uploaded. + @param progress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + + @see `attemptsToRecreateUploadTasksForBackgroundSessions` + */ +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromFile:(NSURL *)fileURL + progress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +/** + Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body. + + @param request The HTTP request for the request. + @param bodyData A data object containing the HTTP body to be uploaded. + @param progress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromData:(nullable NSData *)bodyData + progress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +/** + Creates an `NSURLSessionUploadTask` with the specified streaming request. + + @param request The HTTP request for the request. + @param progress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request + progress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +///----------------------------- +/// @name Running Download Tasks +///----------------------------- + +/** + Creates an `NSURLSessionDownloadTask` with the specified request. + + @param request The HTTP request for the request. + @param progress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. + @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. + + @warning If using a background `NSURLSessionConfiguration` on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use `-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving the downloaded file, rather than the destination block of this method. + */ +- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request + progress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; + +/** + Creates an `NSURLSessionDownloadTask` with the specified resume data. + + @param resumeData The data used to resume downloading. + @param progress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. + @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. + */ +- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData + progress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; + +///--------------------------------- +/// @name Getting Progress for Tasks +///--------------------------------- + +/** + Returns the upload progress of the specified task. + + @param task The session task. Must not be `nil`. + + @return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable. + */ +- (nullable NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task; + +/** + Returns the download progress of the specified task. + + @param task The session task. Must not be `nil`. + + @return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable. + */ +- (nullable NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task; + +///----------------------------------------- +/// @name Setting Session Delegate Callbacks +///----------------------------------------- + +/** + Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`. + + @param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation. + */ +- (void)setSessionDidBecomeInvalidBlock:(nullable void (^)(NSURLSession *session, NSError *error))block; + +/** + Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`. + + @param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. + */ +- (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; + +///-------------------------------------- +/// @name Setting Task Delegate Callbacks +///-------------------------------------- + +/** + Sets a block to be executed when a task requires a new request body stream to send to the remote server, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:needNewBodyStream:`. + + @param block A block object to be executed when a task requires a new request body stream. + */ +- (void)setTaskNeedNewBodyStreamBlock:(nullable NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block; + +/** + Sets a block to be executed when an HTTP request is attempting to perform a redirection to a different URL, as handled by the `NSURLSessionTaskDelegate` method `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`. + + @param block A block object to be executed when an HTTP request is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response. + */ +- (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block; + +/** + Sets a block to be executed when a session task has received a request specific authentication challenge, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didReceiveChallenge:completionHandler:`. + + @param block A block object to be executed when a session task has received a request specific authentication challenge. The block returns the disposition of the authentication challenge, and takes four arguments: the session, the task, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. + */ +- (void)setTaskDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; + +/** + Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. + + @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes five arguments: the session, the task, the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread. + */ +- (void)setTaskDidSendBodyDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block; + +/** + Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`. + + @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task. + */ +- (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError * _Nullable error))block; + +///------------------------------------------- +/// @name Setting Data Task Delegate Callbacks +///------------------------------------------- + +/** + Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`. + + @param block A block object to be executed when a data task has received a response. The block returns the disposition of the session response, and takes three arguments: the session, the data task, and the received response. + */ +- (void)setDataTaskDidReceiveResponseBlock:(nullable NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block; + +/** + Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`. + + @param block A block object to be executed when a data task has become a download task. The block has no return value, and takes three arguments: the session, the data task, and the download task it has become. + */ +- (void)setDataTaskDidBecomeDownloadTaskBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block; + +/** + Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`. + + @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the session, the data task, and the data received. This block may be called multiple times, and will execute on the session manager operation queue. + */ +- (void)setDataTaskDidReceiveDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block; + +/** + Sets a block to be executed to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:willCacheResponse:completionHandler:`. + + @param block A block object to be executed to determine the caching behavior of a data task. The block returns the response to cache, and takes three arguments: the session, the data task, and the proposed cached URL response. + */ +- (void)setDataTaskWillCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block; + +/** + Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`. + + @param block A block object to be executed once all messages enqueued for a session have been delivered. The block has no return value and takes a single argument: the session. + */ +- (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block; + +///----------------------------------------------- +/// @name Setting Download Task Delegate Callbacks +///----------------------------------------------- + +/** + Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`. + + @param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error. + */ +- (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * _Nullable (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block; + +/** + Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`. + + @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes five arguments: the session, the download task, the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the session manager operation queue. + */ +- (void)setDownloadTaskDidWriteDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block; + +/** + Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. + + @param block A block object to be executed when a download task has been resumed. The block has no return value and takes four arguments: the session, the download task, the file offset of the resumed download, and the total number of bytes expected to be downloaded. + */ +- (void)setDownloadTaskDidResumeBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block; + +@end + +///-------------------- +/// @name Notifications +///-------------------- + +/** + Posted when a task resumes. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification; + +/** + Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification; + +/** + Posted when a task suspends its execution. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidSuspendNotification; + +/** + Posted when a session is invalidated. + */ +FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification; + +/** + Posted when a session download task encountered an error when moving the temporary download file to a specified destination. + */ +FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification; + +/** + The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if response data exists for the task. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey; + +/** + The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the response was serialized. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey; + +/** + The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the task has an associated response serializer. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey; + +/** + The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an the response data has been stored directly to disk. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey; + +/** + Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an error exists. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey; + +NS_ASSUME_NONNULL_END diff --git a/its/plugin/projects/AFNetworking/AFNetworking/AFURLSessionManager.m b/its/plugin/projects/AFNetworking/AFNetworking/AFURLSessionManager.m new file mode 100644 index 00000000..170581ac --- /dev/null +++ b/its/plugin/projects/AFNetworking/AFNetworking/AFURLSessionManager.m @@ -0,0 +1,1244 @@ +// AFURLSessionManager.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFURLSessionManager.h" +#import + +#ifndef NSFoundationVersionNumber_iOS_8_0 +#define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug 1140.11 +#else +#define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug NSFoundationVersionNumber_iOS_8_0 +#endif + +static dispatch_queue_t url_session_manager_creation_queue() { + static dispatch_queue_t af_url_session_manager_creation_queue; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + af_url_session_manager_creation_queue = dispatch_queue_create("com.alamofire.networking.session.manager.creation", DISPATCH_QUEUE_SERIAL); + }); + + return af_url_session_manager_creation_queue; +} + +static void url_session_manager_create_task_safely(dispatch_block_t block) { + if (NSFoundationVersionNumber < NSFoundationVersionNumber_With_Fixed_5871104061079552_bug) { + // Fix of bug + // Open Radar:http://openradar.appspot.com/radar?id=5871104061079552 (status: Fixed in iOS8) + // Issue about:https://github.com/AFNetworking/AFNetworking/issues/2093 + dispatch_sync(url_session_manager_creation_queue(), block); + } else { + block(); + } +} + +static dispatch_queue_t url_session_manager_processing_queue() { + static dispatch_queue_t af_url_session_manager_processing_queue; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + af_url_session_manager_processing_queue = dispatch_queue_create("com.alamofire.networking.session.manager.processing", DISPATCH_QUEUE_CONCURRENT); + }); + + return af_url_session_manager_processing_queue; +} + +static dispatch_group_t url_session_manager_completion_group() { + static dispatch_group_t af_url_session_manager_completion_group; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + af_url_session_manager_completion_group = dispatch_group_create(); + }); + + return af_url_session_manager_completion_group; +} + +NSString * const AFNetworkingTaskDidResumeNotification = @"com.alamofire.networking.task.resume"; +NSString * const AFNetworkingTaskDidCompleteNotification = @"com.alamofire.networking.task.complete"; +NSString * const AFNetworkingTaskDidSuspendNotification = @"com.alamofire.networking.task.suspend"; +NSString * const AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate"; +NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error"; + +NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse"; +NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer"; +NSString * const AFNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata"; +NSString * const AFNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error"; +NSString * const AFNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath"; + +static NSString * const AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock"; + +static NSUInteger const AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask = 3; + +static void * AFTaskStateChangedContext = &AFTaskStateChangedContext; + +typedef void (^AFURLSessionDidBecomeInvalidBlock)(NSURLSession *session, NSError *error); +typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential); + +typedef NSURLRequest * (^AFURLSessionTaskWillPerformHTTPRedirectionBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request); +typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionTaskDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential); +typedef void (^AFURLSessionDidFinishEventsForBackgroundURLSessionBlock)(NSURLSession *session); + +typedef NSInputStream * (^AFURLSessionTaskNeedNewBodyStreamBlock)(NSURLSession *session, NSURLSessionTask *task); +typedef void (^AFURLSessionTaskDidSendBodyDataBlock)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend); +typedef void (^AFURLSessionTaskDidCompleteBlock)(NSURLSession *session, NSURLSessionTask *task, NSError *error); + +typedef NSURLSessionResponseDisposition (^AFURLSessionDataTaskDidReceiveResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response); +typedef void (^AFURLSessionDataTaskDidBecomeDownloadTaskBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask); +typedef void (^AFURLSessionDataTaskDidReceiveDataBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data); +typedef NSCachedURLResponse * (^AFURLSessionDataTaskWillCacheResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse); + +typedef NSURL * (^AFURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location); +typedef void (^AFURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite); +typedef void (^AFURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes); +typedef void (^AFURLSessionTaskProgressBlock)(NSProgress *); + +typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error); + + +#pragma mark - + +@interface AFURLSessionManagerTaskDelegate : NSObject +@property (nonatomic, weak) AFURLSessionManager *manager; +@property (nonatomic, strong) NSMutableData *mutableData; +@property (nonatomic, strong) NSProgress *uploadProgress; +@property (nonatomic, strong) NSProgress *downloadProgress; +@property (nonatomic, copy) NSURL *downloadFileURL; +@property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; +@property (nonatomic, copy) AFURLSessionTaskProgressBlock uploadProgressBlock; +@property (nonatomic, copy) AFURLSessionTaskProgressBlock downloadProgressBlock; +@property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler; +@end + +@implementation AFURLSessionManagerTaskDelegate + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.mutableData = [NSMutableData data]; + self.uploadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil]; + self.uploadProgress.totalUnitCount = NSURLSessionTransferSizeUnknown; + + self.downloadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil]; + self.downloadProgress.totalUnitCount = NSURLSessionTransferSizeUnknown; + return self; +} + +#pragma mark - NSProgress Tracking + +- (void)setupProgressForTask:(NSURLSessionTask *)task { + __weak __typeof__(task) weakTask = task; + + self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend; + self.downloadProgress.totalUnitCount = task.countOfBytesExpectedToReceive; + [self.uploadProgress setCancellable:YES]; + [self.uploadProgress setCancellationHandler:^{ + __typeof__(weakTask) strongTask = weakTask; + [strongTask cancel]; + }]; + [self.uploadProgress setPausable:YES]; + [self.uploadProgress setPausingHandler:^{ + __typeof__(weakTask) strongTask = weakTask; + [strongTask suspend]; + }]; + if ([self.uploadProgress respondsToSelector:@selector(setResumingHandler:)]) { + [self.uploadProgress setResumingHandler:^{ + __typeof__(weakTask) strongTask = weakTask; + [strongTask resume]; + }]; + } + + [self.downloadProgress setCancellable:YES]; + [self.downloadProgress setCancellationHandler:^{ + __typeof__(weakTask) strongTask = weakTask; + [strongTask cancel]; + }]; + [self.downloadProgress setPausable:YES]; + [self.downloadProgress setPausingHandler:^{ + __typeof__(weakTask) strongTask = weakTask; + [strongTask suspend]; + }]; + + if ([self.downloadProgress respondsToSelector:@selector(setResumingHandler:)]) { + [self.downloadProgress setResumingHandler:^{ + __typeof__(weakTask) strongTask = weakTask; + [strongTask resume]; + }]; + } + + [task addObserver:self + forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived)) + options:NSKeyValueObservingOptionNew + context:NULL]; + [task addObserver:self + forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToReceive)) + options:NSKeyValueObservingOptionNew + context:NULL]; + + [task addObserver:self + forKeyPath:NSStringFromSelector(@selector(countOfBytesSent)) + options:NSKeyValueObservingOptionNew + context:NULL]; + [task addObserver:self + forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToSend)) + options:NSKeyValueObservingOptionNew + context:NULL]; + + [self.downloadProgress addObserver:self + forKeyPath:NSStringFromSelector(@selector(fractionCompleted)) + options:NSKeyValueObservingOptionNew + context:NULL]; + [self.uploadProgress addObserver:self + forKeyPath:NSStringFromSelector(@selector(fractionCompleted)) + options:NSKeyValueObservingOptionNew + context:NULL]; +} + +- (void)cleanUpProgressForTask:(NSURLSessionTask *)task { + [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))]; + [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToReceive))]; + [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))]; + [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToSend))]; + [self.downloadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))]; + [self.uploadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))]; +} + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + if ([object isKindOfClass:[NSURLSessionTask class]] || [object isKindOfClass:[NSURLSessionDownloadTask class]]) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) { + self.downloadProgress.completedUnitCount = [change[@"new"] longLongValue]; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesExpectedToReceive))]) { + self.downloadProgress.totalUnitCount = [change[@"new"] longLongValue]; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) { + self.uploadProgress.completedUnitCount = [change[@"new"] longLongValue]; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesExpectedToSend))]) { + self.uploadProgress.totalUnitCount = [change[@"new"] longLongValue]; + } + } + else if ([object isEqual:self.downloadProgress]) { + if (self.downloadProgressBlock) { + self.downloadProgressBlock(object); + } + } + else if ([object isEqual:self.uploadProgress]) { + if (self.uploadProgressBlock) { + self.uploadProgressBlock(object); + } + } +} + +#pragma mark - NSURLSessionTaskDelegate + +- (void)URLSession:(__unused NSURLSession *)session + task:(NSURLSessionTask *)task +didCompleteWithError:(NSError *)error +{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + __strong AFURLSessionManager *manager = self.manager; + + __block id responseObject = nil; + + __block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer; + + //Performance Improvement from #2672 + NSData *data = nil; + if (self.mutableData) { + data = [self.mutableData copy]; + //We no longer need the reference, so nil it out to gain back some memory. + self.mutableData = nil; + } + + if (self.downloadFileURL) { + userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL; + } else if (data) { + userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data; + } + + if (error) { + userInfo[AFNetworkingTaskDidCompleteErrorKey] = error; + + dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{ + if (self.completionHandler) { + self.completionHandler(task.response, responseObject, error); + } + + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo]; + }); + }); + } else { + dispatch_async(url_session_manager_processing_queue(), ^{ + NSError *serializationError = nil; + responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError]; + + if (self.downloadFileURL) { + responseObject = self.downloadFileURL; + } + + if (responseObject) { + userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject; + } + + if (serializationError) { + userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError; + } + + dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{ + if (self.completionHandler) { + self.completionHandler(task.response, responseObject, serializationError); + } + + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo]; + }); + }); + }); + } +#pragma clang diagnostic pop +} + +#pragma mark - NSURLSessionDataTaskDelegate + +- (void)URLSession:(__unused NSURLSession *)session + dataTask:(__unused NSURLSessionDataTask *)dataTask + didReceiveData:(NSData *)data +{ + [self.mutableData appendData:data]; +} + +#pragma mark - NSURLSessionDownloadTaskDelegate + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask +didFinishDownloadingToURL:(NSURL *)location +{ + NSError *fileManagerError = nil; + self.downloadFileURL = nil; + + if (self.downloadTaskDidFinishDownloading) { + self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); + if (self.downloadFileURL) { + [[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError]; + + if (fileManagerError) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo]; + } + } + } +} + +@end + +#pragma mark - + +/** + * A workaround for issues related to key-value observing the `state` of an `NSURLSessionTask`. + * + * See: + * - https://github.com/AFNetworking/AFNetworking/issues/1477 + * - https://github.com/AFNetworking/AFNetworking/issues/2638 + * - https://github.com/AFNetworking/AFNetworking/pull/2702 + */ + +static inline void af_swizzleSelector(Class theClass, SEL originalSelector, SEL swizzledSelector) { + Method originalMethod = class_getInstanceMethod(theClass, originalSelector); + Method swizzledMethod = class_getInstanceMethod(theClass, swizzledSelector); + method_exchangeImplementations(originalMethod, swizzledMethod); +} + +static inline BOOL af_addMethod(Class theClass, SEL selector, Method method) { + return class_addMethod(theClass, selector, method_getImplementation(method), method_getTypeEncoding(method)); +} + +static NSString * const AFNSURLSessionTaskDidResumeNotification = @"com.alamofire.networking.nsurlsessiontask.resume"; +static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofire.networking.nsurlsessiontask.suspend"; + +@interface _AFURLSessionTaskSwizzling : NSObject + +@end + +@implementation _AFURLSessionTaskSwizzling + ++ (void)load { + /** + WARNING: Trouble Ahead + https://github.com/AFNetworking/AFNetworking/pull/2702 + */ + + if (NSClassFromString(@"NSURLSessionTask")) { + /** + iOS 7 and iOS 8 differ in NSURLSessionTask implementation, which makes the next bit of code a bit tricky. + Many Unit Tests have been built to validate as much of this behavior has possible. + Here is what we know: + - NSURLSessionTasks are implemented with class clusters, meaning the class you request from the API isn't actually the type of class you will get back. + - Simply referencing `[NSURLSessionTask class]` will not work. You need to ask an `NSURLSession` to actually create an object, and grab the class from there. + - On iOS 7, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `__NSCFURLSessionTask`. + - On iOS 8, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `NSURLSessionTask`. + - On iOS 7, `__NSCFLocalSessionTask` and `__NSCFURLSessionTask` are the only two classes that have their own implementations of `resume` and `suspend`, and `__NSCFLocalSessionTask` DOES NOT CALL SUPER. This means both classes need to be swizzled. + - On iOS 8, `NSURLSessionTask` is the only class that implements `resume` and `suspend`. This means this is the only class that needs to be swizzled. + - Because `NSURLSessionTask` is not involved in the class hierarchy for every version of iOS, its easier to add the swizzled methods to a dummy class and manage them there. + + Some Assumptions: + - No implementations of `resume` or `suspend` call super. If this were to change in a future version of iOS, we'd need to handle it. + - No background task classes override `resume` or `suspend` + + The current solution: + 1) Grab an instance of `__NSCFLocalDataTask` by asking an instance of `NSURLSession` for a data task. + 2) Grab a pointer to the original implementation of `af_resume` + 3) Check to see if the current class has an implementation of resume. If so, continue to step 4. + 4) Grab the super class of the current class. + 5) Grab a pointer for the current class to the current implementation of `resume`. + 6) Grab a pointer for the super class to the current implementation of `resume`. + 7) If the current class implementation of `resume` is not equal to the super class implementation of `resume` AND the current implementation of `resume` is not equal to the original implementation of `af_resume`, THEN swizzle the methods + 8) Set the current class to the super class, and repeat steps 3-8 + */ + NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration]; + NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration]; +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnonnull" + NSURLSessionDataTask *localDataTask = [session dataTaskWithURL:nil]; +#pragma clang diagnostic pop + IMP originalAFResumeIMP = method_getImplementation(class_getInstanceMethod([self class], @selector(af_resume))); + Class currentClass = [localDataTask class]; + + while (class_getInstanceMethod(currentClass, @selector(resume))) { + Class superClass = [currentClass superclass]; + IMP classResumeIMP = method_getImplementation(class_getInstanceMethod(currentClass, @selector(resume))); + IMP superclassResumeIMP = method_getImplementation(class_getInstanceMethod(superClass, @selector(resume))); + if (classResumeIMP != superclassResumeIMP && + originalAFResumeIMP != classResumeIMP) { + [self swizzleResumeAndSuspendMethodForClass:currentClass]; + } + currentClass = [currentClass superclass]; + } + + [localDataTask cancel]; + [session finishTasksAndInvalidate]; + } +} + ++ (void)swizzleResumeAndSuspendMethodForClass:(Class)theClass { + Method afResumeMethod = class_getInstanceMethod(self, @selector(af_resume)); + Method afSuspendMethod = class_getInstanceMethod(self, @selector(af_suspend)); + + if (af_addMethod(theClass, @selector(af_resume), afResumeMethod)) { + af_swizzleSelector(theClass, @selector(resume), @selector(af_resume)); + } + + if (af_addMethod(theClass, @selector(af_suspend), afSuspendMethod)) { + af_swizzleSelector(theClass, @selector(suspend), @selector(af_suspend)); + } +} + +- (NSURLSessionTaskState)state { + NSAssert(NO, @"State method should never be called in the actual dummy class"); + return NSURLSessionTaskStateCanceling; +} + +- (void)af_resume { + NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state"); + NSURLSessionTaskState state = [self state]; + [self af_resume]; + + if (state != NSURLSessionTaskStateRunning) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidResumeNotification object:self]; + } +} + +- (void)af_suspend { + NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state"); + NSURLSessionTaskState state = [self state]; + [self af_suspend]; + + if (state != NSURLSessionTaskStateSuspended) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidSuspendNotification object:self]; + } +} +@end + +#pragma mark - + +@interface AFURLSessionManager () +@property (readwrite, nonatomic, strong) NSURLSessionConfiguration *sessionConfiguration; +@property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue; +@property (readwrite, nonatomic, strong) NSURLSession *session; +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableTaskDelegatesKeyedByTaskIdentifier; +@property (readonly, nonatomic, copy) NSString *taskDescriptionForSessionTasks; +@property (readwrite, nonatomic, strong) NSLock *lock; +@property (readwrite, nonatomic, copy) AFURLSessionDidBecomeInvalidBlock sessionDidBecomeInvalid; +@property (readwrite, nonatomic, copy) AFURLSessionDidReceiveAuthenticationChallengeBlock sessionDidReceiveAuthenticationChallenge; +@property (readwrite, nonatomic, copy) AFURLSessionDidFinishEventsForBackgroundURLSessionBlock didFinishEventsForBackgroundURLSession; +@property (readwrite, nonatomic, copy) AFURLSessionTaskWillPerformHTTPRedirectionBlock taskWillPerformHTTPRedirection; +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidReceiveAuthenticationChallengeBlock taskDidReceiveAuthenticationChallenge; +@property (readwrite, nonatomic, copy) AFURLSessionTaskNeedNewBodyStreamBlock taskNeedNewBodyStream; +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidSendBodyDataBlock taskDidSendBodyData; +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidCompleteBlock taskDidComplete; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveResponseBlock dataTaskDidReceiveResponse; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidBecomeDownloadTaskBlock dataTaskDidBecomeDownloadTask; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveDataBlock dataTaskDidReceiveData; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskWillCacheResponseBlock dataTaskWillCacheResponse; +@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; +@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidWriteDataBlock downloadTaskDidWriteData; +@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidResumeBlock downloadTaskDidResume; +@end + +@implementation AFURLSessionManager + +- (instancetype)init { + return [self initWithSessionConfiguration:nil]; +} + +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { + self = [super init]; + if (!self) { + return nil; + } + + if (!configuration) { + configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; + } + + self.sessionConfiguration = configuration; + + self.operationQueue = [[NSOperationQueue alloc] init]; + self.operationQueue.maxConcurrentOperationCount = 1; + + self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue]; + + self.responseSerializer = [AFJSONResponseSerializer serializer]; + + self.securityPolicy = [AFSecurityPolicy defaultPolicy]; + +#if !TARGET_OS_WATCH + self.reachabilityManager = [AFNetworkReachabilityManager sharedManager]; +#endif + + self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init]; + + self.lock = [[NSLock alloc] init]; + self.lock.name = AFURLSessionManagerLockName; + + [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { + for (NSURLSessionDataTask *task in dataTasks) { + [self addDelegateForDataTask:task uploadProgress:nil downloadProgress:nil completionHandler:nil]; + } + + for (NSURLSessionUploadTask *uploadTask in uploadTasks) { + [self addDelegateForUploadTask:uploadTask progress:nil completionHandler:nil]; + } + + for (NSURLSessionDownloadTask *downloadTask in downloadTasks) { + [self addDelegateForDownloadTask:downloadTask progress:nil destination:nil completionHandler:nil]; + } + }]; + + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +#pragma mark - + +- (NSString *)taskDescriptionForSessionTasks { + return [NSString stringWithFormat:@"%p", self]; +} + +- (void)taskDidResume:(NSNotification *)notification { + NSURLSessionTask *task = notification.object; + if ([task respondsToSelector:@selector(taskDescription)]) { + if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) { + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidResumeNotification object:task]; + }); + } + } +} + +- (void)taskDidSuspend:(NSNotification *)notification { + NSURLSessionTask *task = notification.object; + if ([task respondsToSelector:@selector(taskDescription)]) { + if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) { + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidSuspendNotification object:task]; + }); + } + } +} + +#pragma mark - + +- (AFURLSessionManagerTaskDelegate *)delegateForTask:(NSURLSessionTask *)task { + NSParameterAssert(task); + + AFURLSessionManagerTaskDelegate *delegate = nil; + [self.lock lock]; + delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)]; + [self.lock unlock]; + + return delegate; +} + +- (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate + forTask:(NSURLSessionTask *)task +{ + NSParameterAssert(task); + NSParameterAssert(delegate); + + [self.lock lock]; + self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate; + [delegate setupProgressForTask:task]; + [self addNotificationObserverForTask:task]; + [self.lock unlock]; +} + +- (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; + delegate.manager = self; + delegate.completionHandler = completionHandler; + + dataTask.taskDescription = self.taskDescriptionForSessionTasks; + [self setDelegate:delegate forTask:dataTask]; + + delegate.uploadProgressBlock = uploadProgressBlock; + delegate.downloadProgressBlock = downloadProgressBlock; +} + +- (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; + delegate.manager = self; + delegate.completionHandler = completionHandler; + + uploadTask.taskDescription = self.taskDescriptionForSessionTasks; + + [self setDelegate:delegate forTask:uploadTask]; + + delegate.uploadProgressBlock = uploadProgressBlock; +} + +- (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler +{ + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; + delegate.manager = self; + delegate.completionHandler = completionHandler; + + if (destination) { + delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session, NSURLSessionDownloadTask *task, NSURL *location) { + return destination(location, task.response); + }; + } + + downloadTask.taskDescription = self.taskDescriptionForSessionTasks; + + [self setDelegate:delegate forTask:downloadTask]; + + delegate.downloadProgressBlock = downloadProgressBlock; +} + +- (void)removeDelegateForTask:(NSURLSessionTask *)task { + NSParameterAssert(task); + + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; + [self.lock lock]; + [delegate cleanUpProgressForTask:task]; + [self removeNotificationObserverForTask:task]; + [self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)]; + [self.lock unlock]; +} + +#pragma mark - + +- (NSArray *)tasksForKeyPath:(NSString *)keyPath { + __block NSArray *tasks = nil; + dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); + [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(dataTasks))]) { + tasks = dataTasks; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(uploadTasks))]) { + tasks = uploadTasks; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(downloadTasks))]) { + tasks = downloadTasks; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(tasks))]) { + tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"]; + } + + dispatch_semaphore_signal(semaphore); + }]; + + dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); + + return tasks; +} + +- (NSArray *)tasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +- (NSArray *)dataTasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +- (NSArray *)uploadTasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +- (NSArray *)downloadTasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +#pragma mark - + +- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks { + dispatch_async(dispatch_get_main_queue(), ^{ + if (cancelPendingTasks) { + [self.session invalidateAndCancel]; + } else { + [self.session finishTasksAndInvalidate]; + } + }); +} + +#pragma mark - + +- (void)setResponseSerializer:(id )responseSerializer { + NSParameterAssert(responseSerializer); + + _responseSerializer = responseSerializer; +} + +#pragma mark - +- (void)addNotificationObserverForTask:(NSURLSessionTask *)task { + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:task]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:task]; +} + +- (void)removeNotificationObserverForTask:(NSURLSessionTask *)task { + [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidSuspendNotification object:task]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidResumeNotification object:task]; +} + +#pragma mark - + +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + return [self dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:completionHandler]; +} + +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler { + + __block NSURLSessionDataTask *dataTask = nil; + url_session_manager_create_task_safely(^{ + dataTask = [self.session dataTaskWithRequest:request]; + }); + + [self addDelegateForDataTask:dataTask uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler]; + + return dataTask; +} + +#pragma mark - + +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromFile:(NSURL *)fileURL + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + __block NSURLSessionUploadTask *uploadTask = nil; + url_session_manager_create_task_safely(^{ + uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL]; + }); + + if (!uploadTask && self.attemptsToRecreateUploadTasksForBackgroundSessions && self.session.configuration.identifier) { + for (NSUInteger attempts = 0; !uploadTask && attempts < AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask; attempts++) { + uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL]; + } + } + + [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; + + return uploadTask; +} + +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromData:(NSData *)bodyData + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + __block NSURLSessionUploadTask *uploadTask = nil; + url_session_manager_create_task_safely(^{ + uploadTask = [self.session uploadTaskWithRequest:request fromData:bodyData]; + }); + + [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; + + return uploadTask; +} + +- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + __block NSURLSessionUploadTask *uploadTask = nil; + url_session_manager_create_task_safely(^{ + uploadTask = [self.session uploadTaskWithStreamedRequest:request]; + }); + + [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; + + return uploadTask; +} + +#pragma mark - + +- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler +{ + __block NSURLSessionDownloadTask *downloadTask = nil; + url_session_manager_create_task_safely(^{ + downloadTask = [self.session downloadTaskWithRequest:request]; + }); + + [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler]; + + return downloadTask; +} + +- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler +{ + __block NSURLSessionDownloadTask *downloadTask = nil; + url_session_manager_create_task_safely(^{ + downloadTask = [self.session downloadTaskWithResumeData:resumeData]; + }); + + [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler]; + + return downloadTask; +} + +#pragma mark - +- (NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task { + return [[self delegateForTask:task] uploadProgress]; +} + +- (NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task { + return [[self delegateForTask:task] downloadProgress]; +} + +#pragma mark - + +- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block { + self.sessionDidBecomeInvalid = block; +} + +- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block { + self.sessionDidReceiveAuthenticationChallenge = block; +} + +- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block { + self.didFinishEventsForBackgroundURLSession = block; +} + +#pragma mark - + +- (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block { + self.taskNeedNewBodyStream = block; +} + +- (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block { + self.taskWillPerformHTTPRedirection = block; +} + +- (void)setTaskDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block { + self.taskDidReceiveAuthenticationChallenge = block; +} + +- (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block { + self.taskDidSendBodyData = block; +} + +- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block { + self.taskDidComplete = block; +} + +#pragma mark - + +- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block { + self.dataTaskDidReceiveResponse = block; +} + +- (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block { + self.dataTaskDidBecomeDownloadTask = block; +} + +- (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block { + self.dataTaskDidReceiveData = block; +} + +- (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block { + self.dataTaskWillCacheResponse = block; +} + +#pragma mark - + +- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block { + self.downloadTaskDidFinishDownloading = block; +} + +- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block { + self.downloadTaskDidWriteData = block; +} + +- (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block { + self.downloadTaskDidResume = block; +} + +#pragma mark - NSObject + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, self.session, self.operationQueue]; +} + +- (BOOL)respondsToSelector:(SEL)selector { + if (selector == @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)) { + return self.taskWillPerformHTTPRedirection != nil; + } else if (selector == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) { + return self.dataTaskDidReceiveResponse != nil; + } else if (selector == @selector(URLSession:dataTask:willCacheResponse:completionHandler:)) { + return self.dataTaskWillCacheResponse != nil; + } else if (selector == @selector(URLSessionDidFinishEventsForBackgroundURLSession:)) { + return self.didFinishEventsForBackgroundURLSession != nil; + } + + return [[self class] instancesRespondToSelector:selector]; +} + +#pragma mark - NSURLSessionDelegate + +- (void)URLSession:(NSURLSession *)session +didBecomeInvalidWithError:(NSError *)error +{ + if (self.sessionDidBecomeInvalid) { + self.sessionDidBecomeInvalid(session, error); + } + + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDidInvalidateNotification object:session]; +} + +- (void)URLSession:(NSURLSession *)session +didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler +{ + NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; + __block NSURLCredential *credential = nil; + + if (self.sessionDidReceiveAuthenticationChallenge) { + disposition = self.sessionDidReceiveAuthenticationChallenge(session, challenge, &credential); + } else { + if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { + if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { + credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; + if (credential) { + disposition = NSURLSessionAuthChallengeUseCredential; + } else { + disposition = NSURLSessionAuthChallengePerformDefaultHandling; + } + } else { + disposition = NSURLSessionAuthChallengeRejectProtectionSpace; + } + } else { + disposition = NSURLSessionAuthChallengePerformDefaultHandling; + } + } + + if (completionHandler) { + completionHandler(disposition, credential); + } +} + +#pragma mark - NSURLSessionTaskDelegate + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +willPerformHTTPRedirection:(NSHTTPURLResponse *)response + newRequest:(NSURLRequest *)request + completionHandler:(void (^)(NSURLRequest *))completionHandler +{ + NSURLRequest *redirectRequest = request; + + if (self.taskWillPerformHTTPRedirection) { + redirectRequest = self.taskWillPerformHTTPRedirection(session, task, response, request); + } + + if (completionHandler) { + completionHandler(redirectRequest); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler +{ + NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; + __block NSURLCredential *credential = nil; + + if (self.taskDidReceiveAuthenticationChallenge) { + disposition = self.taskDidReceiveAuthenticationChallenge(session, task, challenge, &credential); + } else { + if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { + if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { + disposition = NSURLSessionAuthChallengeUseCredential; + credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; + } else { + disposition = NSURLSessionAuthChallengeRejectProtectionSpace; + } + } else { + disposition = NSURLSessionAuthChallengePerformDefaultHandling; + } + } + + if (completionHandler) { + completionHandler(disposition, credential); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler +{ + NSInputStream *inputStream = nil; + + if (self.taskNeedNewBodyStream) { + inputStream = self.taskNeedNewBodyStream(session, task); + } else if (task.originalRequest.HTTPBodyStream && [task.originalRequest.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) { + inputStream = [task.originalRequest.HTTPBodyStream copy]; + } + + if (completionHandler) { + completionHandler(inputStream); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + didSendBodyData:(int64_t)bytesSent + totalBytesSent:(int64_t)totalBytesSent +totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend +{ + + int64_t totalUnitCount = totalBytesExpectedToSend; + if(totalUnitCount == NSURLSessionTransferSizeUnknown) { + NSString *contentLength = [task.originalRequest valueForHTTPHeaderField:@"Content-Length"]; + if(contentLength) { + totalUnitCount = (int64_t) [contentLength longLongValue]; + } + } + + if (self.taskDidSendBodyData) { + self.taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalUnitCount); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didCompleteWithError:(NSError *)error +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; + + // delegate may be nil when completing a task in the background + if (delegate) { + [delegate URLSession:session task:task didCompleteWithError:error]; + + [self removeDelegateForTask:task]; + } + + if (self.taskDidComplete) { + self.taskDidComplete(session, task, error); + } +} + +#pragma mark - NSURLSessionDataDelegate + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didReceiveResponse:(NSURLResponse *)response + completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler +{ + NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow; + + if (self.dataTaskDidReceiveResponse) { + disposition = self.dataTaskDidReceiveResponse(session, dataTask, response); + } + + if (completionHandler) { + completionHandler(disposition); + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; + if (delegate) { + [self removeDelegateForTask:dataTask]; + [self setDelegate:delegate forTask:downloadTask]; + } + + if (self.dataTaskDidBecomeDownloadTask) { + self.dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask); + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + didReceiveData:(NSData *)data +{ + + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; + [delegate URLSession:session dataTask:dataTask didReceiveData:data]; + + if (self.dataTaskDidReceiveData) { + self.dataTaskDidReceiveData(session, dataTask, data); + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + willCacheResponse:(NSCachedURLResponse *)proposedResponse + completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler +{ + NSCachedURLResponse *cachedResponse = proposedResponse; + + if (self.dataTaskWillCacheResponse) { + cachedResponse = self.dataTaskWillCacheResponse(session, dataTask, proposedResponse); + } + + if (completionHandler) { + completionHandler(cachedResponse); + } +} + +- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session { + if (self.didFinishEventsForBackgroundURLSession) { + dispatch_async(dispatch_get_main_queue(), ^{ + self.didFinishEventsForBackgroundURLSession(session); + }); + } +} + +#pragma mark - NSURLSessionDownloadDelegate + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask +didFinishDownloadingToURL:(NSURL *)location +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; + if (self.downloadTaskDidFinishDownloading) { + NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); + if (fileURL) { + delegate.downloadFileURL = fileURL; + NSError *error = nil; + [[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error]; + if (error) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo]; + } + + return; + } + } + + if (delegate) { + [delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location]; + } +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didWriteData:(int64_t)bytesWritten + totalBytesWritten:(int64_t)totalBytesWritten +totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite +{ + if (self.downloadTaskDidWriteData) { + self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); + } +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didResumeAtOffset:(int64_t)fileOffset +expectedTotalBytes:(int64_t)expectedTotalBytes +{ + if (self.downloadTaskDidResume) { + self.downloadTaskDidResume(session, downloadTask, fileOffset, expectedTotalBytes); + } +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; + + self = [self initWithSessionConfiguration:configuration]; + if (!self) { + return nil; + } + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration]; +} + +@end diff --git a/its/plugin/projects/AFNetworking/CHANGELOG.md b/its/plugin/projects/AFNetworking/CHANGELOG.md new file mode 100644 index 00000000..82dc3d02 --- /dev/null +++ b/its/plugin/projects/AFNetworking/CHANGELOG.md @@ -0,0 +1,1996 @@ +#Change Log +All notable changes to this project will be documented in this file. +`AFNetworking` adheres to [Semantic Versioning](http://semver.org/). + +--- + +## [3.0.4](https://github.com/AFNetworking/AFNetworking/releases/tag/3.0.4) (12/18/2015) +Released on Friday, December 18, 2015. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A3.0.4+is%3Aclosed). + +#### Fixed +* Fixed issue where `AFNSURLSessionTaskDidResumeNotification` was removed twice + * Implemented by Kevin Harwood in [#3236](https://github.com/AFNetworking/AFNetworking/pull/3236). + + +## [3.0.3](https://github.com/AFNetworking/AFNetworking/releases/tag/3.0.3) (12/16/2015) +Released on Wednesday, December 16, 2015. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A3.0.3+is%3Aclosed). + +#### Added +* Added tests for response serializers to increase test coverage + * Implemented by Kevin Harwood in [#3233](https://github.com/AFNetworking/AFNetworking/pull/3233). + +#### Fixed +* Fixed `AFImageResponseSerializer` serialization macros on watchOS and tvOS + * Implemented by Charles Joseph in [#3229](https://github.com/AFNetworking/AFNetworking/pull/3229). + + +## [3.0.2](https://github.com/AFNetworking/AFNetworking/releases/tag/3.0.2) (12/14/2015) +Released on Monday, December 14, 2015. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A3.0.2+is%3Aclosed). + +#### Fixed +* Fixed a crash in `AFURLSessionManager` when resuming download tasks + * Implemented by Chongyu Zhu in [#3222](https://github.com/AFNetworking/AFNetworking/pull/3222). +* Fixed issue where background button image would not be updated + * Implemented by eofs in [#3220](https://github.com/AFNetworking/AFNetworking/pull/3220). + + +## [3.0.1](https://github.com/AFNetworking/AFNetworking/releases/tag/3.0.1) (12/11/2015) +Released on Friday, December 11, 2015. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A3.0.1+is%3Aclosed). + +#### Added +* Added Xcode 7.2 support to Travis + * Implemented by Kevin Harwood in [#3216](https://github.com/AFNetworking/AFNetworking/pull/3216). + +#### Fixed +* Fixed race condition with ImageView/Button image downloading when starting/cancelling/starting the same request + * Implemented by Kevin Harwood in [#3215](https://github.com/AFNetworking/AFNetworking/pull/3215). + + +## [3.0.0](https://github.com/AFNetworking/AFNetworking/releases/tag/3.0.0) (12/10/2015) +Released on Thursday, December 10, 2015. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A3.0.0+is%3Aclosed). + +For detailed information about migrating to AFNetworking 3.0.0, please reference the [migration guide](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-3.0-Migration-Guide). All 3.0.0 beta changes will be tracked with this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A3.0.0+is%3Aclosed). + +#### Added +* Added support for older versions of Xcode to Travis + * Implemented by Kevin Harwood in [#3209](https://github.com/AFNetworking/AFNetworking/pull/3209). +* Added support for [Codecov.io](https://codecov.io/github/AFNetworking/AFNetworking/AFNetworking?branch=master#sort=coverage&dir=desc) + * Implemented by Cédric Luthi and Kevin Harwood in [#3196](https://github.com/AFNetworking/AFNetworking/pull/3196). + * * **Please help us increase overall coverage by submitting a pull request!** +* Added support for IPv6 to Reachability + * Implemented by SAMUKEI and Kevin Harwood in [#3174](https://github.com/AFNetworking/AFNetworking/pull/3174). +* Added support for Objective-C light weight generics + * Implemented by Kevin Harwood in [#3166](https://github.com/AFNetworking/AFNetworking/pull/3166). +* Added nullability attributes to response object in success block + * Implemented by Nathan Racklyeft in [#3154](https://github.com/AFNetworking/AFNetworking/pull/3154). +* Migrated to Fastlane for CI and Deployment + * Implemented by Kevin Harwood in [#3148](https://github.com/AFNetworking/AFNetworking/pull/3148). +* Added support for tvOS + * Implemented by Kevin Harwood in [#3128](https://github.com/AFNetworking/AFNetworking/issues/3128). +* New image downloading architecture + * Implemented by Kevin Harwood in [#3122](https://github.com/AFNetworking/AFNetworking/issues/3122). +* Added Carthage Support + * Implemented by Kevin Harwood in [#3121](https://github.com/AFNetworking/AFNetworking/issues/3121). +* Added a method to create a unique reachability manager + * Implemented by Mo Bitar in [#3111](https://github.com/AFNetworking/AFNetworking/pull/3111). +* Added a initial delay to the network indicator per the Apple HIG + * Implemented by Kevin Harwood in [#3094](https://github.com/AFNetworking/AFNetworking/pull/3094). + +#### Updated +* Improved testing reliability for continuous integration + * Implemented by Kevin Harwood in [#3124](https://github.com/AFNetworking/AFNetworking/pull/3124). +* Example project now consumes AFNetworking as a library. + * Implemented by Kevin Harwood in [#3068](https://github.com/AFNetworking/AFNetworking/pull/3068). +* Migrated to using `instancetype` where applicable + * Implemented by Kyle Fuller in [#3064](https://github.com/AFNetworking/AFNetworking/pull/3064). +* Tweaks to project to support Framework Project + * Implemented by Christian Noon in [#3062](https://github.com/AFNetworking/AFNetworking/pull/3062). + +#### Changed +* Split the iOS and OS X AppDelegate classes in the Example Project + * Implemented by Cédric Luthi in [#3193](https://github.com/AFNetworking/AFNetworking/pull/3193). +* Changed SSL Pinning Error to be `NSURLErrorServerCertificateUntrusted` + * Implemented by Cédric Luthi and Kevin Harwood in [#3191](https://github.com/AFNetworking/AFNetworking/pull/3191). +* New Progress Reporting API using `NSProgress` + * Implemented by Kevin Harwood in [#3187](https://github.com/AFNetworking/AFNetworking/pull/3187). +* Changed `pinnedCertificates` type in `AFSecurityPolicy` from `NSArray` to `NSSet` + * Implemented by Cédric Luthi in [#3164](https://github.com/AFNetworking/AFNetworking/pull/3164). + +#### Fixed +* Improved task creation performance for iOS 8+ + * Implemented by nikitahils, Nikita G and Kevin Harwood in [#3208](https://github.com/AFNetworking/AFNetworking/pull/3208). +* Fixed certificate validation for servers providing incomplete chains + * Implemented by André Pacheco Neves in [#3159](https://github.com/AFNetworking/AFNetworking/pull/3159). +* Fixed bug in `AFMultipartBodyStream` that may cause the input stream to read more bytes than required. + * Implemented by bang in [#3153](https://github.com/AFNetworking/AFNetworking/pull/3153). +* Fixed race condition crash from Resume/Suspend task notifications + * Implemented by Kevin Harwood in [#3152](https://github.com/AFNetworking/AFNetworking/pull/3152). +* Fixed `AFImageDownloader` stalling after numerous failures + * Implemented by Rick Silva in [#3150](https://github.com/AFNetworking/AFNetworking/pull/3150). +* Fixed warnings generated in UIWebView category + * Implemented by Kevin Harwood in [#3126](https://github.com/AFNetworking/AFNetworking/pull/3126). + +#### Removed +* Removed AFBase64EncodedStringFromString static function + * Implemented by Cédric Luthi in [#3188](https://github.com/AFNetworking/AFNetworking/pull/3188). +* Removed code supporting conditional compilation for unsupported development configurations. + * Implemented by Cédric Luthi in [#3177](https://github.com/AFNetworking/AFNetworking/pull/3177). +* Removed deprecated methods, properties, and notifications from AFN 2.x + * Implemented by Kevin Harwood in [#3168](https://github.com/AFNetworking/AFNetworking/pull/3168). +* Removed support for `NSURLConnection` + * Implemented by Kevin Harwood in [#3120](https://github.com/AFNetworking/AFNetworking/issues/3120). +* Removed `UIAlertView` category support since it is now deprecated + * Implemented by Kevin Harwood in [#3034](https://github.com/AFNetworking/AFNetworking/pull/3034). + + +##[2.6.3](https://github.com/AFNetworking/AFNetworking/releases/tag/2.6.3) (11/11/2015) +Released on Wednesday, November 11, 2015. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A2.6.3+is%3Aclosed). + +#### Fixed +* Fixed clang analyzer warning suppression that prevented building under some project configurations + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#3142](https://github.com/AFNetworking/AFNetworking/pull/3142). +* Restored Xcode 6 compatibility + * Fixed by [jcayzac](https://github.com/jcayzac) in [#3139](https://github.com/AFNetworking/AFNetworking/pull/3139). + + +##[2.6.2](https://github.com/AFNetworking/AFNetworking/releases/tag/2.6.2) (11/06/2015) +Released on Friday, November 06, 2015. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A2.6.2+is%3Aclosed). + +### Important Upgrade Note for Swift +* [#3130](https://github.com/AFNetworking/AFNetworking/pull/3130) fixes a swift interop error that does have a breaking API change if you are using Swift. This was [identified](https://github.com/AFNetworking/AFNetworking/issues/3137) after 2.6.2 was released. It changes the method from `throws` to an error pointer, since that method does return an object and also handles an error pointer, which does not play nicely with the Swift/Objective-C error conversion. See [#2810](https://github.com/AFNetworking/AFNetworking/issues/2810) for additional notes. This affects `AFURLRequestionSerializer` and `AFURLResponseSerializer`. + +#### Added +* `AFHTTPSessionManager` now copies its `securityPolicy` + * Fixed by [mohamede1945](https://github.com/mohamede1945) in [#2887](https://github.com/AFNetworking/AFNetworking/pull/2887). + +#### Updated +* Updated travis to run on 7.1 + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#3132](https://github.com/AFNetworking/AFNetworking/pull/3132). +* Simplifications of if and return statements in `AFSecurityPolicy` + * Fixed by [TorreyBetts](https://github.com/TorreyBetts) in [#3063](https://github.com/AFNetworking/AFNetworking/pull/3063). + +#### Fixed +* Fixed swift interop issue that prevented returning a nil NSURL for a download task + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#3133](https://github.com/AFNetworking/AFNetworking/pull/3133). +* Suppressed false positive memory leak warning in Reachability Manager + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#3131](https://github.com/AFNetworking/AFNetworking/pull/3131). +* Fixed swift interop issue with throws and Request/Response serialization. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#3130](https://github.com/AFNetworking/AFNetworking/pull/3130). +* Fixed race condition in reachability callback delivery + * Fixed by [MichaelHackett](https://github.com/MichaelHackett) in [#3117](https://github.com/AFNetworking/AFNetworking/pull/3117). +* Fixed URLs that were redirecting in the README + * Fixed by [frankenbot](https://github.com/frankenbot) in [#3109](https://github.com/AFNetworking/AFNetworking/pull/3109). +* Fixed Project Warnings + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#3102](https://github.com/AFNetworking/AFNetworking/pull/3102). +* Fixed README link to WWDC session + * Fixed by [wrtsprt](https://github.com/wrtsprt) in [#3099](https://github.com/AFNetworking/AFNetworking/pull/3099). +* Switched from `OS_OBJECT_HAVE_OBJC_SUPPORT` to `OS_OBJECT_USE_OBJC` for watchOS 2 support. + * Fixed by [kylef](https://github.com/kylef) in [#3065](https://github.com/AFNetworking/AFNetworking/pull/3065). +* Added missing __nullable attributes to failure blocks in `AFHTTPRequestOperationManager` and `AFHTTPSessionManager` + * Fixed by [hoppenichu](https://github.com/hoppenichu) in [#3057](https://github.com/AFNetworking/AFNetworking/pull/3057). +* Fixed memory leak in NSURLSession handling + * Fixed by [olegnaumenko](https://github.com/olegnaumenko) in [#2794](https://github.com/AFNetworking/AFNetworking/pull/2794). + + +## [2.6.1](https://github.com/AFNetworking/AFNetworking/releases/tag/2.6.1) (10-13-2015) +Released on Tuesday, October 13th, 2015. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A2.6.1+is%3Aclosed). + +###Future Compatibility Note +Note that AFNetworking 3.0 will soon be released, and will drop support for all `NSURLConnection` based API's (`AFHTTPRequestOperationManager`, `AFHTTPRequestOperation`, and `AFURLConnectionOperation`. If you have not already migrated to `NSURLSession` based API's, please do so soon. For more information, please see the [3.0 migration guide](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-3.0-Migration-Guide). + +####Fixed +* Fixed a bug that prevented empty x-www-form-urlencoded bodies. + * Fixed by [Julien Cayzac](https://github.com/jcayzac) in [#2868](https://github.com/AFNetworking/AFNetworking/pull/2868). +* Fixed bug that prevented AFNetworking from being installed for watchOS via Cocoapods. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2909](https://github.com/AFNetworking/AFNetworking/issues/2909). +* Added missing nullable attributes to `AFURLRequestSerialization` and `AFURLSessionManager`. + * Fixed by [andrewtoth](https://github.com/andrewtoth) in [#2911](https://github.com/AFNetworking/AFNetworking/pull/2911). +* Migrated to `OS_OBJECT_USE_OBJC`. + * Fixed by [canius](https://github.com/canius) in [#2930](https://github.com/AFNetworking/AFNetworking/pull/2930). +* Added missing nullable tags to UIKit extensions. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#3000](https://github.com/AFNetworking/AFNetworking/pull/3000). +* Fixed potential infinite recursion loop if multiple versions of AFNetworking are loaded in a target. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2743](https://github.com/AFNetworking/AFNetworking/issues/2743). +* Updated Travis CI test script + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#3032](https://github.com/AFNetworking/AFNetworking/issues/3032). +* Migrated to `FOUNDATION_EXPORT` from `extern`. + * Fixed by [Andrey Mikhaylov](https://github.com/pronebird) in [#3041](https://github.com/AFNetworking/AFNetworking/pull/3041). +* Fixed issue where `AFURLConnectionOperation` could get stuck in an infinite loop. + * Fixed by [Mattt Thompson](https://github.com/mattt) in [#2496](https://github.com/AFNetworking/AFNetworking/pull/2496). +* Fixed regression where URL request serialization would crash on iOS 8 for long URLs. + * Fixed by [softenhard](https://github.com/softenhard) in [#3028](https://github.com/AFNetworking/AFNetworking/pull/3028). + +## [2.6.0](https://github.com/AFNetworking/AFNetworking/releases/tag/2.6.0) (08-19-2015) +Released on Wednesday, August 19th, 2015. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A2.6.0+is%3Aclosed). + +###Important Upgrade Notes +Please note the following API/project changes have been made: + +* iOS 6 and OS X 10.8 support has been dropped from the project to facilitate support for watchOS 2. The final release supporting iOS 6 and OS X 10.8 is 2.5.4. +* **Full Certificate Chain Validation has been removed** from `AFSecurityPolicy`. As discussed in [#2744](https://github.com/AFNetworking/AFNetworking/issues/2744), there was no documented security advantage to pinning against an entire certificate chain. If you were using full certificate chain, please determine and select the most ideal certificate in your chain to pin against. + * Implemented by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2856](https://github.com/AFNetworking/AFNetworking/pull/2856). +* **The request url will now be returned by the `UIImageView` category if the image is returned from cache.** In previous releases, both the request and the response were nil. Going forward, only the response will be nil. + * Implemented by [Chris Gibbs](https://github.com/chrisgibbs) in [#2771](https://github.com/AFNetworking/AFNetworking/pull/2771). +* **Support for App Extension Targets is now baked in using `NS_EXTENSION_UNAVAILABLE_IOS`.** You no longer need to define `AF_APP_EXTENSIONS` in order to include code in a extension target. + * Implemented by [bnickel](https://github.com/bnickel) in [#2737](https://github.com/AFNetworking/AFNetworking/pull/2737). +* This release now supports watchOS 2.0, which relys on target conditionals that are only present in Xcode 7 and iOS 9/watchOS 2.0/OS X 10.10. If you install the library using CocoaPods, AFNetworking will define these target conditionals for on older platforms, allowing your code to compile. If you do not use Cocoapods, you will need to add the following code your to PCH file. + +``` +#ifndef TARGET_OS_IOS + #define TARGET_OS_IOS TARGET_OS_IPHONE +#endif +#ifndef TARGET_OS_WATCH + #define TARGET_OS_WATCH 0 +#endif +``` +* This release migrates query parameter serialization to model AlamoFire and adhere to RFC standards. Note that `/` and `?` are no longer encoded by default. + * Implemented by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2908](https://github.com/AFNetworking/AFNetworking/pull/2908). + + + +**Note** that support for `NSURLConnection` based API's will be removed in a future update. If you have not already done so, it is recommended that you transition to the `NSURLSession` APIs in the very near future. + +####Added +* Added watchOS 2.0 support. `AFNetworking` can now be added to watchOS targets using CocoaPods. + * Added by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2837](https://github.com/AFNetworking/AFNetworking/issues/2837). +* Added nullability annotations to all of the header files to improve Swift interoperability. + * Added by [Frank LSF](https://github.com/franklsf95) and [Kevin Harwood](https://github.com/Kevin Harwood) in [#2814](https://github.com/AFNetworking/AFNetworking/pull/2814). +* Converted source to Modern Objective-C Syntax. + * Implemented by [Matt Shedlick](https://github.com/mattshedlick) and [Kevin Harwood](https://github.com/Kevin Harwood) in [#2688](https://github.com/AFNetworking/AFNetworking/pull/2688). +* Improved memory performance when download large objects. + * Fixed by [Gabe Zabrino](https://github.com/gfzabarino) and [Kevin Harwood](https://github.com/Kevin Harwood) in [#2672](https://github.com/AFNetworking/AFNetworking/pull/2672). + +####Fixed +* Fixed a crash related for objects that observe notifications but don't properly unregister. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) and [bnickle](https://github.com/bnickel) in [#2741](https://github.com/AFNetworking/AFNetworking/pull/2741). +* Fixed a race condition crash that occured with `AFImageResponseSerialization`. + * Fixed by [Paulo Ferreria](https://github.com/paulosotu) and [Kevin Harwood](https://github.com/Kevin Harwood) in [#2815](https://github.com/AFNetworking/AFNetworking/pull/2815). +* Fixed an issue where tests failed to run on CI due to unavailable simulators. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2834](https://github.com/AFNetworking/AFNetworking/pull/2834). +* Fixed "method override not found" warnings in Xcode 7 Betas + * Fixed by [Ben Guo](https://github.com/benzguo) in [#2822](https://github.com/AFNetworking/AFNetworking/pull/2822) +* Removed Duplicate Import and UIKit Header file. + * Fixed by [diehardest](https://github.com/diehardest) in [#2813](https://github.com/AFNetworking/AFNetworking/pull/2813) +* Removed the ability to include duplicate certificates in the pinned certificate chain. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2756](https://github.com/AFNetworking/AFNetworking/pull/2756). +* Fixed potential memory leak in `AFNetworkReachabilityManager`. + * Fixed by [Julien Cayzac](https://github.com/jcayzac) in [#2867](https://github.com/AFNetworking/AFNetworking/pull/2867). + +####Documentation Improvements +* Clarified best practices for Reachability per Apple recommendations. + * Fixed by [Steven Fisher](https://github.com/tewha) in [#2704](https://github.com/AFNetworking/AFNetworking/pull/2704). +* Added `startMonitoring` call to the Reachability section of the README + * Added by [Jawwad Ahmad](https://github.com/jawwad) in [#2831](https://github.com/AFNetworking/AFNetworking/pull/2831). +* Fixed documentation error around how `baseURL` is used for reachability monitoring. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2761](https://github.com/AFNetworking/AFNetworking/pull/2761). +* Numerous spelling corrections in the documentation. + * Fixed by [Antoine Cœur](https://github.com/Coeur) in [#2732](https://github.com/AFNetworking/AFNetworking/pull/2732) and [#2898](https://github.com/AFNetworking/AFNetworking/pull/2898). + +## [2.5.4](https://github.com/AFNetworking/AFNetworking/releases/tag/2.5.4) (2015-05-14) +Released on 2015-05-14. All issues associated with this milestone can be found using this [filter](https://github.com/AFNetworking/AFNetworking/issues?q=milestone%3A2.5.4+is%3Aclosed). + +####Updated +* Updated the CI test script to run iOS tests on all versions of iOS that are installed on the build machine. + * Updated by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2716](https://github.com/AFNetworking/AFNetworking/pull/2716). + +####Fixed + +* Fixed an issue where `AFNSURLSessionTaskDidResumeNotification` and `AFNSURLSessionTaskDidSuspendNotification` were not being properly called due to implementation differences in `NSURLSessionTask` in iOS 7 and iOS 8, which also affects the `AFNetworkActivityIndicatorManager`. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2702](https://github.com/AFNetworking/AFNetworking/pull/2702). +* Fixed an issue where the OS X test linker would throw a warning during tests. + * Fixed by [Christian Noon](https://github.com/cnoon) in [#2719](https://github.com/AFNetworking/AFNetworking/pull/2719). +* Fixed an issue where tests would randomly fail due to mocked objects not being cleaned up. + * Fixed by [Kevin Harwood](https://github.com/Kevin Harwood) in [#2717](https://github.com/AFNetworking/AFNetworking/pull/2717). + + +## [2.5.3](https://github.com/AFNetworking/AFNetworking/releases/tag/2.5.3) (2015-04-20) + +* Add security policy tests for default policy + +* Add network reachability tests + +* Change `validatesDomainName` property to default to `YES` under all * security policies + +* Fix `NSURLSession` subspec compatibility with iOS 6 / OS X 10.8 + +* Fix leak of data task used in `NSURLSession` swizzling + +* Fix leak for observers from `addObserver:...:withBlock:` + +* Fix issue with network reachability observation on domain name + +## [2.5.2](https://github.com/AFNetworking/AFNetworking/releases/tag/2.5.2) (2015-03-26) +**NOTE** This release contains a security vulnerabilty. **All users should upgrade to a 2.5.3 or greater**. Please reference this [statement](https://gist.github.com/AlamofireSoftwareFoundation/f784f18f949b95ab733a) if you have any further questions about this release. + +* Add guards for unsupported features in iOS 8 App Extensions + +* Add missing delegate callbacks to `UIWebView` category + +* Add test and implementation of strict default certificate validation + +* Add #define for `NS_DESIGNATED_INITIALIZER` for unsupported versions of Xcode + +* Fix `AFNetworkActivityIndicatorManager` for iOS 7 + +* Fix `AFURLRequestSerialization` property observation + +* Fix `testUploadTasksProgressBecomesPartOfCurrentProgress` + +* Fix warnings from Xcode 6.3 Beta + +* Fix `AFImageWithDataAtScale` handling of animated images + +* Remove `AFNetworkReachabilityAssociation` enumeration + +* Update to conditional use assign semantics for GCD properties based on `OS_OBJECT_HAVE_OBJC_SUPPORT` for better Swift support + +## [2.5.1](https://github.com/AFNetworking/AFNetworking/releases/tag/2.5.1) (2015-02-09) +**NOTE** This release contains a security vulnerabilty. **All users should upgrade to a 2.5.3 or greater**. Please reference this [statement](https://gist.github.com/AlamofireSoftwareFoundation/f784f18f949b95ab733a) if you have any further questions about this release. + + * Add `NS_DESIGNATED_INITIALIZER` macros. (Samir Guerdah) + + * Fix and clarify documentation for `stringEncoding` property. (Mattt +Thompson) + + * Fix for NSProgress bug where two child NSProgress instances are added to a +parent NSProgress. (Edward Povazan) + + * Fix incorrect file names in headers. (Steven Fisher) + + * Fix KVO issue when running testing target caused by lack of +`automaticallyNotifiesObserversForKey:` implementation. (Mattt Thompson) + + * Fix use of variable arguments for UIAlertView category. (Kenta Tokumoto) + + * Fix `genstrings` warning for `NSLocalizedString` usage in +`UIAlertView+AFNetworking`. (Adar Porat) + + * Fix `NSURLSessionManager` task observation for network activity indicator +manager. (Phil Tang) + + * Fix `UIButton` category method caching of background image (Fernanda G. +Geraissate) + + * Fix `UIButton` category method failure handling. (Maxim Zabelin) + + * Update multipart upload method requirements to ensure `request.HTTPBody` +is non-nil. (Mattt Thompson) + + * Update to use builtin `__Require` macros from AssertMacros.h. (Cédric +Luthi) + + * Update `parameters` parameter to accept `id` for custom serialization +block. (@mooosu) + +## [2.5.0](https://github.com/AFNetworking/AFNetworking/releases/tag/2.5.0) (2014-11-17) + + * Add documentation for expected background session manager usage (Aaron +Brager) + + * Add missing documentation for `AFJSONRequestSerializer` and +`AFPropertyListSerializer` (Mattt Thompson) + + * Add tests for requesting HTTPS endpoints (Mattt Thompson) + + * Add `init` method declarations of `AFURLResponseSerialization` classes for +Swift compatibility (Allen Rohner) + + * Change default User-Agent to use the version number instead of the build +number (Tim Watson) + + * Change `validatesDomainName` to readonly property (Mattt Thompson, Brian +King) + + * Fix checks when observing `AFHTTPRequestSerializerObservedKeyPaths` (Jacek +Suliga) + + * Fix crash caused by attempting to set nil `NSURLResponse -URL` as key for +`userInfo` dictionary (Elvis Nuñez) + + * Fix crash for multipart streaming requests in XPC services (Mattt Thompson) + + * Fix minor aspects of response serializer documentation (Mattt Thompson) + + * Fix potential race condition for `AFURLConnectionOperation -description` + + * Fix widespread crash related to key-value observing of `NSURLSessionTask +-state` (Phil Tang) + + * Fix `UIButton` category associated object keys (Kristian Bauer, Mattt +Thompson) + + * Remove `charset` parameter from Content-Type HTTP header field values for +`AFJSONRequestSerializer` and `AFPropertyListSerializer` (Mattt Thompson) + + * Update CocoaDocs color scheme (@Orta) + + * Update Podfile to explicitly define sources (Kyle Fuller) + + * Update to relay `downloadFileURL` to the delegate if the manager picks a +`fileURL` (Brian King) + + * Update `AFSSLPinningModeNone` to not validate domain name (Brian King) + + * Update `UIButton` category to cache images in `sharedImageCache` (John +Bushnell) + + * Update `UIRefreshControl` category to set control state to current state +of request (Elvis Nuñez) + +## [2.4.1](https://github.com/AFNetworking/AFNetworking/releases/tag/2.4.1) (2014-09-04) + + * Fix compiler warning generated on 32-bit architectures (John C. Daub) + + * Fix potential crash caused by failed validation with nil responseData + (Mattt Thompson) + + * Fix to suppress compiler warnings for out-of-range enumerated type + value assignment (Mattt Thompson) + +## [2.4.0](https://github.com/AFNetworking/AFNetworking/releases/tag/2.4.0) (2014-09-03) + + * Add CocoaDocs color scheme (Orta) + + * Add image cache to `UIButton` category (Kristian Bauer, Mattt Thompson) + + * Add test for success block on 204 response (Mattt Thompson) + + * Add tests for encodable and re-encodable query string parameters (Mattt +Thompson) + + * Add `AFHTTPRequestSerializer -valueForHTTPHeaderField:` (Kyle Fuller) + + * Add `AFNetworkingOperationFailingURLResponseDataErrorKey` key to user info +of serialization error (Yannick Heinrich) + + * Add `imageResponseSerializer` property to `UIButton` category (Kristian +Bauer, Mattt Thompson) + + * Add `removesKeysWithNullValues` setting to serialization and copying (Jon +Shier) + + * Change request and response serialization tests to be factored out into +separate files (Mattt Thompson) + + * Change signature of success parameters in `UIButton` category methods to +match those in `UIImageView` (Mattt Thompson) + + * Change to remove charset parameter from +`application/x-www-form-urlencoded` content type (Mattt Thompson) + + * Change `AFImageCache` to conform to `NSObject` protocol ( Marcelo Fabri) + + * Change `AFMaximumNumberOfToRecreateBackgroundSessionUploadTask` to +`AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask` (Mattt +Thompson) + + * Fix documentation error for NSSecureCoding (Robert Ryan) + + * Fix documentation for `URLSessionDidFinishEventsForBackgroundURLSession` +delegate method (Mattt Thompson) + + * Fix expired ADN certificate in example project (Carson McDonald) + + * Fix for interoperability within Swift project (Stephan Krusche) + + * Fix for potential deadlock due to KVO subscriptions within a lock +(Alexander Skvortsov) + + * Fix iOS 7 bug where session tasks can have duplicate identifiers if +created from different threads (Mattt Thompson) + + * Fix iOS 8 bug by adding explicit synthesis for `delegate` of +`AFMultipartBodyStream` (Mattt Thompson) + + * Fix issue caused by passing `nil` as body of multipart form part (Mattt +Thompson) + + * Fix issue caused by passing `nil` as destination in download task method +(Mattt Thompson) + + * Fix issue with `AFHTTPRequestSerializer` returning a request and silently +handling an error from a `queryStringSerialization` block (Kyle Fuller, Mattt +Thompson) + + * Fix potential issues by ensuring `invalidateSessionCancelingTasks` only +executes on main thread (Mattt Thompson) + + * Fix potential memory leak caused by deferred opening of output stream +(James Tomson) + + * Fix properties on session managers such that default values will not trump +values set in the session configuration (Mattt Thompson) + + * Fix README to include explicit call to start reachability manager (Mattt +Thompson) + + * Fix request serialization error handling in `AFHTTPSessionManager` +convenience methods (Kyle Fuller, Lars Anderson, Mattt Thompson) + + * Fix stray localization macro (Devin McKaskle) + + * Fix to ensure connection operation `-copyWithZone:` calls super +implementation (Chris Streeter) + + * Fix `UIButton` category to only cancel request for specified state +(@xuzhe, Mattt Thompson) + +## [2.3.1](https://github.com/AFNetworking/AFNetworking/releases/tag/2.3.1) (2014-06-13) + + * Fix issue with unsynthesized `streamStatus` & `streamError` properties +on `AFMultipartBodyStream` (Mattt Thompson) + +## [2.3.0](https://github.com/AFNetworking/AFNetworking/releases/tag/2.3.0) (2014-06-11) + + * Add check for `AF_APP_EXTENSIONS` macro to conditionally compile +background method that makes API call unavailable to App Extensions in iOS 8 +/ OS X 10.10 + + * Add further explanation for network reachability in documentation (Steven +Fisher) + + * Add notification for initial change from +`AFNetworkReachabilityStatusUnknown` to any other state (Jason Pepas, +Sebastian S.A., Mattt Thompson) + + * Add tests for AFNetworkActivityIndicatorManager (Dave Weston, Mattt +Thompson) + + * Add tests for AFURLSessionManager task progress (Ullrich Schäfer) + + * Add `attemptsToRecreateUploadTasksForBackgroundSessions` property, which +attempts Apple's recommendation of retrying a failed upload task if initial +creation did not succeed (Mattt Thompson) + + * Add `completionQueue` and `completionGroup` properties to +`AFHTTPRequestOperationManager` (Robert Ryan) + + * Change deprecating `AFErrorDomain` in favor of +`AFRequestSerializerErrorDomain` & `AFResponseSerializerErrorDomain` (Mattt +Thompson) + + * Change serialization tests to be split over two different files (Mattt +Thompson) + + * Change to make NSURLSession subspec not depend on NSURLConnection subspec +(Mattt Thompson) + + * Change to make Serialization subspec not depend on NSURLConnection subspec +(Nolan Waite, Mattt Thompson) + + * Change `completionHandler` of +`application:handleEventsForBackgroundURLSession:completion:` to be run on +main thread (Padraig Kennedy) + + * Change `UIImageView` category to accept any object conforming to +`AFURLResponseSerialization`, rather than just `AFImageResponseSerializer` +(Romans Karpelcevs) + + * Fix calculation and behavior of `NSProgress` (Padraig Kennedy, Ullrich +Schäfer) + + * Fix deprecation warning for `backgroundSessionConfiguration:` in iOS 8 / +OS X 10.10 (Mattt Thompson) + + * Fix implementation of `copyWithZone:` in serializer subclasses (Chris +Streeter) + + * Fix issue in Xcode 6 caused by implicit synthesis of overridden `NSStream` +properties (Clay Bridges, Johan Attali) + + * Fix KVO handling for `NSURLSessionTask` on iOS 8 / OS X 10.10 (Mattt +Thompson) + + * Fix KVO leak for `NSURLSessionTask` (@Zyphrax) + + * Fix potential crash caused by attempting to use non-existent error of +failing requests due to URLs exceeding a certain length (Boris Bügling) + + * Fix to check existence of `uploadProgress` block inside a referencing +`dispatch_async` to avoid potential race condition (Kyungkoo Kang) + + * Fix `UIImageView` category race conditions (Sunny) + + * Remove unnecessary default operation response serializer setters (Mattt +Thompson) + +## [2.2.4](https://github.com/AFNetworking/AFNetworking/releases/tag/2.2.4) (2014-05-13) + + * Add NSSecureCoding support to all AFNetworking classes (Kyle Fuller, Mattt +Thompson) + + * Change behavior of request operation `NSOutputStream` property to only nil +out if `responseData` is non-nil, meaning that no custom object was set +(Mattt Thompson) + + * Fix data tasks to not attempt to track progress, and rare related crash +(Padraig Kennedy) + + * Fix issue with `-downloadTaskDidFinishDownloading:` not being called +(Andrej Mihajlov) + + * Fix KVO leak on invalidated session tasks (Mattt Thompson) + + * Fix missing import of `UIRefreshControl+AFNetworking" (@BB9z) + + * Fix potential compilation errors on Mac OS X, caused by import order of +``, which signaled an incorrect deprecation warning (Mattt +Thompson) + + * Fix race condition in UIImageView+AFNetworking when making several image +requests in quick succession (Alexander Crettenand) + + * Update documentation for `-downloadTaskWithRequest:` to warn about blocks +being disassociated on app termination and backgrounding (Robert Ryan) + +## [2.2.3](https://github.com/AFNetworking/AFNetworking/releases/tag/2.2.3) (2014-04-18) + + * Fix `AFErrorOrUnderlyingErrorHasCodeInDomain` function declaration for +AFXMLDocumentResponseSerializer (Mattt Thompson) + + * Fix error domain check in `AFErrorOrUnderlyingErrorHasCodeInDomain` +(Mattt Thompson) + + * Fix `UIImageView` category to only `nil` out request operation properties +belonging to completed request (Mattt Thompson) + + * Fix `removesKeysWithNullValues` to respect +`NSJSONReadingMutableContainers` option (Mattt Thompson) + + * Change `removesKeysWithNullValues` property to recursively remove null +values from dictionaries nested in arrays (@jldagon) + + * Change to not override `Content-Type` header field values set by +`HTTPRequestHeaders` property (Aaron Brager, Mattt Thompson) + +## [2.2.2](https://github.com/AFNetworking/AFNetworking/releases/tag/2.2.2) (2014-04-15) + + * Add `removesKeysWithNullValues` property to `AFJSONResponsSerializer` to +automatically remove `NSNull` values in dictionaries serialized from JSON +(Mattt Thompson) + + * Add unit test for checking content type (Diego Torres) + + * Add `boundary` property to `AFHTTPBodyPart -copyWithZone:` + + * Change to accept `id` parameter type in HTTP manager convenience methods +(Mattt Thompson) + + * Change to deprecate `setAuthorizationHeaderFieldWithToken:`, in favor of +users specifying an `Authorization` header field value themselves (Mattt +Thompson) + + * Change to use `long long` type to prevent a difference in stream size +caps on 32-bit and 64-bit architectures (Yung-Luen Lan, Cédric Luthi) + + * Fix calculation of Content-Length in `taskDidSendBodyData` (Christos +Vasilakis) + + * Fix for comparison of image view request operations (Mattt Thompson) + + * Fix for SSL certificate validation to check status codes at runtime (Dave +Anderson) + + * Fix to add missing call to delegate in +`URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:` + + * Fix to call `taskDidComplete` if delegate is missing (Jeff Ward) + + * Fix to implement `respondsToSelector:` for `NSURLSession` delegate +methods to conditionally respond to conditionally respond to optional +selectors if and only if a custom block has been set (Mattt Thompson) + + * Fix to prevent illegal state values from being assigned for +`AFURLConnectionOperation` (Kyle Fuller) + + * Fix to re-establish `AFNetworkingURLSessionTaskDelegate` objects after +restoring from a background configuration (Jeff Ward) + + * Fix to reduce memory footprint by `nil`-ing out request operation +`outputStream` after closing, as well as image view request operation after +setting image (Teun van Run, Mattt Thompson) + + * Remove unnecessary call in class constructor (Bernhard Loibl) + + * Remove unnecessary check for `respondsToSelector:` for `UIScreen scale` +in User-Agent string (Samuel Goodwin) + + * Update App.net certificate and API base URL (Cédric Luthi) + + * Update examples in README (@petard, @orta, Mattt Thompson) + + * Update Travis CI icon to use SVG format (Maximilian Tagher) + +## [2.2.1](https://github.com/AFNetworking/AFNetworking/releases/tag/2.2.1) (2014-03-14) + + * Fix `-Wsign-conversion` warning in AFURLConnectionOperation (Jesse Collis) + + * Fix `-Wshorten-64-to-32` warning (Jesse Collis) + + * Remove unnecessary #imports in `UIImageView` & `UIWebView` categories +(Jesse Collis) + + * Fix call to `CFStringTransform()` by checking return value before setting +as `User-Agent` (Kevin Cassidy Jr) + + * Update `AFJSONResponseSerializer` adding `@autorelease` to relieve memory +pressure (Mattt Thompson, Michal Pietras) + + * Update `AFJSONRequestSerializer` to accept `id` (Daren Desjardins) + + * Fix small documentation bug (@jkoepcke) + + * Fix behavior of SSL pinning. In case of `validatesDomainName == YES`, it +now explicitly uses `SecPolicyCreateSSL`, which also validates the domain +name. Otherwise, `SecPolicyCreateBasicX509` is used. +`AFSSLPinningModeCertificate` now uses `SecTrustSetAnchorCertificates`, which +allows explicit specification of all trusted certificates. For +`AFSSLPinningModePublicKey`, the number of trusted public keys determines if +the server should be trusted. (Oliver Letterer, Eric Allam) + +## [2.2.0](https://github.com/AFNetworking/AFNetworking/releases/tag/2.2.0) (2014-02-25) + + * Add default initializer to make `AFHTTPRequestOperationManager` +consistent with `AFHTTPSessionManager` (Marcelo Fabri) + + * Add documentation about `UIWebView` category and implementing +`UIWebViewDelegate` (Mattt Thompson) + + * Add missing `NSCoding` and `NSCopying` implementations for +`AFJSONRequestSerializer` (Mattt Thompson) + + * Add note about use of `-startMonitoring` in +`AFNetworkReachabilityManager` (Mattt Thompson) + + * Add setter for needsNewBodyStream block (Carmen Cerino) + + * Add support for specifying a response serializer on a per-instance of +`AFURLSessionManagerTaskDelegate` (Blake Watters) + + * Add `AFHTTPRequestSerializer +-requestWithMultipartFormRequest:writingStreamContentsToFile:completionHandler +:` as a workaround for a bug in NSURLSession that removes the Content-Length +header from streamed requests (Mattt Thompson) + + * Add `NSURLRequest` factory properties on `AFHTTPRequestSerializer` (Mattt +Thompson) + + * Add `UIRefreshControl+AFNetworking` (Mattt Thompson) + + * Change example project to enable certificate pinning (JP Simard) + + * Change to allow self-signed certificates (Frederic Jacobs) + + * Change to make `reachabilityManager` property readwrite (Mattt Thompson) + + * Change to sort `NSSet` members during query string parameter +serialization (Mattt Thompson) + + * Change to use case sensitive compare when sorting keys in query string +serialization (Mattt Thompson) + + * Change to use xcpretty instead of xctool for automated testing (Kyle +Fuller, Marin Usalj, Carson McDonald) + + * Change to use `@selector` values as keys for associated objects (Mattt +Thompson) + + * Change `setImageWithURL:placeholder:`, et al. to only set placeholder +image if not `nil` (Alejandro Martinez) + + * Fix auto property synthesis warnings (Oliver Letterer) + + * Fix domain name validation for SSL certificates (Oliver Letterer) + + * Fix issue with session task delegate KVO observation (Kyle Fuller) + + * Fix placement of `baseURL` method declaration (Oliver Letterer) + + * Fix podspec linting error (Ari Braginsky) + + * Fix potential concurrency issues by adding lock around setting +`isFinished` state in `AFURLConnectionOperation` (Mattt Thompson) + + * Fix potential vulnerability caused by hard-coded multipart form data +boundary (Mathias Bynens, Tom Van Goethem, Mattt Thompson) + + * Fix protocol name in #pragma mark declaration (@sevntine) + + * Fix regression causing inflated images to have incorrect orientation +(Mattt Thompson) + + * Fix to `AFURLSessionManager` `NSCoding` implementation, to accommodate +`NSURLSessionConfiguration` no longer conforming to `NSCoding`. + + * Fix Travis CI integration (Kyle Fuller, Marin Usalj, Carson McDonald) + + * Fix various static analyzer warnings (Philippe Casgrain, Jim Young, +Steven Fisher, Mattt Thompson) + + * Fix with download progress calculation of completion units (Kyle Fuller) + + * Fix Xcode 5.1 compiler warnings (Nick Banks) + + * Fix `AFHTTPRequestOperationManager` to default +`shouldUseCredentialStorage` to `YES`, as documented (Mattt Thompson) + + * Remove Unused format property in `AFJSONRequestSerializer` (Mattt +Thompson) + + * Remove unused `acceptablePathExtensions` class method in +`AFJSONRequestSerializer` (Mattt Thompson) + + * Update #ifdef declarations in UIKit categories to be simpler (Mattt +Thompson) + + * Update podspec to includ social_media_url (Kyle Fuller) + + * Update types for 64 bit architecture (Bruno Tortato Furtado, Mattt +Thompson) + +## [2.1.0](https://github.com/AFNetworking/AFNetworking/releases/tag/2.1.0) (2014-01-16) + + * Add CONTRIBUTING (Kyle Fuller) + + * Add domain name verification for SSL certificates (Oliver Letterer) + + * Add leaf certificate checking (Alex Leverington, Carson McDonald, Mattt +Thompson) + + * Add test case for stream failure handling (Kyle Fuller) + + * Add underlying error properties to response serializers to forward errors +to subsequent validation steps (Mattt Thompson) + + * Add `AFImageCache` protocol, to allow for custom image caches to be +specified for `UIImageView` (Mattt Thompson) + + * Add `error` out parameter for request serializer, deprecating existing +request constructor methods (Adam Becevello) + + * Change request serializer protocol to take id type for parameters (Mattt +Thompson) + + * Change to add validation of download task responses (Mattt Thompson) + + * Change to force upload progress, by using original request Content-Length +(Mateusz Malczak) + + * Change to use `NSDictionary` object literals for `NSError` `userInfo` +construction (Mattt Thompson) + + * Fix #pragma declaration to be NSURLConnectionDataDelegate, rather than +NSURLConnectionDelegate (David Paschich) + + * Fix a bug when appending a file part to multipart request from a URL +(Kyle Fuller) + + * Fix analyzer warning about weak receiver being set to nil, capture strong +reference (Stewart Gleadow) + + * Fix appending file part to multipart request to use suggested file name, +rather than temporary one (Kyle Fuller) + + * Fix availability macros for network activity indicator (Mattt Thompson) + + * Fix crash in iOS 6.1 caused by KVO on `isCancelled` property of +`AFURLConnectionOperation` (Sam Page) + + * Fix dead store issues in `AFSecurityPolicy` (Andrew Hershberger) + + * Fix incorrect documentation for `-HTTPRequestOperationWithRequest:...` +(Kyle Fuller) + + * Fix issue in reachability callbacks, where reachability managers created +for a particular domain would initially report no reachability (Mattt +Thompson) + + * Fix logic for handling data task turning into download task (Kyle Fuller) + + * Fix property list response serializer to handle 204 response (Kyle Fuller) + + * Fix README multipart example (Johan Forssell) + + * Fix to add check for non-nil delegate in +`URLSession:didCompleteWithError:` (Kaom Te) + + * Fix to dramatically improve creation of images in +`AFInflatedImageFromResponseWithDataAtScale`, including handling of CMYK, 16 +/ 32 bpc images, and colorspace alpha settings (Robert Ryan) + + * Fix Travis CI integration and unit testing (Kyle Fuller, Carson McDonald) + + * Fix typo in comments (@palringo) + + * Fix UIWebView category to use supplied success callback (Mattt Thompson) + + * Fix various static analyzer warnings (Kyle Fuller, Jesse Collis, Mattt +Thompson) + + * Fix `+batchOfRequestOperations:...` completion block to execute in +`dispatch_async` (Mattt Thompson) + + * Remove synchronous `SCNetworkReachabilityGetFlags` call when initializing +managers, which had the potential to block in certain network conditions +(Yury Korolev, Mattt Thompson) + + * Remove unnecessary check for completionHandler in HTTP manager (Mattt +Thompson) + + * Remove unused conditional clauses (Luka Bratos) + + * Update documentation for `AFCompoundResponseSerializer` (Mattt Thompson) + + * Update httpbin certificates (Carson McDonald) + + * Update notification constant names to be consistent with `NSURLSession` +terminology (Mattt Thompson) + +## [2.0.3](https://github.com/AFNetworking/AFNetworking/releases/tag/2.0.3) (2013-11-18) + + * Fix a bug where `AFURLConnectionOperation -pause` did not correctly reset +the state of `AFURLConnectionOperation`, causing the Network Thread to enter +an infinite loop (Erik Chen) + + * Fix a bug where `AFURLConnectionOperation -cancel` does not set the +appropriate error on the `NSOperation` (Erik Chen) + + * Fix to post `AFNetworkingTaskDidFinishNotification` only on main queue +(Jakub Hladik) + + * Fix issue where the query string serialization block was not used (Kevin +Harwood) + + * Fix project file and repository directory items (Andrew Newdigate) + + * Fix `NSURLSession` subspec (Mattt Thompson) + + * Fix to session task delegate KVO by moving observer removal to +`-didCompleteWithError:` (Mattt Thompson) + + * Add AFNetworking 1.x behavior for image construction in inflation to +ensure correct orientation (Mattt Thompson) + + * Add `NSParameterAssert` for internal task constructors in order to catch +invalid constructions early (Mattt Thompson) + + * Update replacing `NSParameterAssert` with early `nil` return if session +was unable to create a task (Mattt Thompson) + + * Update `AFHTTPRequestOperationManager` and `AFHTTPSessionManager` to use +relative `self class` to create class constructor instances (Bogdan +Poplauschi) + + * Update to break out of loop if output stream does not have space to write +bytes (Mattt Thompson) + + * Update documentation and README with various fixes (Max Goedjen, Mattt +Thompson) + + * Remove unnecessary willChangeValueForKey and didChangeValueForKey method +calls (Mindaugas Vaičiūnas) + + * Remove deletion of all task delegates in +`URLSessionDidFinishEventsForBackgroundURLSession:` (Jeremy Mailen) + + * Remove empty, unused `else` branch (Luka Bratos) + +## [2.0.2](https://github.com/AFNetworking/AFNetworking/releases/tag/2.0.2) (2013-10-29) + + * Add `UIWebView + -loadRequest:MIMEType:textEncodingName:progress:success:failure:` (Mattt + Thompson) + + * Fix iOS 6 compatibility in `AFHTTPSessionManager` & + `UIProgressView+AFNetworking` (Olivier Halligon, Mattt Thompson) + + * Fix issue writing partial data to output stream (Kyle Fuller) + + * Fix behavior for `nil` response in request operations (Marcelo Fabri) + + * Fix implementation of + batchOfRequestOperations:progressBlock:completionBlock: for nil when passed + empty operations parameter (Mattt Thompson) + + * Update `AFHTTPSessionManager` to allow `-init` and `initWithConfig:` to + work (Ben Scheirman) + + * Update `AFRequestOperation` to default to `AFHTTPResponseSerializer` (Jiri + Techet) + + * Update `AFHTTPResponseSerializer` to remove check for nonzero responseData + length (Mattt Thompson) + + * Update `NSCoding` methods to use NSStringFromSelector(@selector()) pattern + instead of `NSString` literals (Mattt Thompson) + + * Update multipart form stream to set Content-Length after setting request + stream (Mattt Thompson) + + * Update documentation with outdated references to `AFHTTPSerializer` (Bruno + Koga) + + * Update documentation and README with various fixes (Jon Chambers, Mattt + Thompson) + + * Update files to remove executable privilege (Kyle Fuller) + +## 2.0.1 (2013-10-10) + + * Fix iOS 6 compatibility (Matt Baker, Mattt Thompson) + + * Fix example applications (Sam Soffes, Kyle Fuller) + + * Fix usage of `NSSearchPathForDirectoriesInDomains` in README (Leo Lou) + + * Fix names of exposed private methods `downloadProgress` and +`uploadProgress` (Hermes Pique) + + * Fix initial upload/download task progress updates (Vlas Voloshin) + + * Fix podspec to include `AFNetworking.h` `#import` (@haikusw) + + * Fix request serializers to not override existing header field values with +defaults (Mattt Thompson) + + * Fix unused format string placeholder (Thorsten Lockert) + + * Fix `AFHTTPRequestOperation -initWithCoder:` to call `super` (Josh Avant) + + * Fix `UIProgressView` selector name (Allen Tu) + + * Fix `UIButton` response serializer (Sam Grossberg) + + * Fix `setPinnedCertificates:` and pinned public keys (Kyle Fuller) + + * Fix timing of batched operation completion block (Denys Telezhkin) + + * Fix `GCC_WARN_ABOUT_MISSING_NEWLINE` compiler warning (Chuck Shnider) + + * Fix a format string missing argument issue in tests (Kyle Fuller) + + * Fix location of certificate chain bundle location (Kyle Fuller) + + * Fix memory leaks in AFSecurityPolicyTests (Kyle Fuller) + + * Fix potential concurrency issues in `AFURLSessionManager` by adding locks +around access to mutiple delegates dictionary (Mattt Thompson) + + * Fix unused variable compiler warnings by wrapping `OSStatus` and +`NSCAssert` with NS_BLOCK_ASSERTIONS macro (Mattt Thompson) + + * Fix compound serializer error handling (Mattt Thompson) + + * Fix string encoding for responseString (Juan Enrique) + + * Fix `UIImageView -setBackgroundImageWithRequest:` (Taichiro Yoshida) + + * Fix regressions nested multipart parameters (Mattt Thompson) + + * Add `responseObject` property to `AFHTTPRequestOperation` (Mattt Thompson) + + * Add support for automatic network reachability monitoring for request +operation and session managers (Mattt Thompson) + + * Update documentation and README with various corrections and fixes +(@haikusw, Chris Hellmuth, Dave Caunt, Mattt Thompson) + + * Update default User-Agent such that only ASCII character set is used +(Maximillian Dornseif) + + * Update SSL pinning mode to have default pinned certificates by default +(Kevin Harwood) + + * Update `AFSecurityPolicy` to use default authentication handling unless a +credential exists for the server trust (Mattt Thompson) + + * Update Prefix.pch (Steven Fisher) + + * Update minimum iOS test target to iOS 6 + + * Remove unused protection space block type (Kyle Fuller) + + * Remove unnecessary Podfile.lock (Kyle Fuller) + +## [2.0.0](https://github.com/AFNetworking/AFNetworking/releases/tag/2.0.0) (2013-09-27) + +* Initial 2.0.0 Release + +==================== +#AFNetworking 1.0 Change Log +-- + +## [1.3.4](https://github.com/AFNetworking/AFNetworking/releases/tag/1.3.4) (2014-04-15) + + * Fix `AFHTTPMultipartBodyStream` to randomly generate form boundary, to +prevent attack based on a known value (Mathias Bynens, Tom Van Goethem, Mattt +Thompson) + + * Fix potential non-terminating loop in `connection:didReceiveData:` (Mattt +Thompson) + + * Fix SSL certificate validation to provide a human readable Warning when +SSL Pinning fails (Maximillian Dornseif) + + * Fix SSL certificate validation to assert that no impossible pinning +configuration exists (Maximillian Dornseif) + + * Fix to check `CFStringTransform()` call for success before using result +(Kevin Cassidy Jr) + + * Fix to prevent unused assertion results with macros (Indragie Karunaratne) + + * Fix to call call `SecTrustEvaluate` before calling +`SecTrustGetCertificateCount` in SSL certificate validation (Josh Chung) + + * Fix to add explicit cast to `NSUInteger` in format string (Alexander +Kempgen) + + * Remove unused variable `kAFStreamToStreamBufferSize` (Alexander Kempgen) + +## [1.3.3](https://github.com/AFNetworking/AFNetworking/releases/tag/1.3.3) (2013-09-25) + + * Add stream error handling to `AFMultipartBodyStream` (Nicolas Bachschmidt, +Mattt Thompson) + + * Add stream error handling to `AFURLConnectionOperation +-connection:didReceiveData:` (Ian Duggan, Mattt Thompson) + + * Fix parameter query string encoding of square brackets according to RFC +3986 (Kra Larivain) + + * Fix AFHTTPBodyPart determination of end of input stream data (Brian Croom) + + * Fix unit test timeouts (Carson McDonald) + + * Fix truncated `User-Agent` header field when app contained non-ASCII +characters (Diego Torres) + + * Fix outdated link in documentation (Jonas Schmid) + + * Fix `AFHTTPRequestOperation` `HTTPError` property to be thread-safe +(Oliver Letterer, Mattt Thompson) + + * Fix API compatibility with iOS 5 (Blake Watters, Mattt Thompson) + + * Fix potential race condition in `AFURLConnectionOperation +-cancelConnection` (@mm-jkolb, Mattt Thompson) + + * Remove implementation of `connection:needNewBodyStream:` delegate method +in `AFURLConnectionOperation`, which fixes stream errors on authentication +challenges (Mattt Thompson) + + * Fix calculation of network reachability from flags (Tracy Pesin, Mattt +Thompson) + + * Update AFHTTPClient documentation to clarify scope of `parameterEncoding` +property (Thomas Catterall) + + * Update `UIImageView` category to allow for nested calls to +`setImageWithURLRequest:` (Philippe Converset) + + * Change `UIImageView` category to accept invalid SSL certificates when +`_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is defined (Flávio Caetano) + + * Change to replace #pragma clang with cast (Cédric Luthi) + +## [1.3.2](https://github.com/AFNetworking/AFNetworking/releases/tag/1.3.2) (2013-08-08) + + * Add return status checks when building list of pinned public keys (Sylvain +Guillope) + + * Add return status checks when handling connection authentication challenges +(Sylvain Guillope) + + * Add tests around `AFHTTPClient initWithBaseURL:` (Kyle Fuller) + + * Change to remove all `_AFNETWORKING_PIN_SSL_CERTIFICATES_` conditional +compilation (Dustin Barker) + + * Change to allow fallback to generic image loading when PNG/JPEG data +provider methods fail (Darryl H. Thomas) + + * Change to only set placeholder image if not `nil` (Mattt Thompson) + + * Change to use `response.MIMEType` rather than (potentially nonexistent) +Content-Type headers to determine image data provider (Mattt Thompson) + + * Fix image request test endpoint (Carson McDonald) + + * Fix compiler warning caused by `size_t` value defaulted to `NULL` (Darryl H. +Thomas) + + * Fix mutable headers property in `AFHTTPClient -copyWithZone:` (Oliver +Letterer) + + * Fix documentation and asset references in README (Romain Pouclet, Peter +Goldsmith) + + * Fix bug in examples always using `AFSSLPinningModeNone` (Dustin Barker) + + * Fix execution of tests under Travis (Blake Watters) + + * Fix static analyzer warnings about CFRelease calls to NULL pointer (Mattt +Thompson) + + * Change to return early in `AFGetMediaTypeAndSubtypeWithString` if string is +`nil` (Mattt Thompson) + + * Change to opimize network thread creation (Mattt Thompson) + +## [1.3.1](https://github.com/AFNetworking/AFNetworking/releases/tag/1.3.1) (2013-06-18) + + * Add `automaticallyInflatesResponseImage` property to +`AFImageRequestOperation`, which when enabled, offers significant performance +improvements for drawing images loaded through `UIImageView+AFNetworking` by +inflating compressed image data in the background (Mattt Thompson, Peter +Steinberger) + + * Add `NSParameterAssert` check for `nil` `urlRequest` parameter in +`AFURLConnectionOperation` initializer (Kyle Fuller) + + * Fix reachability to detect the case where a connection is required but can +be automatically established (Joshua Vickery) + + * Fix to Test target Podfile (Kyle Fuller) + +## [1.3.0](https://github.com/AFNetworking/AFNetworking/releases/tag/1.3.0) (2013-06-01) + + * Change in `AFURLConnectionOperation` `NSURLConnection` authentication +delegate methods and associated block setters. If +`_AFNETWORKING_PIN_SSL_CERTIFICATES_` is defined, +`-setWillSendRequestForAuthenticationChallengeBlock:` will be available, and +`-connection:willSendRequestForAuthenticationChallenge:` will be implemented. +Otherwise, `-setAuthenticationAgainstProtectionSpaceBlock:` & +`-setAuthenticationChallengeBlock:` will be available, and +`-connection:canAuthenticateAgainstProtectionSpace:` & +`-connection:didReceiveAuthenticationChallenge:` will be implemented instead +(Oliver Letterer) + + * Change in AFNetworking podspec to include Security framework (Kevin Harwood, +Oliver Letterer, Sam Soffes) + + * Change in AFHTTPClient to @throw exception when non-designated intializer is +used (Kyle Fuller) + + * Change in behavior of connection:didReceiveAuthenticationChallenge: to not +use URL-encoded credentials, which should already have been applied (@xjdrew) + + * Change to set AFJSONRequestOperation error when unable to decode response +string (Chris Pickslay, Geoff Nix) + + * Change AFURLConnectionOperation to lazily initialize outputStream property +(@fumoboy007) + + * Change instances of (CFStringRef)NSRunLoopCommonModes to +kCFRunLoopCommonModes + + * Change #warning to #pragma message for dynamic framework linking warnings +(@michael_r_may) + + * Add unit testing and continuous integration system (Blake Watters, Oliver +Letterer, Kevin Harwood, Cédric Luthi, Adam Fraser, Carson McDonald, Mattt +Thompson) + + * Fix multipart input stream implementation (Blake Watters, OliverLetterer, +Aleksey Kononov, @mattyohe, @mythodeia, @JD-) + + * Fix implementation of authentication delegate methods (Oliver Letterer, +Kevin Harwood) + + * Fix implementation of AFSSLPinningModePublicKey on Mac OS X (Oliver Letterer) + + * Fix error caused by loading file:// requests with AFHTTPRequestOperation +subclasses (Dave Anderson, Oliver Letterer) + + * Fix threading-related crash in AFNetworkActivityIndicatorManager (Dave Keck) + + * Fix to suppress GNU expression and enum assignment warnings from Clang +(Henrik Hartz) + + * Fix leak caused by CFStringConvertEncodingToIANACharSetName in AFHTTPClient +-requestWithMethod:path:parameters: (Daniel Demiss) + + * Fix missing __bridge casts in AFHTTPClient (@apouche, Mattt Thompson) + + * Fix Objective-C++ compatibility (Audun Holm Ellertsen) + + * Fix to not escape tildes (@joein3d) + + * Fix warnings caused by unsynthesized properties (Jeff Hunter) + + * Fix to network reachability calls to provide correct status on +initialization (@djmadcat, Mattt Thompson) + + * Fix to suppress warnings about implicit signedness conversion (Matt Rubin) + + * Fix AFJSONRequestOperation -responseJSON failing cases (Andrew Vyazovoy, +Mattt Thompson) + + * Fix use of object subscripting to avoid incompatibility with iOS < 6 and OS +X < 10.8 (Paul Melnikow) + + * Various fixes to reverted multipart stream provider implementation (Yaron +Inger, Alex Burgel) + +## [1.2.1](https://github.com/AFNetworking/AFNetworking/releases/tag/1.2.1) (2013-04-18) + + * Add `allowsInvalidSSLCertificate` property to `AFURLConnectionOperation` and +`AFHTTPClient`, replacing `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` macro +(Kevin Harwood) + + * Add SSL pinning mode to example project (Kevin Harwood) + + * Add name to AFNetworking network thread (Peter Steinberger) + + * Change pinned certificates to trust all derived certificates (Oliver +Letterer) + + * Fix documentation about SSL pinning (Kevin Harwood, Mattt Thompson) + + * Fix certain enumerated loops to use fast enumeration, resulting in better +performance (Oliver Letterer) + + * Fix macro to work correctly under Mac OS X 10.7 and iOS 4 SDK (Paul Melnikow) + + * Fix documentation, removing unsupported `@discussion` tags (Michele Titolo) + + * Fix `SecTrustCreateWithCertificates` expecting an array as first argument +(Oliver Letterer) + + * Fix to use `errSecSuccess` instead of `noErr` for Security frameworks +OSStatus (Oliver Letterer) + + * Fix `AFImageRequestOperation` to use `[self alloc]` instead of explicit +class, which allows for subclassing (James Clarke) + + * Fix for `numberOfFinishedOperations` calculations (Rune Madsen) + + * Fix calculation of data length in `-connection:didReceiveData:` +(Jean-Francois Morin) + + * Fix to encode JSON only with UTF-8, following recommendation of +`NSJSONSerialiation` (Sebastian Utz) + +## [1.2.0](https://github.com/AFNetworking/AFNetworking/releases/tag/1.2.0) (2013-03-24) + + * Add `SSLPinningMode` property to `AFHTTPClient` (Oliver Letterer, Kevin +Harwood, Adam Becevello, Dustin Barker, Mattt Thompson) + + * Add single quote ("'"), comma (","), and asterix ("*") to escaped URL +encoding characters (Eric Florenzano, Marc Nijdam, Garrett Murray) + + * Add `credential` property to `AFURLConnectionOperation` (Mattt Thompson) + + * Add `-setDefaultCredential:` to `AFHTTPClient` + + * Add `shouldUseCredentialStorage` property to `AFURLConnectionOperation` +(Mattt Thompson) + + * Add support for repeated key value pairs in `AFHTTPClient` URL query string +(Nick Dawson) + + * Add `AFMultipartFormData - +appendPartWithFileURL:name:fileName:mimeType:error` (Daniel Rodríguez Troitiño) + + * Add `AFMultipartFormData - +appendPartWithInputStream:name:fileName:mimeType:` (@joein3d) + + * Change SSL pinning to be runtime property on `AFURLConnectionOperation` +rather than defined by macro (Oliver Letterer) + + * Change `AFMultipartBodyStream` to `AFMultipartBodyStreamProvider`, vending +one side of a bound CFStream pair rather than subclassing `NSInputStream` (Mike +Ash) + + * Change default `Accept-Language` header in `AFHTTPClient` (@therigu, Mattt +Thompson) + + * Change `AFHTTPClient` operation cancellation to be based on request URL path +rather than absolute URL string (Mattt Thompson) + + * Change request operation subclass processing queues to use +`DISPATCH_QUEUE_CONCURRENT` (Mattt Thompson) + + * Change `UIImageView+AFNetworking` to resolve asymmetry in cached image case +between success block provided and not provided (@Eveets, Mattt Thompson) + + * Change `UIImageView+AFNetworking` to compare `NSURLRequest` instead of +`NSURL` to determine if previous request was equivalent (Cédric Luthi) + + * Change `UIImageView+AFNetworking` to only set image if non-`nil` (Sean +Kovacs) + + * Change indentation settings to four spaces at the project level (Cédric +Luthi) + + * Change `AFNetworkActivityIndicatorManager` to only update if requests have a +non-`nil` URL (Cédric Luthi) + + * Change `UIImageView+AFNetworking` to not do `setHTTPShouldHandleCookies` +(Konstantinos Vaggelakos) + + * Fix request stream exhaustion error on authentication challenges (Alex +Burgel) + + * Fix implementation to use `NSURL` methods instead of `CFURL` functions where +applicable (Cédric Luthi) + + * Fix race condition in `UIImageView+AFNetworking` (Peyman) + + * Fix `responseJSON`, `responseString`, and `responseStringEncoding` to be +threadsafe (Jon Parise, Mattt Thompson) + + * Fix `AFContentTypeForPathExtension` to ensure non-`NULL` content return +value (Zach Waugh) + + * Fix documentation for `appendPartWithFileURL:name:error:` + (Daniel Rodríguez Troitiño) + + * Fix request operation subclass processing queues to initialize with +`dispatch_once` (Sasmito Adibowo) + + * Fix posting of `AFNetworkingOperationDidStartNotification` and +`AFNetworkingOperationDidFinishNotification` to avoid crashes when logging in +response to notifications (Blake Watters) + + * Fix ordering of registered operation consultation in `AFHTTPClient` (Joel +Parsons) + + * Fix warning: multiple methods named 'postNotificationName:object:' found +[-Wstrict-selector-match] (Oliver Jones) + + * Fix warning: multiple methods named 'objectForKey:' found +[-Wstrict-selector-match] (Oliver Jones) + + * Fix warning: weak receiver may be unpredictably set to nil +[-Wreceiver-is-weak] (Oliver Jones) + + * Fix missing #pragma clang diagnostic pop (Steven Fisher) + +## [1.1.0](https://github.com/AFNetworking/AFNetworking/releases/tag/1.1.0) (2012-12-27) + + * Add optional SSL certificate pinning with `#define +_AFNETWORKING_PIN_SSL_CERTIFICATES_` (Dustin Barker) + + * Add `responseStringEncoding` property to `AFURLConnectionOperation` (Mattt +Thompson) + + * Add `userInfo` property to `AFURLConnectionOperation` (Mattt Thompson, +Steven Fisher) + + * Change behavior to cause a failure when an operation is cancelled (Daniel +Tull) + + * Change return type of class constructors to `instancetype` (@guykogus) + + * Change notifications to always being posted on an asynchronously-dispatched +block run on the main queue (Evadne Wu, Mattt Thompson) + + * Change from NSLocalizedString to NSLocalizedStringFromTable with +AFNetworking.strings table for localized strings (Cédric Luthi) + + * Change `-appendPartWithHeaders:body:` to add assertion handler for existence +of body data parameter (Jonathan Beilin) + + * Change `AFHTTPRequestOperation -responseString` to follow guidelines from +RFC 2616 regarding the use of string encoding when none is specified in the +response (Jorge Bernal) + + * Change AFHTTPClient parameter serialization dictionary keys with +`caseInsensitiveCompare:` to ensure + deterministic ordering of query string parameters, which may otherwise + cause ambiguous representations of nested parameters (James Coleman, + Mattt Thompson) + + * Fix -Wstrict-selector-match warnings raised by Xcode 4.6DP3 (Jesse Collis, +Cédric Luthi) + + * Fix NSJSONSerialization crash with Unicode character escapes in JSON +response (Mathijs Kadijk) + + * Fix issue with early return in -startMonitoringNetworkReachability if +network reachability object could not be created (i.e. invalid hostnames) +(Basil Shkara) + + * Fix retain cycles in AFImageRequestOperation.m and AFHTTPClient.m caused by +strong references within blocks (Nick Forge) + + * Fix issue caused by Rails behavior of returning a single space in head :ok +responses, which is interpreted as invalid (Sebastian Ludwig) + + * Fix issue in streaming multipart upload, where final encapsulation boundary +would not be appended if it was larger than the available buffer, causing a +potential timeout (Tomohisa Takaoka, David Kasper) + + * Fix memory leak of network reachability callback block (Mattt Thompson) + + * Fix `-initWithCoder:` for `AFURLConnectionOperation` and `AFHTTPClient` to +cast scalar types (Mattt Thompson) + + * Fix bug in `-enqueueBatchOfHTTPRequestOperations:...` to by using +`addOperations:waitUntilFinished:` instead of adding each operation +individually. (Mattt Thompson) + + * Change `#warning` messages of checks for `CoreServices` and +`MobileCoreServices` to message according to the build target platform (Mattt +Thompson) + + * Change `AFQueryStringFromParametersWithEncoding` to create keys string +representations using the description method as specified in documentation +(Cédric Luthi) + + * Fix __unused keywords for better Xcode indexing (Christian Rasmussen) + + * Fix warning: unused parameter 'x' [-Werror,-Wunused-parameter] (Oliver Jones) + + * Fix warning: property is assumed atomic by default +[-Werror,-Wimplicit-atomic-properties] (Oliver Jones) + + * Fix warning: weak receiver may be unpredictably null in ARC mode +[-Werror,-Wreceiver-is-weak] (Oliver Jones) + + * Fix warning: multiple methods named 'selector' found +[-Werror,-Wstrict-selector-match] (Oliver Jones) + + * Fix warning: 'macro' is not defined, evaluates to 0 (Oliver Jones) + + * Fix warning: atomic by default property 'X' has a user (Oliver Jones)defined +getter (property should be marked 'atomic' if this is intended) [-Werror, +-Wcustom-atomic-properties] (Oliver Jones) + + * Fix warning: 'response' was marked unused but was used +[-Werror,-Wused-but-marked-unused] (Oliver Jones) + + * Fix warning: enumeration value 'AFFinalBoundaryPhase' not explicitly handled +in switch [-Werror,-Wswitch-enum] (Oliver Jones) + +## [1.0.1](https://github.com/AFNetworking/AFNetworking/releases/tag/1.0.1) / 2012-11-01 + + * Fix error in multipart upload streaming, where byte range at boundaries +was not correctly calculated (Stan Chang Khin Boon) + + * If a success block is specified to `UIImageView -setImageWithURLRequest: +placeholderImage:success:failure`:, it is now the responsibility of the +block to set the image of the image view (Mattt Thompson) + + * Add `JSONReadingOptions` property to `AFJSONRequestOperation` (Jeremy + Foo, Mattt Thompson) + + * Using __weak self / __strong self pattern to break retain cycles in + background task and network reachability blocks (Jerry Beers, Dan Weeks) + + * Fix parameter encoding to leave period (`.`) unescaped (Diego Torres) + + * Fixing last file component in multipart form part creation (Sylver + Bruneau) + + * Remove executable permission on AFHTTPClient source files (Andrew + Sardone) + + * Fix warning (error with -Werror) on implicit 64 to 32 conversion (Dan + Weeks) + + * Add GitHub's .gitignore file (Nate Stedman) + + * Updates to README (@ckmcc) + +## [1.0](https://github.com/AFNetworking/AFNetworking/releases/tag/1.0) / 2012-10-15 + + * AFNetworking now requires iOS 5 / Mac OSX 10.7 or higher (Mattt Thompson) + + * AFNetworking now uses Automatic Reference Counting (ARC) (Mattt Thompson) + + * AFNetworking raises compiler warnings for missing features when +SystemConfiguration or CoreServices / MobileCoreServices frameworks are not +included in the project and imported in the precompiled headers (Mattt +Thompson) + + * AFNetworking now raises compiler error when not compiled with ARC (Steven +Fisher) + + * Add `NSCoding` and `NSCopying` protocol conformance to +`AFURLConnectionOperation` and `AFHTTPClient` (Mattt Thompson) + + * Add substantial improvements HTTP multipart streaming support, having +files streamed directly from disk and read sequentially from a custom input +stream (Max Lansing, Stan Chang Khin Boon, Mattt Thompson) + + * Add `AFMultipartFormData -throttleBandwidthWithPacketSize:delay:` as +workaround to issues when uploading over 3G (Mattt Thompson) + + * Add request and response to `userInfo` of errors returned from failing +`AFHTTPRequestOperation` (Mattt Thompson) + + * Add `userInfo` dictionary with current status in reachability changes +(Mattt Thompson) + + * Add `Accept` header for image requests in `UIImageView` category (Bratley +Lower) + + * Add explicit declaration of `NSURLConnection` delegate methods so that +they can be overridden in subclasses (Mattt Thompson, Evan Grim) + + * Add parameter validation to match conditions specified in documentation +(Jason Brennan, Mattt Thompson) + + * Add import to `UIKit` to avoid build errors from `UIDevice` references in +`User-Agent` default header (Blake Watters) + + * Remove `AFJSONUtilities` in favor of `NSJSONSerialization` (Mattt Thompson) + + * Remove `extern` declaration of `AFURLEncodedStringFromStringWithEncoding` +function (`CFURLCreateStringByAddingPercentEscapes` should be used instead) +(Mattt Thompson) + + * Remove `setHTTPShouldHandleCookies:NO` from `AFHTTPClient` (@phamsonha, +Mattt Thompson) + + * Remove `dispatch_retain` / `dispatch_release` with ARC in iOS 6 (Benoit +Bourdon) + + * Fix threading issue with `AFNetworkActivityIndicatorManager` (Eric Patey) + + * Fix issue where `AFNetworkActivityIndicatorManager` count could become +negative (@ap4y) + + * Fix properties to explicitly set options to suppress warnings (Wen-Hao +Lue, Mattt Thompson) + + * Fix compiler warning caused by mismatched types in upload / download +progress blocks (Gareth du Plooy, tomas.a) + + * Fix weak / strong variable relationships in `completionBlock` (Peter +Steinberger) + + * Fix string formatting syntax warnings caused by type mismatch (David +Keegan, Steven Fisher, George Cox) + + * Fix minor potential security vulnerability by explicitly using string +format in NSError localizedDescription value in userInfo (Steven Fisher) + + * Fix `AFURLConnectionOperation -pause` by adding state checks to prevent +likely memory issues when resuming (Mattt Thompson) + + * Fix warning caused by miscast of type when +`CLANG_WARN_IMPLICIT_SIGN_CONVERSION` is set (Steven Fisher) + + * Fix incomplete implementation warning in example code (Steven Fisher) + + * Fix warning caused by using `==` comparator on floats (Steven Fisher) + + * Fix iOS 4 bug where file URLs return `NSURLResponse` rather than +`NSHTTPURLResponse` objects (Leo Lobato) + + * Fix calculation of finished operations in batch operation progress +callback (Mattt Thompson) + + * Fix documentation typos (Steven Fisher, Matthias Wessendorf, +jorge@miv.uk.com) + + * Fix `hasAcceptableStatusCode` to return true after a network failure (Tony +Million) + + * Fix warning about missing prototype for private static method (Stephan +Diederich) + + * Fix issue where `nil` content type resulted in unacceptable content type +(Mattt Thompson) + + * Fix bug related to setup and scheduling of output stream (Stephen Tramer) + + * Fix AFContentTypesFromHTTPHeader to correctly handle comma-delimited +content types (Peyman, Mattt Thompson, @jsm174) + + * Fix crash caused by `_networkReachability` not being set to `NULL` after +releasing (Blake Watters) + + * Fix Podspec to correctly import required headers and use ARC (Eloy Durán, +Blake Watters) + + * Fix query string parameter escaping to leave square brackets unescaped +(Mattt Thompson) + + * Fix query string parameter encoding of `NSNull` values (Daniel Rinser) + + * Fix error caused by referencing `__IPHONE_OS_VERSION_MIN_REQUIRED` without +importing `Availability.h` (Blake Watters) + + * Update example to use App.net API, as Twitter shut off its unauthorized +access to the public timeline (Mattt Thompson) + + * Update `AFURLConnectionOperation` to replace `NSAutoReleasePool` with +`@autoreleasepool` (Mattt Thompson) + + * Update `AFHTTPClient` operation queue to specify +`NSOperationQueueDefaultMaxConcurrentOperationCount` rather than +previously-defined constant (Mattt Thompson) + + * Update `AFHTTPClient -initWithBaseURL` to automatically append trailing +slash, so as to fix common issue where default path is not respected without +trailing slash (Steven Fisher) + + * Update default `AFHTTPClient` `User-Agent` header strings (Mattt Thompson, +Steven Fisher) + + * Update icons for iOS example application (Mattt Thompson) + + * Update `numberOfCompletedOperations` variable in progress block to be +renamed to `numberOfFinishedOperations` (Mattt Thompson) + + +## 0.10.0 / 2012-06-26 + + * Add Twitter Mac Example application (Mattt Thompson) + + * Add note in README about how to set `-fno-objc-arc` flag for multiple files + at once (Pål Brattberg) + + * Add note in README about 64-bit architecture requirement (@rmuginov, Mattt + Thompson) + + * Add note in `AFNetworkActivityIndicatorManager` about not having to manually + manage animation state (Mattt Thompson) + + * Add missing block parameter name for `imageProcessingBlock` (Francois + Lambert) + + * Add NextiveJson to list of supported JSON libraries (Mattt Thompson) + + * Restore iOS 4.0 compatibility with `addAcceptableStatusCodes:` and + `addAcceptableContentTypes:` (Zachary Waldowski) + + * Update `AFHTTPClient` to use HTTP pipelining for `GET` and `HEAD` requests by + default (Mattt Thompson) + + * Remove @private ivar declaration in headers (Peter Steinberger, Mattt + Thompson) + + * Fix potential premature deallocation of _skippedCharacterSet (Tom Wanielista, + Mattt Thompson) + + * Fix potential issue in `setOutputStream` by closing any existing + `outputStream` (Mattt Thompson) + + * Fix filename in AFHTTPClient header (Steven Fisher) + + * Fix documentation for UIImageView+AFNetworking (Mattt Thompson) + + * Fix HTTP multipart form format, which caused issues with Tornado web server + (Matt Chen) + + * Fix `AFHTTPClient` to not append empty data into multipart form data (Jon + Parise) + + * Fix URL encoding normalization to not conditionally escape percent-encoded + strings (João Prado Maia, Kendall Helmstetter Gelner, @cysp, Mattt Thompson) + + * Fix `AFHTTPClient` documentation reference of + `HTTPRequestOperationWithRequest:success:failure` (Shane Vitarana) + + * Add `AFURLRequestOperation -setRedirectResponseBlock:` (Kevin Harwood) + + * Fix `AFURLConnectionOperation` compilation error by conditionally importing + UIKit framework (Steven Fisher) + + * Fix issue where image processing block is not called correctly with success + block in `AFImageRequestOperation` (Sergey Gavrilyuk) + + * Fix leaked dispatch group in batch operations (@andyegorov, Mattt Thompson) + + * Fix support for non-LLVM compilers in `AFNetworkActivityIndicatorManager` + (Abraham Vegh, Bill Williams, Mattt Thompson) + + * Fix AFHTTPClient to not add unnecessary data when constructing multipart form + request with nil parameters (Taeho Kim) + +## 1.0RC1 / 2012-04-25 + + * Add `AFHTTPRequestOperation +addAcceptableStatusCodes / ++addAcceptableContentTypes` to dynamically add acceptable status codes and +content types on the class level (Mattt Thompson) + + * Add support for compound and complex `Accept` headers that include multiple +content types and / or specify a particular character encoding (Mattt Thompson) + + * Add `AFURLConnectionOperation +-setShouldExecuteAsBackgroundTaskWithExpirationHandler:` to have operations +finish once an app becomes inactive (Mattt Thompson) + + * Add support for pausing / resuming request operations (Peter Steinberger, +Mattt Thompson) + + * Improve network reachability functionality in `AFHTTPClient`, including a +distinction between WWan and WiFi reachability (Kevin Harwood, Mattt Thompson) + + +## 0.9.2 / 2012-04-25 + + * Add thread safety to `AFNetworkActivityIndicator` (Peter Steinberger, Mattt +Thompson) + + * Document requirement of available JSON libraries for decoding responses in +`AFJSONRequestOperation` and parameter encoding in `AFHTTPClient` (Mattt +Thompson) + + * Fix `AFHTTPClient` parameter encoding (Mattt Thompson) + + * Fix `AFJSONEncode` and `AFJSONDecode` to use `SBJsonWriter` and +`SBJsonParser` instead of `NSObject+SBJson` (Oliver Eikemeier) + + * Fix bug where `AFJSONDecode` does not return errors (Alex Michaud) + + * Fix compiler warning for undeclared +`AFQueryStringComponentFromKeyAndValueWithEncoding` function (Mattt Thompson) + + * Fix cache policy for URL requests (Peter Steinberger) + + * Fix race condition bug in `UIImageView+AFNetworking` caused by incorrectly +nil-ing request operations (John Wu) + + * Fix reload button in Twitter example (Peter Steinberger) + + * Improve batched operation by deferring execution of batch completion block +until all component request completion blocks have finished (Patrick Hernandez, +Kevin Harwood, Mattt Thompson) + + * Improve performance of image request decoding by dispatching to background + queue (Mattt Thompson) + + * Revert `AFImageCache` to cache image objects rather than `NSPurgeableData` +(Tony Million, Peter Steinberger, Mattt Thompson) + + * Remove unnecessary KVO `willChangeValueForKey:` / `didChangeValueForKey:` +calls (Peter Steinberger) + + * Remove unnecessary @private ivar declarations in headers (Peter Steinberger, +Mattt Thompson) + + * Remove @try-@catch block wrapping network thread entry point (Charles T. Ahn) + + +## 0.9.1 / 2012-03-19 + + * Create Twitter example application (Mattt Thompson) + + * Add support for nested array and dictionary parameters for query string and +form-encoded requests (Mathieu Hausherr, Josh Chung, Mattt Thompson) + + * Add `AFURLConnectionOperation -setCacheResponseBlock:`, which allows the +behavior of the `NSURLConnectionDelegate` method +`-connection:willCacheResponse:` to be overridden without subclassing (Mattt +Thompson) + + * Add `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` macros for +NSURLConnection authentication delegate methods (Mattt Thompson) + + * Add properties for custom success / failure callback queues (Peter +Steinberger) + + * Add notifications for network reachability changes to `AFHTTPClient` (Mattt +Thompson) + + * Add `AFHTTPClient -patchPath:` convenience method (Mattt Thompson) + + * Add support for NextiveJson (Adrian Kosmaczewski) + + * Improve network reachability checks (C. Bess) + + * Improve NSIndexSet formatting in error strings (Jon Parise) + + * Document crashing behavior in iOS 4 loading a file:// URL (Mattt Thompson) + + * Fix crash caused by `AFHTTPClient -cancelAllHTTPOperationsWithMethod:` not +checking operation to be instance of `AFHTTPRequestOperation` (Mattt Thompson) + + * Fix crash caused by passing `nil` URL in requests (Sam Soffes) + + * Fix errors caused by connection property not being nil'd out after an +operation finishes (Kevin Harwood, @zdzisiekpu) + + * Fix crash caused by passing `NULL` error pointer when setting `NSInvocation` +in `AFJSONEncode` and `AFJSONDecode` (Tyler Stromberg) + + * Fix batch operation completion block returning on background thread (Patrick +Hernandez) + + * Fix documentation for UIImageView+AFNetworking (Dominic Dagradi) + + * Fix race condition caused by `AFURLConnectionOperation` being cancelled on +main thread, rather than network thread (Erik Olsson) + + * Fix `AFURLEncodedStringFromStringWithEncoding` to correctly handle cases +where % is used as a literal rather than as part of a percent escape code +(Mattt Thompson) + + * Fix missing comma in `+defaultAcceptableContentTypes` for +`AFImageRequestOperation` (Michael Schneider) + + +## 0.9.0 / 2012-01-23 + + * Add thread-safe behavior to `AFURLConnectionOperation` (Mattt Thompson) + + * Add batching of operations for `AFHTTPClient` (Mattt Thompson) + + * Add authentication challenge callback block to override default + implementation of `connection:didReceiveAuthenticationChallenge:` in + `AFURLConnectionOperation` (Mattt Thompson) + + * Add `_AFNETWORKING_PREFER_NSJSONSERIALIZATION_`, which, when defined, + short-circuits the standard preference ordering used in `AFJSONEncode` and + `AFJSONDecode` to use `NSJSONSerialization` when available, falling back on + third-party-libraries. (Mattt Thompson, Shane Vitarana) + + * Add custom `description` for `AFURLConnectionOperation` and `AFHTTPClient` + (Mattt Thompson) + + * Add `text/javascript` to default acceptable content types for + `AFJSONRequestOperation` (Jake Boxer) + + * Add `imageScale` property to change resolution of images constructed from + cached data (Štěpán Petrů) + + * Add note about third party JSON libraries in README (David Keegan) + + * `AFQueryStringFromParametersWithEncoding` formats `NSArray` values in the + form `key[]=value1&key[]=value2` instead of `key=(value1,value2)` (Dan Thorpe) + + * `AFImageRequestOperation -responseImage` on OS X uses `NSBitmapImageRep` to + determine the correct pixel dimensions of the image (David Keegan) + + * `AFURLConnectionOperation` `connection` has memory management policy `assign` + to avoid retain cycles caused by `NSURLConnection` retaining its delegate + (Mattt Thompson) + + * `AFURLConnectionOperation` calls super implementation for `-isReady`, + following the guidelines for `NSOperation` subclasses (Mattt Thompson) + + * `UIImageView -setImageWithURL:` and related methods call success callback + after setting image (Cameron Boehmer) + + * Cancel request if an authentication challenge has no suitable credentials in + `AFURLConnectionOperation -connection:didReceiveAuthenticationChallenge:` + (Jorge Bernal) + + * Remove exception from + `multipartFormRequestWithMethod:path:parameters:constructing BodyWithBlock:` + raised when certain HTTP methods are used. (Mattt Thompson) + + * Remove `AFImageCache` from public API, moving it into private implementation + of `UIImageView+AFNetworking` (Mattt Thompson) + + * Mac example application makes better use of AppKit technologies and + conventions (Mattt Thompson) + + * Fix issue with multipart form boundaries in `AFHTTPClient + -multipartFormRequestWithMethod:path:parameters:constructing BodyWithBlock:` + (Ray Morgan, Mattt Thompson, Sam Soffes) + + * Fix "File Upload with Progress Callback" code snippet in README (Larry +Legend) + + * Fix to SBJSON invocations in `AFJSONEncode` and `AFJSONDecode` (Matthias + Tretter, James Frye) + + * Fix documentation for `AFHTTPClient requestWithMethod:path:parameters:` + (Michael Parker) + + * Fix `Content-Disposition` headers used for multipart form construction + (Michael Parker) + + * Add network reachability status change callback property to `AFHTTPClient`. + (Mattt Thompson, Kevin Harwood) + + * Fix exception handling in `AFJSONEncode` and `AFJSONDecode` (David Keegan) + + * Fix `NSData` initialization with string in `AFBase64EncodedStringFromString` + (Adam Ernst, Mattt Thompson) + + * Fix error check in `appendPartWithFileURL:name:error:` (Warren Moore, + Baldoph, Mattt Thompson) + + * Fix compiler warnings for certain configurations (Charlie Williams) + + * Fix bug caused by passing zero-length `responseData` to response object + initializers (Mattt Thompson, Serge Paquet) diff --git a/its/plugin/projects/AFNetworking/CONTRIBUTING.md b/its/plugin/projects/AFNetworking/CONTRIBUTING.md new file mode 100644 index 00000000..9bb98ead --- /dev/null +++ b/its/plugin/projects/AFNetworking/CONTRIBUTING.md @@ -0,0 +1,96 @@ +# Contributing Guidelines + +This document contains information and guidelines about contributing to this project. +Please read it before you start participating. + +**Topics** + +* [Asking Questions](#asking-questions) +* [Reporting Security Issues](#reporting-security-issues) +* [Reporting Issues](#reporting-other-issues) +* [Submitting Pull Requests](#submitting-pull-requests) +* [Developers Certificate of Origin](#developers-certificate-of-origin) +* [Code of Conduct](#code-of-conduct) + +## Asking Questions + +We don't use GitHub as a support forum. +For any usage questions that are not specific to the project itself, +please ask on [Stack Overflow](https://stackoverflow.com) instead. +By doing so, you'll be more likely to quickly solve your problem, +and you'll allow anyone else with the same question to find the answer. +This also allows maintainers to focus on improving the project for others. + +## Reporting Security Issues + +The Alamofire Software Foundation takes security seriously. +If you discover a security issue, please bring it to our attention right away! + +Please **DO NOT** file a public issue, +instead send your report privately to . +This will help ensure that any vulnerabilities that _are_ found +can be [disclosed responsibly](http://en.wikipedia.org/wiki/Responsible_disclosure) +to any affected parties. + +## Reporting Other Issues + +A great way to contribute to the project +is to send a detailed issue when you encounter an problem. +We always appreciate a well-written, thorough bug report. + +Check that the project issues database +doesn't already include that problem or suggestion before submitting an issue. +If you find a match, add a quick "+1" or "I have this problem too." +Doing this helps prioritize the most common problems and requests. + +When reporting issues, please include the following: + +* The version of Xcode you're using +* The version of iOS or OS X you're targeting +* The full output of any stack trace or compiler error +* A code snippet that reproduces the described behavior, if applicable +* Any other details that would be useful in understanding the problem + +This information will help us review and fix your issue faster. + +## Submitting Pull Requests + +Pull requests are welcome, and greatly encouraged. When submitting a pull request, please create proper test cases demonstrating the issue to be fixed or the new feature. + +## Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +- (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +- (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +- (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +- (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +## Code of Conduct + +The Code of Conduct governs how we behave in public or in private +whenever the project will be judged by our actions. +We expect it to be honored by everyone who contributes to this project. + +See [CONDUCT.md](https://github.com/Alamofire/Foundation/blob/master/CONDUCT.md) for details. + +--- + +*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.* diff --git a/its/plugin/projects/AFNetworking/Framework/AFNetworking.h b/its/plugin/projects/AFNetworking/Framework/AFNetworking.h new file mode 100644 index 00000000..61a17eb8 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Framework/AFNetworking.h @@ -0,0 +1,66 @@ +// AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +//! Project version number for AFNetworking. +FOUNDATION_EXPORT double AFNetworkingVersionNumber; + +//! Project version string for AFNetworking. +FOUNDATION_EXPORT const unsigned char AFNetworkingVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import + +#import +#import + +#ifndef _AFNETWORKING_ +#define _AFNETWORKING_ + +#import +#import +#import + +#if !TARGET_OS_WATCH +#import +#endif + +#import +#import + +#if TARGET_OS_IOS || TARGET_OS_TV +#import +#import +#import +#import +#import +#import +#import +#endif + +#if TARGET_OS_IOS +#import +#import +#import +#endif + + +#endif /* _AFNETWORKING_ */ diff --git a/its/plugin/projects/AFNetworking/Framework/Info.plist b/its/plugin/projects/AFNetworking/Framework/Info.plist new file mode 100644 index 00000000..2a327732 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Framework/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + FMWK + CFBundleShortVersionString + 3.0.0 + CFBundleSignature + ???? + CFBundleVersion + 3.0.4 + NSPrincipalClass + + + diff --git a/its/plugin/projects/AFNetworking/Framework/module.modulemap b/its/plugin/projects/AFNetworking/Framework/module.modulemap new file mode 100644 index 00000000..a9200e1d --- /dev/null +++ b/its/plugin/projects/AFNetworking/Framework/module.modulemap @@ -0,0 +1,5 @@ +framework module AFNetworking { + umbrella header "AFNetworking.h" + export * + module * { export * } +} \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/LICENSE b/its/plugin/projects/AFNetworking/LICENSE new file mode 100644 index 00000000..3fbc2c9a --- /dev/null +++ b/its/plugin/projects/AFNetworking/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/its/plugin/projects/AFNetworking/README.md b/its/plugin/projects/AFNetworking/README.md new file mode 100644 index 00000000..53cb2024 --- /dev/null +++ b/its/plugin/projects/AFNetworking/README.md @@ -0,0 +1,320 @@ +

+ AFNetworking +

+ +[![Build Status](https://travis-ci.org/AFNetworking/AFNetworking.svg)](https://travis-ci.org/AFNetworking/AFNetworking) +[![codecov.io](https://codecov.io/github/AFNetworking/AFNetworking/coverage.svg?branch=master)](https://codecov.io/github/AFNetworking/AFNetworking?branch=master) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/AFNetworking.svg)](https://img.shields.io/cocoapods/v/AFNetworking.svg) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Platform](https://img.shields.io/cocoapods/p/AFNetworking.svg?style=flat)](http://cocoadocs.org/docsets/AFNetworking) +[![Twitter](https://img.shields.io/badge/twitter-@AFNetworking-blue.svg?style=flat)](http://twitter.com/AFNetworking) + +AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of the [Foundation URL Loading System](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html), extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use. + +Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac. + +Choose AFNetworking for your next project, or migrate over your existing projects—you'll be happy you did! + +## How To Get Started + +- [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/archive/master.zip) and try out the included Mac and iPhone example apps +- Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles on the Wiki](https://github.com/AFNetworking/AFNetworking/wiki) +- Check out the [documentation](http://cocoadocs.org/docsets/AFNetworking/) for a comprehensive look at all of the APIs available in AFNetworking +- Read the [AFNetworking 3.0 Migration Guide](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-3.0-Migration-Guide) for an overview of the architectural changes from 2.0. + +## Communication + +- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). (Tag 'afnetworking') +- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). +- If you **found a bug**, _and can provide steps to reliably reproduce it_, open an issue. +- If you **have a feature request**, open an issue. +- If you **want to contribute**, submit a pull request. + +## Installation +AFNetworking supports multiple methods for installing the library in a project. + +## Installation with CocoaPods + +[CocoaPods](http://cocoapods.org) is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries like AFNetworking in your projects. See the ["Getting Started" guide for more information](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking). You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +> CocoaPods 0.39.0+ is required to build AFNetworking 3.0.0+. + +#### Podfile + +To integrate AFNetworking into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '8.0' + +pod 'AFNetworking', '~> 3.0' +``` + +Then, run the following command: + +```bash +$ pod install +``` + +### Installation with Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. + +You can install Carthage with [Homebrew](http://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate AFNetworking into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "AFNetworking/AFNetworking" ~> 3.0 +``` + +Run `carthage` to build the framework and drag the built `AFNetworking.framework` into your Xcode project. + +## Requirements + +| AFNetworking Version | Minimum iOS Target | Minimum OS X Target | Minimum watchOS Target | Minimum tvOS Target | Notes | +|:--------------------:|:---------------------------:|:----------------------------:|:----------------------------:|:----------------------------:|:-------------------------------------------------------------------------:| +| 3.x | iOS 7 | OS X 10.9 | watchOS 2.0 | tvOS 9.0 | Xcode 7+ is required. `NSURLConnectionOperation` support has been removed. | +| 2.6 -> 2.6.3 | iOS 7 | OS X 10.9 | watchOS 2.0 | n/a | Xcode 7+ is required. | +| 2.0 -> 2.5.4 | iOS 6 | OS X 10.8 | n/a | n/a | Xcode 5+ is required. `NSURLSession` subspec requires iOS 7 or OS X 10.9. | +| 1.x | iOS 5 | Mac OS X 10.7 | n/a | n/a | +| 0.10.x | iOS 4 | Mac OS X 10.6 | n/a | n/a | + +(OS X projects must support [64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)). + +> Programming in Swift? Try [Alamofire](https://github.com/Alamofire/Alamofire) for a more conventional set of APIs. + +## Architecture + +### NSURLSession + +- `AFURLSessionManager` +- `AFHTTPSessionManager` + +### Serialization + +* `` + - `AFHTTPRequestSerializer` + - `AFJSONRequestSerializer` + - `AFPropertyListRequestSerializer` +* `` + - `AFHTTPResponseSerializer` + - `AFJSONResponseSerializer` + - `AFXMLParserResponseSerializer` + - `AFXMLDocumentResponseSerializer` _(Mac OS X)_ + - `AFPropertyListResponseSerializer` + - `AFImageResponseSerializer` + - `AFCompoundResponseSerializer` + +### Additional Functionality + +- `AFSecurityPolicy` +- `AFNetworkReachabilityManager` + +## Usage + +### AFURLSessionManager + +`AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. + +#### Creating a Download Task + +```objective-c +NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; + +NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"]; +NSURLRequest *request = [NSURLRequest requestWithURL:URL]; + +NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { + NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; + return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; +} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { + NSLog(@"File downloaded to: %@", filePath); +}]; +[downloadTask resume]; +``` + +#### Creating an Upload Task + +```objective-c +NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; + +NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"]; +NSURLRequest *request = [NSURLRequest requestWithURL:URL]; + +NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"]; +NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + if (error) { + NSLog(@"Error: %@", error); + } else { + NSLog(@"Success: %@ %@", response, responseObject); + } +}]; +[uploadTask resume]; +``` + +#### Creating an Upload Task for a Multi-Part Request, with Progress + +```objective-c +NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) { + [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil]; + } error:nil]; + +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + +NSURLSessionUploadTask *uploadTask; +uploadTask = [manager + uploadTaskWithStreamedRequest:request + progress:^(NSProgress * _Nonnull uploadProgress) { + // This is not called back on the main queue. + // You are responsible for dispatching to the main queue for UI updates + dispatch_async(dispatch_get_main_queue(), ^{ + //Update the progress view + [progressView setProgress:uploadProgress.fractionCompleted]; + }); + } + completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + if (error) { + NSLog(@"Error: %@", error); + } else { + NSLog(@"%@ %@", response, responseObject); + } + }]; + +[uploadTask resume]; +``` + +#### Creating a Data Task + +```objective-c +NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; + +NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"]; +NSURLRequest *request = [NSURLRequest requestWithURL:URL]; + +NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + if (error) { + NSLog(@"Error: %@", error); + } else { + NSLog(@"%@ %@", response, responseObject); + } +}]; +[dataTask resume]; +``` + +--- + +### Request Serialization + +Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body. + +```objective-c +NSString *URLString = @"http://example.com"; +NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]}; +``` + +#### Query String Parameter Encoding + +```objective-c +[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil]; +``` + + GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3 + +#### URL Form Parameter Encoding + +```objective-c +[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil]; +``` + + POST http://example.com/ + Content-Type: application/x-www-form-urlencoded + + foo=bar&baz[]=1&baz[]=2&baz[]=3 + +#### JSON Parameter Encoding + +```objective-c +[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil]; +``` + + POST http://example.com/ + Content-Type: application/json + + {"foo": "bar", "baz": [1,2,3]} + +--- + +### Network Reachability Manager + +`AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. + +* Do not use Reachability to determine if the original request should be sent. + * You should try to send it. +* You can use Reachability to determine when a request should be automatically retried. + * Although it may still fail, a Reachability notification that the connectivity is available is a good time to retry something. +* Network reachability is a useful tool for determining why a request might have failed. + * After a network request has failed, telling the user they're offline is better than giving them a more technical but accurate error, such as "request timed out." + +See also [WWDC 2012 session 706, "Networking Best Practices."](https://developer.apple.com/videos/play/wwdc2012-706/). + +#### Shared Network Reachability + +```objective-c +[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { + NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status)); +}]; + +[[AFNetworkReachabilityManager sharedManager] startMonitoring]; +``` + +--- + +### Security Policy + +`AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. + +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. + +#### Allowing Invalid SSL Certificates + +```objective-c +AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; +manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production +``` + +--- + +## Unit Tests + +AFNetworking includes a suite of unit tests within the Tests subdirectory. These tests can be run simply be executed the test action on the platform framework you would like to test. + +## Credits + +AFNetworking is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). + +AFNetworking was originally created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla). + +AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/). + +And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors). + +### Security Disclosure + +If you believe you have identified a security vulnerability with AFNetworking, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## License + +AFNetworking is released under the MIT license. See LICENSE for details. diff --git a/its/plugin/projects/AFNetworking/Tests/Info.plist b/its/plugin/projects/AFNetworking/Tests/Info.plist new file mode 100644 index 00000000..32379bec --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + com.alamofire.afnetworking.${PRODUCT_NAME:rfc1034identifier} + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + + diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_0.cer b/its/plugin/projects/AFNetworking/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_0.cer new file mode 100644 index 0000000000000000000000000000000000000000..5cbf610fe652c33dab0c2f549e601ea2beb2133e GIT binary patch literal 1321 zcmXqLVpTP0V&PrD%*4pVB*5L(@Y3#O{b8vMhc`%ceT_8WW#iOp^Jx3d%gD&e%3zRY z$Zf#M#vIDRCd?EXY$$3V4B~JJ^SETDXF8`Al_+@TB^yc_h=YW=g$2sX%k@%#QprFm zz2y8{LsbK1kQB493|xmtW_pH#V{vh5QDR<<3ziM!u8p+Ps?OPR7gikGq)G; zu1Hh4nD@AP(YYhJv%7-2_vf%4$Yg9iu|>8!dzn<;s*Cf^Hb#clEK6`@W@tI)bo`mv{s z@V@J9MiGG(Wmz#FrGKW~%VEjeP$jB+xU%kQn(=&%S*Poa1>(;qMQ)z2`gY2%2W+|R ztao^L92DzusX*q+g6bnoa6>Bm;VSNHF28t z1u!`@)+smLxi{yZyT z{ubz;_molL%Du{&9?jpuF(AvwBE}-}?$4=%MRspl&2!f53%B@}Cs3s243QRO0mfhx zA`Y6^VUfWHGM=B2@jnX-GZX6qh;mhsayAZaHef(23?dA)7HBL` zYg5T6DJihh*H13WF-A$A`pJpLy6Hw1dO#UWwI;aLI)SWEV6ir^G%#o5Olb39Z2OzT z$Y`KtpaF9T6Qh_6$lhY0#pu~W-#H-IpcJWYWvnUH{=|*R>~$7rQ>n*uU3uy=Ci?faV9? z8{daWojCmG-d9!bCtsRY-{sh_WxG$+H&Z1GTe0o!mM(|)C^uZsmr(D0A#M|Ed{+Ml LSE!%Gvt}Lu*zU_* literal 0 HcmV?d00001 diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_1.cer b/its/plugin/projects/AFNetworking/Tests/Resources/ADN.net/ADNNetServerTrustChain/adn_1.cer new file mode 100644 index 0000000000000000000000000000000000000000..683d5ff30ac23b7f8ef3ceacf01f82f08c278102 GIT binary patch literal 1628 zcmbtUdr*{B6u)=B-DLrRg%$9DumUnXl)VdxMv5$pK%&MY5H%LJj|D#6SG!9L$T+z= zOF4kSG%3W;PD+v^HX@>wfPzM*(rZi0d_)g5Lujl-@zJ>=j@I}`(>HS;=XZYR+~0kC zhggNV#41RzGd#@WiCywNmock-Ykj{Qb}&_oo+WNV=Wtu9?WP;X0s$ggxhruNGTD5g zgqNKq_a+i*xJV`?aYdX`W3ot})3fra#FxUZ5^-s1X=DMoSa3zM2Aw>Dgi#kG349ch z$`ut$6=rjZNv&r!(#1K_OoPE9RVs+TuN#?9Vn~!ciomzZ*DWdv%xG$WNech3npq@h zT#et;)F>5mqKOp;K7J5bfEX+GK!CgOtQeynwM&>dKy@!>UWRDYe=KlF-R}WYNWLlZ7T1^83TfLdxsEuIbY~Z&$S* zURc|^a=j{6dnD^KB#Md`7vzd1T>qr&jfolPmLTbR@IZOMP?cwwSIZ6WKm5w&9G<@G zm%Jkl+6~T4mot-=h~t8Odb@-9prx^W^*fHV*1D>J1D@f#=S`_@?>%((MPb$G{h+S7 zDn~{9hE49ZZwa>dwFUh6iRRk->+|fhPu*GYt#0Vl?KEZ83CE#kwO?C8N2u4u&e8mP zU$vbWUfAxRR^hj_KDKG$wcmCXt7cp*(yPXJ3`Tf|m3Nz1d4CaiIMNv&7~kjf;ZfP( zls=}2lyAjdV01z|Aaq@0OU1UkTFf9G06R&XP!u7AH|E5{K9R*1i!n|n`{(PCna$cc ztkFEjq%j)IoW)=&1F8<<3m!$&Y&rf`oQV`jkIIk~l^`?Hz-T~)&|6S3;sB8%C7>p- zIlwu@A~nn@j|HY47}R5dXo^z48ayn_jew|uLFbQWrB)Ke6hWKFO;<@rvIl+EgB*HP z03%gF`I*pbK_v(Iioi~X%v2NAtpLOXehtz=(*r6+r4Q7z&`TkX0}s_WK3Aicz@q4Q zJk?0oq8aI0bPc*U6YPNYeMcLh>!0zl6cX3l+c?M5g`mbj7ZGH z$z#k9B_Sku!Y0@@<>5UVShMkoGC($NrKtk=8!O4i%_PAdZ(m@Gd&p)@+UO_PvWcIQ zR*FZ3VsQ>F6G}xS@c*45=D%hLpn`(3U+J{nI_^5vjq`-WCkU; z^L_Y}(|rYoYm%I?#lf35p?u^-WH>THC$VJA%d7VdBw{-1r zMPt*v?=r2qYmfH_*Qcf=%l+$y+w+&l^uN&~KRUW^v+eUny!+yo9N|FRRrkHyEO}>M zZb-D`U#M1AT)3J&#G#XdOXX^H^cPc?-4b25KXZK6+=CIvJlf9x-h9wK_*h72by?}3 zvXK=ZRya9+xN~|HS+T(;PB||RICJOS-X2ns7rgt*t-bkcExiNl_9vg6*&XJnQF(up rxa4w_VduVe8Jlvu7wP)PzGG&dTHrk&& ztLnL}Q0ws3DJJQQxMViOXD)Ntcx3yg{tGjftaOaDx_oEKHJjTd7E8R&_^LL2_gWe( zWby8^XKvxdy5w!Em&G4m((=PUDRAG9qi=3oOnS`rlw%^#5e>)C->0KGMe7P*nC|y2 z;KS3U1MC5c*hY*|CU8utq&? zd&l;QPp7z6SghtsIkZ15c52JPg{pGxu~Grt3PNWbcjs{jTI}#X&BV;ez_>WsAklyi z7{#*ujEw(TSb)i@&43@o7Y6ZJ4VZzHfh)yU1V#fRgNzj0^gGw*%(v-CW8(-{yshZ|Lo0pNehH&82Z8W| zU7xFN3a0j%{+jp4b?dyFK8D^qCcbdi>Dyd!?)Ky0%ED_;6{j%X3T>aIlJc!9?aaM7 z=4V%!Y|Nakd}3aOl6Haf<4||QM9KFNM_cv%48AQe6jMI&{86fy@#+0i(hF>VoQmr< z>`vh5)a7A|3EF<-C)bRNqVe;E_SKjrTkLgNQvXCvo9oE*Ox~A0j}8cg?>JE=G%@s( zN9K(^T1?UWE>{!`Z-3cUpcXqJVcs5ZaZdd$r{$b8PO_^XycF~OmEz6}p*c2l_Rss% i5HmaZ>>Kx0s_N+r%s(?U)rMSO`QxRY@Z$0p@?HQubYDLJ literal 0 HcmV?d00001 diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/Equifax_Secure_Certificate_Authority_Root.cer b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/Equifax_Secure_Certificate_Authority_Root.cer new file mode 100644 index 0000000000000000000000000000000000000000..c44db27440eea7a3bb31f074f7e78371561bc439 GIT binary patch literal 804 zcmXqLVpcF{V(MJL%*4pV#A15y%XtG{HcqWJkGAi;jEtyK7--W?Eu}p{{{8NQ7Hh1uCKtoSIx(l&avIT2zvmmYJMblB(cXT9T1p zlvz?~AScdiX<=YtWMpV&VrXg@CC+Pz%%!@0jq{Ox#K_9P+}O)t(Ade;*vN1&c4I_3 zN7B0mvvlP-awm#p%;1vycZ(%oxFt#P@Wq;Q^I0G4VEo``^5#+3RF;%AAG3qwSvQ|f zZ`kj|)c5Z$Bj=lk3?lx2et+P(>%1#k`=NY8!A#Nc$zmV*r)OvT#K>w;01QT1d6rCrbc56d z$qN#f#2ds?H}DO44Y)yZ#VpL?9OPqYAO*5ffJN9qu#w-$05u*!3T63OSb!;m%|IT+ zQD%`a5Ni9zim?Tynv|}XXQT;yqDaXH{;!k|4}C{hi*zM48M0k@wKhia%E3OmNuvA zKkw=ni3M#yYhh_-T4IHvu7Ng4gj-kzDxwganp|3xs^FYjRFavNnVeXXs^C~!l96AO zSyE{rC(dhNWMFD!XkcOh1X1F=h86}EaIS$9s(oSxA`ts{-Ba^Jib{)16g=~i^$evA zBthcL!a{Iy_niEs#2f`@M}sCtC1h_fvNA9?G4eA2#krW87#SIEosmd3`1?g%St_h9 z`o2w$#goGA6%()QS$Mowf^~aVUEz{vM-rB8 zc;E1(Q-gn=>b1AcpVuy%czni5Cka!Lxoc;*P15r}^|9UgpxD%K-GKLn zRWmYrJAbccP2mx&T~(X99nfJ_DhYXeI*4sAAI+GJ;96w?KnRSYz&yu2LMu%guB{L-T2)MEXj)Pnrt%#!?~ zO5{WVOxw(jjSOWEh4TEo#e~`n*fuqCod3Xa{CHtq+Pgz=6OmQZF1=nXBf{aiZTHiO t@0-nD%ZBBjy0xb`dBT(WYCEOVw(M`?ElTD*W)ARMxPHdF#7`~uLID2>L2m#6 literal 0 HcmV?d00001 diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GeoTrust_Global_CA_Root.cer b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GeoTrust_Global_CA_Root.cer new file mode 100644 index 0000000000000000000000000000000000000000..4ae42e81b7ab27da185c149c5cfa42e0c7d8ef11 GIT binary patch literal 856 zcmXqLVh%BAVzODl%*4pV#LQ$8X28qFsnzDu_MMlJk(HIfz{!x?fRl|ml!Z;0DKywn z%s>Rh;S%O`Pt6Z0DlINi@XSlrGn6)v1c@^X3&F+RbMliCa}=B%4dldm4U7y-jSLM; z41gd?oYx4MOBFks7?qHn&dAEZ+{DPwV9>ZE`H0 z6mGAWcxBJR8$Lf)IB#Qq>8r@j(Qzw6Kh08eFKb2jT#Fa1+q3ElmpnU?ux!Koh9{jG z{PR?=y>0%ycG<+^Gfp~5n2O9@JHu^~p8u(j?al|qriSYVyzkU)s0v^E>0NyGC5GOe zB0oe#O>Z7>TU=dqV&eXjq1tCJOt+h(mU8C)xn{}2Q-05`T&-Ryc{cRki8q(xEP|iL z`1k1k3s5%ullJU%-x5nnhV4_CEGKgF{j<=!D9bwQo3C9yKfCOD9l8Dl%SXS=f`u)w z#HnfDwp}5z*XXqbvqlh0;nUT|wht|KvzxUf&8d7PX7DBcfcA^R>?c2&m>C%u7Y7>z z8t?-nN>-SW@jnZz0W**?kOc|wv52vV9H^R+(cAfZHERlwVC|~f)E%eJ_!-E9q?K7D z48$6+D?m*#z+h)&Fnz3<^;ADLq)#(o%KVv9B2W4&w34PQQcs_E;k;Cw`^$rymYl!q zD8=eG+xwkYerV8Um4)V9uT#pj^mIP|wJx2o|5xFS$AFMY+fH zHOmzG^_HFFIkah}E5q?~f`Lj(50<{#ChEbN@+!{1Q_AqwZO)}*gqX8t$jL%n|| zx;{<6pajCVfdT#lzY<`5?N(B`Y#Ht#t+bmWaeWL>aa)DSBl2kv#o#2RDJF?^AzyO7 zuV|nQ_>#+0Fk8SbW~QBhMdt9UM8pCSizoz;mkC(}5wsoeTv+t!tVYS{7rz&raP_Rd zezJI&O;r0p>Vu=$;I8v zqtkxd{V4K!{?>Vg!?l|#hsMx7x@*S5_VlYI&E5iU$8AmbL;nry=Tdc<@^)WQ``)I7 z$L@dA(|IJ0t*&oSq?R5U1wcjK5g=c)s28xP8>nG~>Lip4 zUOG>Lh{a(dBs3BNRq+mE@anq!Qi=K^v(B&d18%YtomatJN znAt&lEPM`XgH21tDcn)ckmj<$8sQT>X2w|_aIn+=dqQI*H5q^6nv6ZAtb(U^Vz_%M z;h931rYg+z6oqsB6oQ#L#Y^!#TL>N?%6P!)<^j8h2S|noC8tOO>8*&M9uwMS1DWCIIF1;>+Olkv)u z2E1V=*kZnE)$1$+`^1ex5Og&t0rMs>5N=PjGmI-kr*oB(Jo7qZZnhDI>}GgkBqTNm ztJU*o(B?8%@H$UNV^CFA9@u*&$@f6@Rcyb>(0d{0QC2CCbC+3(AmgYI2tXo-=AyGe z%x2a5cO)@!=bqZnct@+w{$Pr2EveFh*_=Rw#)4UJrVPFwP~>L0P>cYnL}IIw!w(Ap zoFoxV25*9-hPe&1Ll*z19tZ#348K6|-HZsd_fD?)W6<7OT`{w@`sMgw4fa;GuZ6wn z>gxTgpdfbUyVozM)$0?A>)U_1rfEr@FYc7L)p_2Fzra*I{}Z`yOUEjD;|fe8nMF@N z+;wkjtszP(*>rf>n!J(a8I5Z#_1cYtbCzbd)D`1xo-Hpj&b^@!D-v~SKE;d!1J53u?)eu?Lb)0M literal 0 HcmV?d00001 diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath1/googlecom_1.cer b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath1/googlecom_1.cer new file mode 100644 index 0000000000000000000000000000000000000000..521e439356a71e9f4d3c961a699a71a3e39271a2 GIT binary patch literal 1012 zcmXqLV*X&z#B^f;GZP~d6El-lnE@{wr&gOs+jm|@Mpjk^11Cdn15P&PP!={}rqEzR zF#{10hfA2(JvBe1sI<65!80#e&rsSx5+u$nECd&K&&f|p%u#T5G>{YLH8eIbF)%d* zLQ~TyAlJ;$$QX!BEln+>3_MZo5H=8m*umwVpP!zS3bMga)j%0yfec)*B(*3nwM4*a^M3LAGe6{B?Y;%s`RxZT1juU`Fgx7hC=Sf2|8Hfp+?=g% zueTt}>spn2&wle8@vRLX}#GsT|w};n`%#W_`E6QYIW@KPo-1yv} z@ri*vFhFIMStJa^8bl6M&B*BO{Jokrg-5VfV zv9;`LEHyT2jm&(v2kd#0n;BlBO{BF zfr5b?jBmi$CWK-_3djTlaga3%ECL3620UzBK&>o{*D9G<8IjWhFf{|y0waTZ&-s_f zt@j|VB`tHGQ z8!q!lJp8@!-<*YuU;I63|K)n&oxMFvBp)a$D~AgAFA-zntlPQ%-RQ_AqwZO)}*gqX8t$jL%n|| zx;{<6pajCVfdT#lzY<`5?N(B`Y#Ht#t+bmWaeWL>aa)DSBl2kv#o#2RDJF?^AzyO7 zuV|nQ_>#+0Fk8SbW~QBhMdt9UM8pCSizoz;mkC(}5wsoeTv+t!tVYS{7rz&raP_Rd zezJI&O;r0p>Vu=$;I8v zqtkxd{V4K!{?>Vg!?l|#hsMx7x@*S5_VlYI&E5iU$8AmbL;nry=Tdc<@^)WQ``)I7 z$L@dA(|IJ0t*&oSq?R5U1wcjK5g=c)s28xP8>nG~>Lip4 zUOG>Lh{a(dBs3BNRq+mE@anq!Qi=K^v(B&d18%YtomatJN znAt&lEPM`XgH21tDcn)ckmj<$8sQT>X2w|_aIn+=dqQI*H5q^6nv6ZAtb(U^Vz_%M z;h931rYg+z6oqsB6oQ#L#Y^!#TL>N?%6P!)<^j8h2S|noC8tOO>8*&M9uwMS1DWCIIF1;>+Olkv)u z2E1V=*kZnE)$1$+`^1ex5Og&t0rMs>5N=PjGmI-kr*oB(Jo7qZZnhDI>}GgkBqTNm ztJU*o(B?8%@H$UNV^CFA9@u*&$@f6@Rcyb>(0d{0QC2CCbC+3(AmgYI2tXo-=AyGe z%x2a5cO)@!=bqZnct@+w{$Pr2EveFh*_=Rw#)4UJrVPFwP~>L0P>cYnL}IIw!w(Ap zoFoxV25*9-hPe&1Ll*z19tZ#348K6|-HZsd_fD?)W6<7OT`{w@`sMgw4fa;GuZ6wn z>gxTgpdfbUyVozM)$0?A>)U_1rfEr@FYc7L)p_2Fzra*I{}Z`yOUEjD;|fe8nMF@N z+;wkjtszP(*>rf>n!J(a8I5Z#_1cYtbCzbd)D`1xo-Hpj&b^@!D-v~SKE;d!1J53u?)eu?Lb)0M literal 0 HcmV?d00001 diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath2/googlecom_1.cer b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleComServerTrustChainPath2/googlecom_1.cer new file mode 100644 index 0000000000000000000000000000000000000000..521e439356a71e9f4d3c961a699a71a3e39271a2 GIT binary patch literal 1012 zcmXqLV*X&z#B^f;GZP~d6El-lnE@{wr&gOs+jm|@Mpjk^11Cdn15P&PP!={}rqEzR zF#{10hfA2(JvBe1sI<65!80#e&rsSx5+u$nECd&K&&f|p%u#T5G>{YLH8eIbF)%d* zLQ~TyAlJ;$$QX!BEln+>3_MZo5H=8m*umwVpP!zS3bMga)j%0yfec)*B(*3nwM4*a^M3LAGe6{B?Y;%s`RxZT1juU`Fgx7hC=Sf2|8Hfp+?=g% zueTt}>spn2&wle8@vRLX}#GsT|w};n`%#W_`E6QYIW@KPo-1yv} z@ri*vFhFIMStJa^8bl6M&B*BO{Jokrg-5VfV zv9;`LEHyT2jm&(v2kd#0n;BlBO{BF zfr5b?jBmi$CWK-_3djTlaga3%ECL3620UzBK&>o{*D9G<8IjWhFf{|y0waTZ&-s_f zt@j|VB`tHGQ z8!q!lJp8@!-<*YuU;I63|K)n&oxMFvBp)a$D~AgAFA-zntlPQ%-RyYhh_-T4IHvu7Ng4gj-kzDxwganp|3xs^FYjRFavNnVeXXs^C~!l96AO zSyE{rC(dhNWMFD!XkcOh1X1F=h86}EaIS$9s(oSxA`ts{-Ba^Jib{)16g=~i^$evA zBthcL!a{Iy_niEs#2f`@M}sCtC1h_fvNA9?G4eA2#krW87#SIEosmd3`1?g%St_h9 z`o2w$#goGA6%()QS$Mowf^~aVUEz{vM-rB8 zc;E1(Q-gn=>b1AcpVuy%czni5Cka!Lxoc;*P15r}^|9UgpxD%K-GKLn zRWmYrJAbccP2mx&T~(X99nfJ_DhYXeI*4sAAI+GJ;96w?KnRSYz&yu2LMu%guB{L-T2)MEXj)Pnrt%#!?~ zO5{WVOxw(jjSOWEh4TEo#e~`n*fuqCod3Xa{CHtq+Pgz=6OmQZF1=nXBf{aiZTHiO t@0-nD%ZBBjy0xb`dBT(WYCEOVw(M`?ElTD*W)ARMxPHdF#7`~uLID2>L2m#6 literal 0 HcmV?d00001 diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleInternetAuthorityG2.cer b/its/plugin/projects/AFNetworking/Tests/Resources/Google.com/GoogleInternetAuthorityG2.cer new file mode 100644 index 0000000000000000000000000000000000000000..521e439356a71e9f4d3c961a699a71a3e39271a2 GIT binary patch literal 1012 zcmXqLV*X&z#B^f;GZP~d6El-lnE@{wr&gOs+jm|@Mpjk^11Cdn15P&PP!={}rqEzR zF#{10hfA2(JvBe1sI<65!80#e&rsSx5+u$nECd&K&&f|p%u#T5G>{YLH8eIbF)%d* zLQ~TyAlJ;$$QX!BEln+>3_MZo5H=8m*umwVpP!zS3bMga)j%0yfec)*B(*3nwM4*a^M3LAGe6{B?Y;%s`RxZT1juU`Fgx7hC=Sf2|8Hfp+?=g% zueTt}>spn2&wle8@vRLX}#GsT|w};n`%#W_`E6QYIW@KPo-1yv} z@ri*vFhFIMStJa^8bl6M&B*BO{Jokrg-5VfV zv9;`LEHyT2jm&(v2kd#0n;BlBO{BF zfr5b?jBmi$CWK-_3djTlaga3%ECL3620UzBK&>o{*D9G<8IjWhFf{|y0waTZ&-s_f zt@j|VB`tHGQ z8!q!lJp8@!-<*YuU;I63|K)n&oxMFvBp)a$D~AgAFA-zntlPQ%-RQ_AqwZO)}*gqX8t$jL%n|| zx;{<6pajCVfdT#lzY<`5?N(B`Y#Ht#t+bmWaeWL>aa)DSBl2kv#o#2RDJF?^AzyO7 zuV|nQ_>#+0Fk8SbW~QBhMdt9UM8pCSizoz;mkC(}5wsoeTv+t!tVYS{7rz&raP_Rd zezJI&O;r0p>Vu=$;I8v zqtkxd{V4K!{?>Vg!?l|#hsMx7x@*S5_VlYI&E5iU$8AmbL;nry=Tdc<@^)WQ``)I7 z$L@dA(|IJ0t*&oSq?R5U1wcjK5g=c)s28xP8>nG~>Lip4 zUOG>Lh{a(dBs3BNRq+mE@anq!Qi=K^v(B&d18%YtomatJN znAt&lEPM`XgH21tDcn)ckmj<$8sQT>X2w|_aIn+=dqQI*H5q^6nv6ZAtb(U^Vz_%M z;h931rYg+z6oqsB6oQ#L#Y^!#TL>N?%6P!)<^j8h2S|noC8tOO>8*&M9uwMS1DWCIIF1;>+Olkv)u z2E1V=*kZnE)$1$+`^1ex5Og&t0rMs>5N=PjGmI-kr*oB(Jo7qZZnhDI>}GgkBqTNm ztJU*o(B?8%@H$UNV^CFA9@u*&$@f6@Rcyb>(0d{0QC2CCbC+3(AmgYI2tXo-=AyGe z%x2a5cO)@!=bqZnct@+w{$Pr2EveFh*_=Rw#)4UJrVPFwP~>L0P>cYnL}IIw!w(Ap zoFoxV25*9-hPe&1Ll*z19tZ#348K6|-HZsd_fD?)W6<7OT`{w@`sMgw4fa;GuZ6wn z>gxTgpdfbUyVozM)$0?A>)U_1rfEr@FYc7L)p_2Fzra*I{}Z`yOUEjD;|fe8nMF@N z+;wkjtszP(*>rf>n!J(a8I5Z#_1cYtbCzbd)D`1xo-Hpj&b^@!D-v~SKE;d!1J53u?)eu?Lb)0M literal 0 HcmV?d00001 diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/AddTrust_External_CA_Root.cer b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/AddTrust_External_CA_Root.cer new file mode 100644 index 0000000000000000000000000000000000000000..8a99c54a99fbe7d188e8349044bbf835338815b0 GIT binary patch literal 1082 zcmXqLVlgvlVwPLL%*4pV#K>sC%f_kI=F#?@mywZ`mBAq2klTQhjX9KsO_(Xz)lkGh z2*lwM=5|a;2`MTqE>UoFGE_5A0f}-8%fdxnD@sy}@)C0tLP7!*{8CHG^NX?#l?)U> z>X?NkG1WOcDg@={ml(*2^BNc!m>L@x8kkrZTSSTT8XjN?rvBY=YQMRKuAJRO$F&7v$3OVnzc89ta_Yo{keA2e z`77qma!f!mNNh*Jt^yXWhK4aLSy*%>fBq$A#xwu(vU-c)21|O=7}o zpAG)XtF8Q7ZrndN|6ykS?(0t1vt6DXU;8fCF}^6Oki&d)W$Kd11yjtwGwAaknpAY_ zf<@77krl2-Vzp|wZ@G5l-I}w)F56FP-*skC{gt>gGb=(_aQkxO{;<->uV*!{yKU#v zPTh9dDPMHcj_TjoB)8i0+;|888*y*(5iaqn(`z5X>60`I?kALv!$}}rd+fLyRuno|Argo zyVp48xF<9RZun_r`~1&0HR0n8VoUc&{b@g6QQ4_D>yZyTSDWdcPxk_kT$;B1PMzPo zg1<7BuX&gPMRfc2iaj`Z->vky%Gx(yoVK)1E)YoHHJ8oQOX9M2)tNx2g;mKHpY2|F zRQr(GK4IQxdz0%btCw@~I;_sR+uwEg+qWJmC)U6#u3zUbPg2YfRdBYM`MhSY%8iv1 z#fv-a!=w!@B(@at&pLa8Z(g6C^uwMR&8OuJKf3rFV=4A5OW;5LW3PBaw%*G#K73KL eD)|+-^sdfJR+9^zH04HUoFGE_5A0f}-8%fdxnD@sy}@)C0t zLP7!*{8CHG^NX?#l?)U>>X?NkG1WOcDg@={ml(*2^BNc!m>L@x8kkrZTSSTT8Xr?e)pb%`8bxG1NBDgg8$LDi;*&sNkGhRFavNnVeXXnV+ZNSXz>i zUzAx=Y0$)k5>||?49rbT{0u;GE~X|XMuv$mLMC0}3fs7bSLN=}^DgNnGqueZ*D4n< z6z&PWf8>{zP``J*K-k{-1x4Ev>rZ;~i!Zl*yn!Y0-G9O9$G^1Mas9H3`8oNSN!3k} z?B{bfw=QU^DqCMT;rg4uyuaq;{JOuP>5E9+&wWRh>HF8utl#=4-MMHl55u+2*V#Ik z-}cXt5m{aL^l{#w8!MhnQn}@vowOtL@2i7*a<+AU=IfpHWOh#G%pVmV2Ci4vKIFA= zP55IpEl_<=`r%W0+p=G|9Y3zHV55BMJr9muOZ--TYIZYkdHv!{qla_4Uy;`An7uyI z8eK6;)mv82xcTluVDn*4H@{rFnZKrr->NYVceLpZe9OHpX1z|b)cx=i_IqB&9+|z~ zb>^eRQ7T(@tqik0pTFwAXT-h_EB=4kvG%3;?_E2-a9jO+;p`;Wd86gD@W-3GA9g0} z=+OvUBO*J8>v`ep^L%%0S58~#vDfDN`mMZ5J_iIF--KCzyS(U8^!80GNaN+QxRXU2R+|OyuVRJ3p-z1^F zk&nQT$}{_BWZ$b06!4^&QvNEyh26!5W#v54$m zU&mzoYuQJemcF&`EM~m9X=HQ-oQP%l85#exumE#yn*l#axiE;&YQPMn3#pvFxko}c zOOHQR=ZkHrGQ%Gu64I;-<~_|vo9`t L|Is>Mz#<<2E=x9y literal 0 HcmV?d00001 diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/COMODO_RSA_Domain_Validation_Secure_Server_CA.cer b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/COMODO_RSA_Domain_Validation_Secure_Server_CA.cer new file mode 100644 index 0000000000000000000000000000000000000000..7d7e8f271e43b37257755ed76258f83533d2fc98 GIT binary patch literal 1548 zcmXqLV&gDqV*apznTe5!NkCgK@72vxvmBAGyxWUwde{wk**LY@JlekVGBWb8G8iCn^}^YVyJDP36f(LR)Wd}1v@G@rxulDre!84 zmSpDVDL9svWaJlRmQ)(ZiSrto7#JBE8Gu2QIIoct%l>tM=+0mehQ3*LT8Ce;an;7{SfZ|+C zO^l2TeTSGNA1;Vo^4h|*SLZL|h0C4?QjT*cvAT*`typk?hpArn%tZKZm_Od`*m7q{&aV)n$~Wm>Ajm<9!v|rP#}>ot^b`a`{cO`cb&R;w)*7}tyvn1 z6Mge1`KvDdRAqWs?T*{h3u_`xd;a@PbPlkOoGh0UsQ4~IWc9z&fC@XG4Ki)Qzp`iS zd0;(7t~KZm^JEo?ywmD|uFneYsX8y=edx9H?Y6oTXLH}_$*LE}-f=Z(SoL_5Blr5f zF73B=K9!zZzwT*k(^4j8Mh3>kO^m6)5J@zU2Zph%GK++PScAy!^>s|Pzm|QpY3W=0 z&SJ)!n?^=g3}itH_*lePL?*1yvYHabePhBap|Iln&ReWBZaoL5JXwB5#{VoVz?9u) zAOun_4B~SbumLG1Mh1uxsw`p#B5WMmY>cd|?97aC7L$QANQ(lCh=Gs+8ygFd$zZ_2 z#+Kg5!^p&F-~*DBXK^)fHgH^EzreQ5I-{hdz)D{~xhO|3IX^c)B|kY4#L$PN5@2FR zNz3r0tOwL!PzbY@k&z|UAlbkg#y4PU(}x>eg2Q0Pl$4O7(&7?lN1$OP1}bpPjBOH7 z&H2g21t_|alOix&>YDMx+oW3Enqy18ignT4uqBKyHLAs>l?!)62EY2D)#s1!8 zy%OuLo^b8Ag>_ERqA5R|r0&1XXX|l2#Ky4d$%{KTw>~Vcc=Jv9&c(YqeNz2PUxn06 z+kW_8XkV{q+@F-)=k4}Rd!2c9{{xSYNlgMzdECN38Q;2aBKhqx`6;Z^yrd>x{QmlU zf6zK!j+=HX76iUL*j{q={z9+*dKSQ|d&3)hX>v9@we zoI;w^(w)n;S|0p5!}FgsLtM84&_yXI1PlgS;nsZ2K} z{M3DAepM>rLb}5B8&2G=>zgv}-Az+5pP)HK(oIrzN5l2gSK2hPTnf~blUB}e%iq6i qLcyi5^45y?uT)oxp9?7JVX#{D_;#|%{2y$EjE|ZWuKdg2yAc4zK1JmK literal 0 HcmV?d00001 diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_0.cer b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_0.cer new file mode 100644 index 0000000000000000000000000000000000000000..e2a2a3a13c337456dd97eac8f5ea0186c028edc0 GIT binary patch literal 1363 zcmXqLV)Zv@VliL9%*4pVB#;(ucmBzdNqZZf9$k7-F?5dsFB_*;n@8JsUPeZ4RtAH{ z35MJToNUaYENsF|?oNi%29h8Shp>=)QEFmIYLS9(VqS7aYB7*$C}6+`l4KWV4^GTU z%P&eXlroS2iEs%EI{W+jyZ9?OJ1Y2O=4O_prWl$Tn1JM%g>|8FLBWm+F8R5MnRyCf zi8+}mi6xo&c?!X)$)!c9K&q$=Xq&U6ft)xmP_Ln(kpUP)0lDTtuBDN&simo9ltHwi zqJccfWNu*zsBzBuc_l^pIWS{^mdhE)K$M8O78j@Hm1HL71PA*lglFcYBqstLE@mJC zb{r3{mR?3lNkLL(o?d=Yx?EA-7B?Sst|Zh1$a@ju?VVET@jhe86SpVXKW6ZaibQ@k|SnBgJAku#^1TxU-{ z_x#_SNs3#=qzV+BFYJ&sQ=Z2#>t=&SsNkF6c+E|l{^Tx_+9-9#w6s9Vq{Zc6iO21! z|K>P2S}oK6JcZGI!jlCDdV1C`dRDz`)*;$?`KY{%2ufW@24nzyne)4B|5xFhDe`vVfwB zLz|6}m6e^D5zb;V@CPYYVDT_;Gq7Ug1}b1-+++w$^XvxN2AVK+OpIc(p!hAe($_Br zr!>9f{M`JMd=RDY91v{4!N!)}$iv9QXb=K2P@cutz}vucf%^j2HfNAdpvL5)9H_43 zM2J3cVh5&YNcuyhW=LX&q-AGEJ)lN|##WeH7#UeA4a$M;hWf^U3CV^Ma&0IvP=OoB z*d_sWa(;4g0g8zRsvzG9vH&wi6Ka}o;zrH@sO1AN@iQ{`n!MKK&adQmNdCR|=X6!O z^N;u3Qt!>5eXsJ0;?dfLn_hi$TIrVYtwrnZL#diHpX*n?_o{Dh`n_#kt;^#ko13e? z++AkH;9dE^nv8IoTSFbv#5ooWQt_j~DDWJ+VZR^-xpSk*h7w z&X(#tT5?2XjYYU0L+0BW51#3#=2>&Rc%`7X@58BEpEPU@1uX96sFlCn^}^YVyJDP36f(LR)Wd}1v@G@rxulDre!84 zmSpDVDL9svWaJlRmQ)(ZiSrto7#JBE8Gu2QIIoct%l>tM=+0mehQ3*LT8Ce;an;7{SfZ|+C zO^l2TeTSGNA1;Vo^4h|*SLZL|h0C4?QjT*cvAT*`typk?hpArn%tZKZm_Od`*m7q{&aV)n$~Wm>Ajm<9!v|rP#}>ot^b`a`{cO`cb&R;w)*7}tyvn1 z6Mge1`KvDdRAqWs?T*{h3u_`xd;a@PbPlkOoGh0UsQ4~IWc9z&fC@XG4Ki)Qzp`iS zd0;(7t~KZm^JEo?ywmD|uFneYsX8y=edx9H?Y6oTXLH}_$*LE}-f=Z(SoL_5Blr5f zF73B=K9!zZzwT*k(^4j8Mh3>kO^m6)5J@zU2Zph%GK++PScAy!^>s|Pzm|QpY3W=0 z&SJ)!n?^=g3}itH_*lePL?*1yvYHabePhBap|Iln&ReWBZaoL5JXwB5#{VoVz?9u) zAOun_4B~SbumLG1Mh1uxsw`p#B5WMmY>cd|?97aC7L$QANQ(lCh=Gs+8ygFd$zZ_2 z#+Kg5!^p&F-~*DBXK^)fHgH^EzreQ5I-{hdz)D{~xhO|3IX^c)B|kY4#L$PN5@2FR zNz3r0tOwL!PzbY@k&z|UAlbkg#y4PU(}x>eg2Q0Pl$4O7(&7?lN1$OP1}bpPjBOH7 z&H2g21t_|alOix&>YDMx+oW3Enqy18ignT4uqBKyHLAs>l?!)62EY2D)#s1!8 zy%OuLo^b8Ag>_ERqA5R|r0&1XXX|l2#Ky4d$%{KTw>~Vcc=Jv9&c(YqeNz2PUxn06 z+kW_8XkV{q+@F-)=k4}Rd!2c9{{xSYNlgMzdECN38Q;2aBKhqx`6;Z^yrd>x{QmlU zf6zK!j+=HX76iUL*j{q={z9+*dKSQ|d&3)hX>v9@we zoI;w^(w)n;S|0p5!}FgsLtM84&_yXI1PlgS;nsZ2K} z{M3DAepM>rLb}5B8&2G=>zgv}-Az+5pP)HK(oIrzN5l2gSK2hPTnf~blUB}e%iq6i qLcyi5^45y?uT)oxp9?7JVX#{D_;#|%{2y$EjE|ZWuKdg2yAc4zK1JmK literal 0 HcmV?d00001 diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_2.cer b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_2.cer new file mode 100644 index 0000000000000000000000000000000000000000..ad75f0fc5419119a8f36aba983d42c13c6b18c82 GIT binary patch literal 1400 zcmXqLVl6RfVu@M6%*4pVB%q%5F6_1E=f2g~3l{xpxu;~n%f_kI=F#?@mywZ&mBAq2 zklTQhjX9KsO_(Xz)lkGh2*lwM=5|a;2`MTqE>UoFGE_5A0f}-8%fdxnD@sy}@)C0t zLP7!*{8CHG^NX?#l?)U>>X?NkG1WOcDg@={ml(*2^BNc!m>L@x8kkrZTSSTT8Xr?e)pb%`8bxG1NBDgg8$LDi;*&sNkGhRFavNnVeXXnV+ZNSXz>i zUzAx=Y0$)k5>||?49rbT{0u;GE~X|XMuv$mLMC0}3fs7bSLN=}^DgNnGqueZ*D4n< z6z&PWf8>{zP``J*K-k{-1x4Ev>rZ;~i!Zl*yn!Y0-G9O9$G^1Mas9H3`8oNSN!3k} z?B{bfw=QU^DqCMT;rg4uyuaq;{JOuP>5E9+&wWRh>HF8utl#=4-MMHl55u+2*V#Ik z-}cXt5m{aL^l{#w8!MhnQn}@vowOtL@2i7*a<+AU=IfpHWOh#G%pVmV2Ci4vKIFA= zP55IpEl_<=`r%W0+p=G|9Y3zHV55BMJr9muOZ--TYIZYkdHv!{qla_4Uy;`An7uyI z8eK6;)mv82xcTluVDn*4H@{rFnZKrr->NYVceLpZe9OHpX1z|b)cx=i_IqB&9+|z~ zb>^eRQ7T(@tqik0pTFwAXT-h_EB=4kvG%3;?_E2-a9jO+;p`;Wd86gD@W-3GA9g0} z=+OvUBO*J8>v`ep^L%%0S58~#vDfDN`mMZ5J_iIF--KCzyS(U8^!80GNaN+QxRXU2R+|OyuVRJ3p-z1^F zk&nQT$}{_BWZ$b06!4^&QvNEyh26!5W#v54$m zU&mzoYuQJemcF&`EM~m9X=HQ-oQP%l85#exumE#yn*l#axiE;&YQPMn3#pvFxko}c zOOHQR=ZkHrGQ%Gu64I;-<~_|vo9`t L|Is>Mz#<<2E=x9y literal 0 HcmV?d00001 diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_3.cer b/its/plugin/projects/AFNetworking/Tests/Resources/HTTPBin.org/HTTPBinOrgServerTrustChain/httpbin_3.cer new file mode 100644 index 0000000000000000000000000000000000000000..8a99c54a99fbe7d188e8349044bbf835338815b0 GIT binary patch literal 1082 zcmXqLVlgvlVwPLL%*4pV#K>sC%f_kI=F#?@mywZ`mBAq2klTQhjX9KsO_(Xz)lkGh z2*lwM=5|a;2`MTqE>UoFGE_5A0f}-8%fdxnD@sy}@)C0tLP7!*{8CHG^NX?#l?)U> z>X?NkG1WOcDg@={ml(*2^BNc!m>L@x8kkrZTSSTT8XjN?rvBY=YQMRKuAJRO$F&7v$3OVnzc89ta_Yo{keA2e z`77qma!f!mNNh*Jt^yXWhK4aLSy*%>fBq$A#xwu(vU-c)21|O=7}o zpAG)XtF8Q7ZrndN|6ykS?(0t1vt6DXU;8fCF}^6Oki&d)W$Kd11yjtwGwAaknpAY_ zf<@77krl2-Vzp|wZ@G5l-I}w)F56FP-*skC{gt>gGb=(_aQkxO{;<->uV*!{yKU#v zPTh9dDPMHcj_TjoB)8i0+;|888*y*(5iaqn(`z5X>60`I?kALv!$}}rd+fLyRuno|Argo zyVp48xF<9RZun_r`~1&0HR0n8VoUc&{b@g6QQ4_D>yZyTSDWdcPxk_kT$;B1PMzPo zg1<7BuX&gPMRfc2iaj`Z->vky%Gx(yoVK)1E)YoHHJ8oQOX9M2)tNx2g;mKHpY2|F zRQr(GK4IQxdz0%btCw@~I;_sR+uwEg+qWJmC)U6#u3zUbPg2YfRdBYM`MhSY%8iv1 z#fv-a!=w!@B(@at&pLa8Z(g6C^uwMR&8OuJKf3rFV=4A5OW;5LW3PBaw%*G#K73KL eD)|+-^sdfJR+9^zH04H=)QEFmIYLS9(VqS7aYB7*$C}6+`l4KWV4^GTU z%P&eXlroS2iEs%EI{W+jyZ9?OJ1Y2O=4O_prWl$Tn1JM%g>|8FLBWm+F8R5MnRyCf zi8+}mi6xo&c?!X)$)!c9K&q$=Xq&U6ft)xmP_Ln(kpUP)0lDTtuBDN&simo9ltHwi zqJccfWNu*zsBzBuc_l^pIWS{^mdhE)K$M8O78j@Hm1HL71PA*lglFcYBqstLE@mJC zb{r3{mR?3lNkLL(o?d=Yx?EA-7B?Sst|Zh1$a@ju?VVET@jhe86SpVXKW6ZaibQ@k|SnBgJAku#^1TxU-{ z_x#_SNs3#=qzV+BFYJ&sQ=Z2#>t=&SsNkF6c+E|l{^Tx_+9-9#w6s9Vq{Zc6iO21! z|K>P2S}oK6JcZGI!jlCDdV1C`dRDz`)*;$?`KY{%2ufW@24nzyne)4B|5xFhDe`vVfwB zLz|6}m6e^D5zb;V@CPYYVDT_;Gq7Ug1}b1-+++w$^XvxN2AVK+OpIc(p!hAe($_Br zr!>9f{M`JMd=RDY91v{4!N!)}$iv9QXb=K2P@cutz}vucf%^j2HfNAdpvL5)9H_43 zM2J3cVh5&YNcuyhW=LX&q-AGEJ)lN|##WeH7#UeA4a$M;hWf^U3CV^Ma&0IvP=OoB z*d_sWa(;4g0g8zRsvzG9vH&wi6Ka}o;zrH@sO1AN@iQ{`n!MKK&adQmNdCR|=X6!O z^N;u3Qt!>5eXsJ0;?dfLn_hi$TIrVYtwrnZL#diHpX*n?_o{Dh`n_#kt;^#ko13e? z++AkH;9dE^nv8IoTSFbv#5ooWQt_j~DDWJ+VZR^-xpSk*h7w z&X(#tT5?2XjYYU0L+0BW51#3#=2>&Rc%`7X@58BEpEPU@1uX96sFleUxR{z485vdw)TK)uSl9UE%^}`fch26`@xAJ|OL#HgJ-H(be>TqWs=uBRmwfot zUxUJ1qF=J&b3#SSTxWes_3~)A``z$&^RMj{Y0I+tUoo+$IP@HOU3j^I=Z8$)=KyXu zW7DFFUW3B7>dY+rUW(mJwa=^IS(r22ba<$IwC)LX*UwonauWF9_ zp0lbs%26qtaw{FXf>vGQwUSwut#UUj;pdwYwwuxc9skd55({BJqx;e!aGq{UOZ>F8 zB@cyH?bE;beQ%LBzvl&x?CWOzrD5i-p{3KdC@E}ck?OFPUn6m~A#nzaSKwRSqP5CF zZl;`n_r72gx;v9=L56QzyfqUuBLm}NM+18UK47rR@-s62XJKJxVs9`I1MyWsd>#WX zHV$nzMpjmKW<~>1khmZVp8-!3S6Y64Qeu%_a(*syAajEQnUNvuTJJl_*opPiO18aw zq}|5J^z~5Q@CDy8$#;!b{V z@i)_V-`wakI C5GTO^ literal 0 HcmV?d00001 diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/SelfSigned/NoDomains.cer b/its/plugin/projects/AFNetworking/Tests/Resources/SelfSigned/NoDomains.cer new file mode 100644 index 0000000000000000000000000000000000000000..6b6cce65b21e82464a994fba6adf62f91033f9de GIT binary patch literal 747 zcmXqLVtQ`S#CU!IGZP~d6Cch)(a~+BasKOyt0xXl z-dT96N^bKTtv!yyUtYc|vAeJ_ru$`f{|imV=L)Pke@<0|d^-0vr1p97^7l7d<}7Eb zx3tlg^jH2+)g=~t|0#oxn#OjYf7~-e3NrL3vN=3YmAP@-y7!A=&>cMqMrP@rt#Nsx z#xuV9vFv*!-y`4mO!rlA26I%J^XbjYmc6nxR*%oW=y>qiYx&LX7gm?1AO4t>9s9I% zoz0;qHNP%6$Fpb(ihen?b~j`5t@*!>@cvn}Z|_Fnpxf~eW?C1Hy!;P7k85tNCYZ+)5@Bsr}mYKV5 z;`11Av2kd#F|x9VA$XW7w0mq(AHyKi2Rrvogz3O0Hs`KvLdZ(Dk6ZQ6~wg7P<$ l&U`IAmc;PtPVPiMXT~|ay+>B>sAE01`uZC?uH~n%0RVpbD^UOd literal 0 HcmV?d00001 diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/SelfSigned/foobar.com.cer b/its/plugin/projects/AFNetworking/Tests/Resources/SelfSigned/foobar.com.cer new file mode 100644 index 0000000000000000000000000000000000000000..a9ca08eacdf4a860b3968195a0029ee3f66a5faf GIT binary patch literal 747 zcmXqLVtQ`S#CU!IGZP~d6CYP(-PYdE{;!(t>LUMDyb!A~dNqwpaF*et zY0>(}lc#(re#`Y%(E7L5WM($!{{8Qnm>C%u7i$@481MlDUY4Jc@jnX-GZTA*ff$Id z3gYt^aItY{voW%=vNJOxhbA{TG#MF6uN{rBjGvgG*qHxvscT`w_4S-;cR!bx2`m(n zEm+0f&N{obB4i3Q5p zTN>^1rQ~CBIu?3tNN8m^|2b5C{+h=p^NnPWna(mf5%lPB`-}&gJ9F3t&aRuWeS3-G z-H=B2)n6a3INoG|k!;bn&{sudNlqEhmf6Cc>%TM{dDRPJGh{+Cye z%_Q2-gSgeG|T0nf|@GeD}@W4;@Pv lzx~K+m9W*`cV5*6;|0=u+y2>~Tm5-ef%^1nBfrZ*dH@)(EGYm0 literal 0 HcmV?d00001 diff --git a/its/plugin/projects/AFNetworking/Tests/Resources/logo.png b/its/plugin/projects/AFNetworking/Tests/Resources/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..4fc5a3c9104eed904619d378fa48907c200e52e8 GIT binary patch literal 14795 zcmajGWk6Kj7BD4PB*a&T8DgAlJEkL4qNeg|5*zdNiy2HyE}{X@p*Z9@p=jJ!d-3n_{GG;E^r74@BmNnxcR``&AoYG zZcP8dAP;r3bhUGKw}ZnNE-;!~z&+e0839WFvf$+WU$ii{f5Zd`jL+NLnUA0M(FIHY zc@PZ#zd!2a^xvo5+%=*9KfV7Gv75G!Gn7vg>IV04wFEZKn(1OGXK^`KsJT1bRT~a> z{ErkNws3d2n=Ra#K~77UfgNmaX$QNw!Ep%z28*k}+}zD!mQWRWNk#w%ubrJ0AWuOt z(MQ6H3IZas{QL?6qQas=a*xFxi3!VyJ>nM;`46l-+|t7d3UmJttkr*EMIQYt?1eHo zIRh)pLtX7Wp;n5na3_XKrp4|4ofi3j#rF@a)xXjrtnja}d;l?g7hC&(Z1sO`0s3?C z^}mV>4F0S7P#B=^u7F~kU_L-NtH>|Y+-vBXj;be2^r+}M}RZoL=Xb=NFJ#<5(eOT_*&CFIV|l4R1{?(lbZeONF__Z?b3D8`kGy<$l&H-XCQHn*m=>jZY;Jn=u zadH}bLFXXg;V$TGwHsp$s+VE!8u`zSLd1ZZk}w#frE~|N1VEvWE|MB3&AF@g-|;<` zbm>>DS1viPsCvngKHp+zm|^<(&Lwrh~ z-->5FtGok~kNmsFRZn4i!lr}2gP6SzW=(*JKQzRbOx3uGiD>@3qDbFa_xRrB5`$CG zH^j~ZAO97{puN!SY(DQV8ji@>T4SWZ1d_Fs>=II&i`F*V?;F&YvsG)^cR)ixM|}tX zlBqGa{MYO==mN@0r6f$PLn*HXaQ}kav5(45^!%|?Ex-E(6tO)Bm)!2VeTsj#v8ZcU z0$2CFu?fp*{90d*pVRk&&V-6aeuKuI{+m*Ocwh&#!&0a9hqx91VoZAUy@<=BNGZdr z`2hss6v6hDZb>~@&8{k^6iKO|-*f?fRbqc<)_WRHyG3cCmF>gRxc%sc&137ONrTF8 z$6J@m!7!3IH|`a{!iPyrQZ{g;mScpvd|0dDH3EVfK=ik&QwvTTi0%+E?e* zzxyrB(^3mhx!bg-AjR})&uiG#o z@~o839JNi}3@8hIV24M35;>sj>AG^MXq>R$qpkP}x%cn6kwf{PK_|kLa}^2LcW%_( zy~GJ|5!3T(%C8gyVJcs5K=!`I!dMs>&>(=U+|8YoW2Z$|*g3&~qCp9D zfq+=O&RcJxv9$j_U z_;Do;ijwjT#Jydr)AP@u1H=#PHqF5i>8bEwJ5C?$r)xgzr7^1x77MSsyAVGKhSYH6 zthb=KF7d?#EVld}}>(1I!Os)!c0x z*-%}L7G!ZN8Rr_8vv7B|S9`?L3@kzhn&>o(tFy!sfHLb!W$%E-xK`HoC#-a^sFvca zezh{}yy;Qbsc!>}u(;AXcK-=W-nN(S3AGsQEO((A6Xe`EDi3+D3M~=U;UXWe)_xtx3KyjTO;px|s!E|7 z^;iAw;_$Zt+GZjcTD7qx|nyV@Drv=wL8-4_$kR*C!d4 zx9c@~&EbTgOko$rYXyp8UJ==5k(*W<0!i{F)y)#~dlB(mGil{e_nkExmEXAp-ScsD zlmPlp8jj5F)wZD5toc;l_NGJ_`;PGWOi}I-FuFa(&}bi=c@m8_!UGkUq{dz;;s`%h zIM*@mpIsxZoZY^mtktzYwUbZ)J=lE%zvxR`G48#am{-#PH`Y2gok@Ej zY}Z-2D`od;ClyJ#<;Mk{ebc{48O0il&Tp}>d11`c1{|Yl3RYk}*gH$c6P&i=E*vEx zfk`Yy{Lr<)HD zC;l!$3!KeM`+{j6tP@4nxXP5K?(cPHNeA>Gw z%6m;S39UhtCmw7-PzJ*3(^Qfk7JMQu10QX&iD>;Va%t*;2OS?VHI-}br4L~3R1pfa z$pB8kh__g{b4<=0hwnit+$^K^eiwdcM$oUm3JJQLX0TKl?Zm$cEXgIguCK_CWlw*b z#XBC2{aQ3&^)=e#GS&p&V1)<^WUz3vbwOq*)6{*u43hR}3d21Xr=v=Na0bZTiZ49* zNoIaequ;J`*xd-+x1})E_lDFGJMJ&n+zJ-cAu706fcP#*uldqR6n|K1vGFmYxoD>l z%Nq_M^BXvqcS+ACHe#jB7$UgTo2z~l0Yh!{%dVTclI!=hVm*b|)~@bNvLfiC;RHrN z6aa9&P5)&q`p3`Yc?M2d7P?X%*4^nUsqIEx&>tx~Y6%9HK_vGrBlW(J|CL2%VjMg2 z`6{TBiR8nqQM_G5B|o*KkxRf^`TnLYlONk6ZxjgGf19XsU9vQ)Nbb?zCd|9CIoyG` z!|vyn5RmZzFvc}DFELA)Rz%-_}(;#+>@xgU!MP-*%D7S;0yr|Z2#FNp6Kk`(u@JGH1}RSe}Wyp%1o~70k~kw zjN=`LMi{;A>G(!DpOKhg>pvhx(&6GkKX_GzVf$wiIXwn$)LoF}CR4rEpCr1c)I}Hv zg>h7JwZ@4nEU3!5E)w==REd73+giYhz{iy8in{iY% zYmiQiJapvb?tW$eV^w$_BB{7m-dSPBcLS$8m$0XMmWG#E55q>tkYsai;SuN-8JF0RsD+Pk%~3h! zbS~tSO?$wOXB?H@lVL#HKVJI#bUd^iH9sT?q#xuQ40|C%;rL`D=Bs?OBFIWp+REl3 z&VidS+$Tr??Ty7%Dvb0u+VRv)(^}pY-XW9(J1iGScmQz@t7P`m*~$f}54W%WCQJ{k z>}hn%S7P6}n&1_!W^KD8Tc#^HzdP=P9pkDw%Rx7lTAa_SO&@z>QRjIIml(+FS7&6> zT>EG9!u%+cma=1(YA1gACio~v@GZ)9`pg~sEp3||wf2lVQR3jJnQoh`v-i4q7fPtS z&#;>+(_+#unH!c9(YqbD@bcDD=}(U(+W2iXF%;&D*!9}8cEj_<cB+BJ_@@X<{11972_B|zOotH>A{66k zYqdjCV;UqUD|pMbDV$^+e+~#QGz8Fff0a>#kS1g*Qj5%s^btz8) zhlvp`IOZCv=B49oau_$6-uCqhu8 zpeCA9uyt!9m6rSk`r%{xOD2CZul;I2ZNZ5}v*&zdYBH&EMMx#!0^-=M+E@wClifnD za8Ik_T-Y|I)ocNsuL=oKvw9dl^)!B^`&l+@=;g8&Pj@YDXXb0*yBl{+eqmeixg92M zz?AP?X3hR->#2{uX%TLM6sHut7Tl23@$8w{CA*f{v@I!Z z*#SW-oT7pejW)Q0>7Qun&F;r|{$39f;qu}spDC*m5U?t~5_H}7Jv$H{K?0!;xsW90 zwJ+_shE!xnLXg&sL4-qc0y4Qf;2D`-enKq2@Z0VHu2YtkDPm(!tz@8ZA?K*sXI^`) zuQZf0xv`A~n>KE=Xq<-*cYn*ILv109e^lpn)C3(&w4OZxjP0rLU@h5iHjS;>f!{%t zUP8EYa0EX;xd$#GK7l<{vktTgm>GaB3G`Qsm$_bwDfY}m`~3ch=dpf z9!Qk$=3TAlzGyqp$WBP*TC{J;c@9*=F>g3g&DXMb%g2GW24-FS&56nn*>j(1v z)yGj^a*y?xz@9M1fyM{?=SAn3O}*A?$jEhy6xYO%f~rGtn(p~$;=NUVYXM^~)u}-s z&T?Kv&(JmYX1CEX1@-KAG{Xk*`INM5klH?zGuGCi7hGA_&|#ZDHuX?~df0dbQ?rui zNEOP&^j5|^VDL9=a&Jk{-8UriG?G;roi{#XZT1=*F3{XRJB&Rz9J$(~o_T5EvOL|5 z)g{+8WoNTD^`2>z$WZfVM_9f(Fg<$wxeCdBcoZ||KX?)L-`vZ_Z{83RV{6x$%%nsD z9J)GSTB>UEGUWBgVMZ?^%tiGyBFUc(N^6~bOjL{(?Owu$QFXRQ z^!znv$cD=3KxoZYT*25KV=y&eu;Gi2Ofz~Hw8vh0wV+{89u1Hh-e}r?$jioAmq!!a zHr2Sj$>G6#vBuJ)6R`;FeY`Mfvp*vbX>GTqBlc?ySz9tcmU*iT6&xy8YMUQ0t$n(i zefKxZXQPIb0@rV?tO}^jiI$z)U_8+GpZYYNfZ{=v zV$uAw<1Y0as_cy^aJ-;#Ymc>2vQYJ$Zb^<)AF&vSd9Sm(Qb0NPmKUSYIU6aykdNF@ z!gx0Ut*T$fG3~vKx5ZDLEHP^~HpSz)K7tsDspSznA|QOrHr;i+vefXJnNx61E9#wK zxBw@X1}v;|lE&I!(s7ZN4}YcMpqLl)?^o`Vt}?G-9T-wg`jcg`b8IHuuWC;?HFx^h zN0&c%x&J<`s1?}h+~+YN=*xRcCgVyl0MQ&)J@z_=TI3k*MlaG@C(K zUz#3`$obpQG?RX(Mt^<$>|vLeajE$ulbePE#fI~RH9oACS2BRu5~KVO*Plls(B3a= z@^M?dT%%cW#HN4sNa?YEmh170rWJV``do758J3gx|P8+u|AyNPIThI>vHv_fO z=}&tmQuOSLM1&t#<#qNX-)ES!>(dNwGC->ia9UNiXFo|X_EmH|u_RiUd~Rt8Z4RwT zf+Rs%?2!3mAh%-H{Fa_ENRZ^B{$}Ew79mac$`PH$`j-uX^NP^^9wnk2oHo_M+%ZRV zbixdM%^8`_d*Vr|q)57>n#zp6^xR4Co5HW55X{iSka$ zf|thHJ*8YJ-Us2g;p+1Hu4-Kf#KrZ(h7aIGl9XYfj9_-4Oa`^O!rbmNJ+1^b6w+98nT`fX2fM`H4+E3g&_`Wu3|8}kk3^2#cNW) zw&7pU(N1g}TOUn}`JB%lk_x~0P7}fJxH;-RE>-*58Wg|1!TznnPl-m$cv&;YazN z^QFCq&Gp@6v$0=SS+v<~n<6c|Iu9sJCM7LIUSD*g$vI+_b(m;7`^m$;QmV6CbH?hc zR&%QtP}vFe$*Slmf$KG+v>dV9_&Uy~)nkJ zY?I?u##WL~hOXy->25l4%AV|9!deO&Z}A{dL)@<{4}C6F1#(-g-kK|5$&=MCtH)R!J=2sjY4Cko3F}$N2JlrR8Wc- zsqX{r`nV2{s~2U~ogBuC4C2i-nrC-FI+3xr@IcD9OmGn6{@PEsA)Pq5!$f!*U_QT` z6|Vv167fGp^HWiv)pC*CgKm-A011)utqJ9R5)p8v|*&4yXXWTC2P)5xz7`U zg82;EL|z)2xYR#5({Zu7rlS22pE950tgOknY_&Tve3r$2;S zw^>J|qvE9?RT~W}?I}k``V&ohmLtYmRiD=vEF4RJW+k{RVAF19i;P*-a~5rH7VRuM zHhSN&tF@~Q44o}Ji~>>-ATHT!)Ro7Ims~U2W%n%7cghwmxW_fOxY_l-W?uc*Jz%$r zs1IUg$F}-q*9{bJ(>I=gC`TxR^qTVzwJU#Zbaj226JMWVr41N>u{umxplKc<8?n03 zl7leLgGZ%{J68sHAiW$_GnrR0$B;_VF6;Vsx+z6t&&mOZ>N*~q+|KXzBe=1=>vG(d z2Zw8O3vglWfI(O`7J1V5^14&UBVMhN;zNF{{Ux)H9Wz&H%p0K*ZtI{rWq}=f-$0q_ z+@4U~dI!V)F&W%da6YG^fey6;at zn6Pq=b#-F@;|hD{Fp-hAxqX1WW|%>GZPfA=YdrzCMO61k6IjZALq5L<92F|J`-hJ= z2!GLc4(JDIlQr#U-E$&$Y0Ov!d21Fj7k!awnEi7g!FycbkTdCDDPbB8krUFLiR0+h z;SI9hbne9G4cgyS69#%u=q@1HLCj*f#-l5G-Be%YeW`R!sMaUmR9gM1cAJX6{~e_S z=9N#Q#esbQo@(Cuja9HIw+MVbw15A@!Ev_Xm(9Ng(C6T*Ju|m$2tPb)DY04;lAL+; zD_aijA3h15wls1=usJLd?tL7$ok--d9=QUF0ouPI@0%!?K8!Iof3zXD%}lzTXb^qM z$*;$ewD1+EWiQ-l&*q<%7RKh}AeKSd^Qem6wRQb)gL$2mibJ3`dTk5CQ>5|XXB9Ow znXmG}-%DA&^D&lDa ztm(1LPOMN1evYY2g5HZ1bnpX7)el=L)kcgIoE=0&222*G>pwQ*gK-EJ6;E{uWb`YO z46)uNCI9se)tMD=&(sF}*}#(0o0G85Wn2Eww@Sv(p>2E9o~!9U>gvS}C4zLGFHn!* z{pL0XXHssP4ZIu$F>kS&msZQk*x88JnOIsnQTPIoHi6ivi zv#8K=b+IdQj(Z*%Iqve-o|zxvnQqjv?oU~B%{d=wcxPNYmLdQgUALY39p=saFG?ES);W;kkpW$*D(k_A2W#slAei8kYr$e{>)U1nF#b1887gkRpMa;^>6JC)x` z;j9R3oRbK+-mkO|@?_{F?B(nEFm;YDDj!&~MT$Uo9kXZ7m7w}qXwWUWoj&;1Vlaya z_BA(CzEedwX$ge|&Ghp<{;@{=Y-?-?e#@z7(OC0jg@NBR<}|*ZbaM=2+NH+X&d-ZqY~T>~N1s_AG)y-QQw|Bk^S{f(=~rWZU}nc7 zM{4@{P>JHRb1qHOZJ$5mSykE7qdcO`&XKuZ-lxsas|A+AIZ1m#zUy0vw8r zzBX$-sU>`g3ZqmSar{%M^VX;SS*7WC8r+$1x|4SbRe7y$-a~wlt{;}ljxqGnd@~-9 z&4o3r5uGE>uf7gsE<;uaQku4J=3tIBKOH(uR|D%r$f+R8A009@RdSoZ{7|}0RohPE z7@Pp4!I=ctX%hy@;8DXYF4SYt$SAn9gqAlR(q-ZKR#SVPBBokUHXnGCsqjF`y9|wM z`>ePUDZn{T;49olHld7HYZoDPQXbK;-l}St-eW7U_rXi%Bpr{s@@#JfdE!B7Cpu92 zexB*wyW)d`HfbZuQJi_lPlDcB$iEdw%M7|aOoXEo z&)How$2+E_WSq=9cpd1ucSi;=JZrXcg7n(C_i3Y+7Oc;MK6UQYp$O>o7c3F<`kjh5 z{HJl1S%VI>+o7DEduw70FOJ5?2Oi^4r8b_CK4nqnD1q_l;{1BBqjPv>M{tl?dAV6+ zR#Q$ZS-C?Us(D3lzBYomiU5P5DO_ae{q5tkq5hT)17P0_1C4Y{9uHepemV*CUI?ke3Kq^65bh5 zS_1az{qJCk0atxIa*oVB{gx=Gg!M^n+Aq2Wg3^_&t1vS6=U}9%4 zg~E((`ulE-d#P(K2?NKhfWNR#V7GMqD6a}_8GeHPbMy5{VvtVH3?(za>rchc)geR~`;0raQle zkblk!sit?jT@Q+{;J(?LYF2v%qf2d~qX&{vJ48}}zz|4wB;@6+;OP;pIJM zOcoR0dY>Ojp2e=&+DNwovM5NX^4XE+RPbCbHVgM*9UFvf=-DBocwKdcVKT^s2egmF z?JM64{jSxAzxjHlSLz!cv*y*(x-yfg7*azmUe}|PJ|a2;N7?|p&Bg_Um3A$)>Jw>B zc}y zdS_XW>dll-MAenmp@^|TzX8Rv`&ix9?_T6i4mQjoyG0d(PGpIdMM-!on69t95#|*n zARQ%QgA6-Y*KeJ?wSIU*zB;Il^V0A4GYo`>JvSi>Py6;mz>FnQ$|9MyCTC3%vg=dP zh=4>=UzzhA{>RWk0U~W@w{x$yBTc#@6Wn_`iPPZ(shk5Xi5(3~c>DDh-e{F;O#=oZ zbDyC8iIcTDJNUg*-vJ4L?0aX++(pWliMXC;qU~SJd&05XA(DrcX5$j_`q(Kv#h3R@ z7TVz913Qve#w}qtobJ{{9jiK7)s9IE8Kkz0PyG=3)bBr6dMs@af^CuFJ$l%#2i^+! zV~{wH4c* zRObJqrOU!(YTdES1Xru{26Loy13LLs{!>2z>U%xUg-_>1dVMD|`D4aUwi~(?&^l$- zVA^5HJ6WK`wH#C{PadzBmfs2K<(k9W=QNL}!5&kgZntl0-(QY+-zD6Y?}*&D&!GSs z5X{Q;MTB zK8FUkKKf;$=a*BQC0^fXVzZk(z%ADji@H{s;!K6Pw$F!6hp6K|NDkW!#zhCjNno<~ zsf_rv7lu0sF?9zj*F1jTVvwl{ysvaLd#f(OINQ7a%M;=IzDE1nHP%2WYd^AiED%&d z*8JayNGt^^$*rPc=K z+(Rug7twRIPStPnjnUV6hV)G#@HfoC>&nAc?Z|uxYf0v&^%KZq|Rr_lq zB17yPPq$wy1w68{n!jFq(Nj2h>X$>%y2@tjdc8Cy$>}7sE_`odUib%NKns3`pj}Im zHYYzv;;7?Nb#KJ4RSyJeGY_fGNNJtMMJ`Q%bF9VLncQ0-4pkC_Y{c91Bvl9&Oi@Ws zbWodY;YpTUFEvr~;P&GM^d++ijc6p5zg07TMj{S5r0mm8`|86hZDC${yIv7(5WPJ6 zyZK>CBx#WJfLi7{$Tev>K$pymT>wi(*jvNDQ7gjfYotbs=i|)`>ep0<3X`%Z(a4XVH@P0kem+m>ri-Q#b8kx5rXR z@4cYbkygd%%+}SJ_3((%=vgJE^9F%?ru)v8CraUYED)ZX?;=?=Tbl9DmWkg5cBG3G zt&^ecd(a+MU%%+jZP7IBJ9B(1+4Sf!k%h0x{qZ=cd?|HGeq4Zvcp8)6;W$yo0JGWd3k{gp{9dy+x)P7ZE@K%0p zfaeTugKYhi6ckCWLL08_x}HdkTWblF30-@v5H63p2XjNt4@;}|y1kjoq(ib9-npRd%S@^~0lqA7tWfMkeua$|S5C0+re7Bikz9)BG!f z%uXuL0PUolYf(R`X5}Ku=U_xqo`OUg`ksCXlNaMDv~U*@hPW9S6 zXxb}H{V;hoiJB-ipgAs1P(Txo@umG`szOKMRX9gy?~ZHvxowhvdcSA_b=yw@sH5Du zb4g+b5v?Zo1E8g?QgkJ$x!z-Jt@GD}-M(XTM{k-uKJ|=UK~SoFEWu>5!ikh~8*alz zg{zk7@%trIrs3Eq|MZ!X@7OE7_6NW#MxpidjS=dq_l>MS`Q^;Ix8$qeSl)Q+>KsiG zp@zLzsBY)T{OzVKEBkms`-FAQYp2y6|8m`mfQ=~ulfF-E>aS1vAHBra{>02gh^Q{SEHAMU{TTTipTDRRFGnP5rg=GZ@}SUOlG%3h43 zsQST^3?d2q&F6e%#-foj?Nx|)Mro;}io`uJTMN_(9GHd-C>=7}WfTMkk!`sy6Q-8? z-2hJrEsMXIg?Xl2K^|zvV7_v@oRr@54YPU?RIPCuNd7{XHgmyqtkEXAbuZ7G1WNwu ztYM0&lb+(DXEpu|SP-eRCC~?{R`tlB#qP{x^eE@{4oMBXk)+)N;`R8utiDjfRBR4G zd>rBmD@#`>Ly&y9N&rz@p`TErL|chx*I}rke+T+o0q>-cr3OI&y+79{dWzNsCaQ~5 ztb~2@N_kbYk9UlJ(tawVIewd!W$yb@nx5AEn;j3_%Y$AECh5Osf$A^2XNjEhApF$& z>*ikBL)8y!<{QF=QGEP6f(g||FHu;`sjTsuT2NBrxleG2g?7FszWCwk+LN3wts?~i zEBF})xMV1^H%|)?eE5sBj4+IPiYZQXZfV&MVy0UVjur1Z@OxX!7Nq)6)rrNs3w|=2nO=nfQqlQi!}EL4o3#&qnTF7d19e%}C%5R) zK1upyo%QQ36_Mo`9$BuR-LKz`bv8L$D`n!v5Pr;eQ1u(O=dYQC=pCBMyey|2LTo$> z`2D>4SEPtnU$`&bu+bFXtNY9bRkeCoNajR5wGiifNT={4Zl7v;s?GO@i(Prij^xh! zBASzd`%Gcc+rpe}&C`u11ukJaqTz?y8{TgpoJqB%Jk!g0>CN8@i!9^u2%Ov!ym0ws-C8ZK|}} z&aDMD0%li_#HGk${bvh8`ZUbBa-k(^^YB-!8gsSJRN&Ic=l1H0dBar;Ap4a`=wr~=VXARIRP{&-_snLnpH%w*hI?QRS z{<}R+%Num9N?a=Lgb76NPnnezVI@pXW=zaLcPduxa@<2O80rcr> z9vmX@qUZ6E%_28F%)It)`dZI#TJFD{0K30Iw$O%^vrqK*3eo3D+oBWo-#P7{cXA#S zST9Z43_~AENf6a}lMU$j*x-6m7FMHk{H+=1J(QbMW~-w653uV$oFb?x&;OMDv~Qes z1l^KIaj5625NskQnwiMk*&qQ7u&*P+!Int7jpZ6{m@eiidcXKM^J>pVa=Yif%@blf zcI&4vm)0}6f6K3-3GNh5P(&IxY*uI>Y3G(%j?=F6PLE66eKLqUUlG@@(csie^{9Pa z=+{!4a%Gmo3eE~7Dug^7P92|@ixUtW2Vn8SPSa)Idj`jz~RAyYk23g&Q`!|5^`c= zg|V%SY(wNiY>o@tt^04hu51c=&JGLSCP%X4R!}Wg(h=|G+7}r3e3hPM_j;Jtm)4kU zZre;kOkjE^>QNaZ`{@$=3k!*lOQ+TYUJOkrNccQb@JRZ)ObDF7e&&7mU}EQ|L8RR^ z?HCiL&sPIWC1S53Pi_{qY`1n5V9 zO`#dQ_mj^4>waf2T`@VZy80ny|4sh#*`U=i0?c+oq__GGz%l*KwBM=-4MiAN#FA&cU+nar2sbX< zGyEJBb1n((7XxEDN^*))d~>eP`lJvi^F&W?;Kz> zpIbY>pEsR$u&gHI^(0F5yN}J|Mf(m2mKqyqFdOIp-j;4J*>UrA;y|k6;AuHk z_4J;R?s<80;pvMP(#%r@!9hELhlh~|9ST2*mh@?Wj2yUbk(B|*X~1=HLU#Gy;=c@l zs_0?{IKR92_#cCdvrXUv$_(K8_rb+$*T4m2(ib29WAOi^9^E ozf4*?Z;p7XVVC>C#FL0ZY!3!+pMp39fXzIgTj0fsklv;Y7A literal 0 HcmV?d00001 diff --git a/its/plugin/projects/AFNetworking/Tests/Tests-Prefix.pch b/its/plugin/projects/AFNetworking/Tests/Tests-Prefix.pch new file mode 100644 index 00000000..eb2007ec --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests-Prefix.pch @@ -0,0 +1,9 @@ +// +// Prefix header +// +// The contents of this file are implicitly included at the beginning of every source file. +// + +#ifdef __OBJC__ + #import +#endif diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFAutoPurgingImageCacheTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFAutoPurgingImageCacheTests.m new file mode 100644 index 00000000..add2301f --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFAutoPurgingImageCacheTests.m @@ -0,0 +1,233 @@ +// AFAutoPurgingImageCacheTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import "AFAutoPurgingImageCache.h" + +@interface AFAutoPurgingImageCacheTests : XCTestCase +@property (nonatomic, strong) AFAutoPurgingImageCache *cache; +@property (nonatomic, strong) UIImage *testImage; +@end + +@implementation AFAutoPurgingImageCacheTests + +- (void)setUp { + [super setUp]; + self.cache = [[AFAutoPurgingImageCache alloc] initWithMemoryCapacity:100 * 1024 * 1024 + preferredMemoryCapacity:60 * 1024 * 1024]; + + NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:@"logo" ofType:@"png"]; + self.testImage = [UIImage imageWithContentsOfFile:path]; + + +} + +- (void)tearDown { + [self.cache removeAllImages]; + self.cache = nil; + self.testImage = nil; + [super tearDown]; +} + +#pragma mark - Cache Return Images + +- (void)testImageIsReturnedFromCacheForIdentifier { + NSString *identifier = @"logo"; + [self.cache addImage:self.testImage withIdentifier:identifier]; + + UIImage *cachedImage = [self.cache imageWithIdentifier:identifier]; + XCTAssertEqual(self.testImage, cachedImage, @"Cached image should equal original image"); +} + +- (void)testImageIsReturnedFromCacheForURLRequest { + NSURL *url = [NSURL URLWithString:@"http://test.com/image"]; + NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; + [self.cache addImage:self.testImage forRequest:request withAdditionalIdentifier:nil]; + + UIImage *cachedImage = [self.cache imageforRequest:request withAdditionalIdentifier:nil]; + XCTAssertEqual(self.testImage, cachedImage, @"Cached image should equal original image"); +} + +- (void)testImageIsReturnedFromCacheForURLRequestWithAdditionalIdentifier { + NSURL *url = [NSURL URLWithString:@"http://test.com/image"]; + NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; + NSString *additionalIdentifier = @"filter"; + [self.cache addImage:self.testImage forRequest:request withAdditionalIdentifier:additionalIdentifier]; + + UIImage *cachedImage = [self.cache imageforRequest:request withAdditionalIdentifier:additionalIdentifier]; + XCTAssertEqual(self.testImage, cachedImage, @"Cached image should equal original image"); +} + +- (void)testImageIsNotReturnedWhenAdditionalIdentifierIsNotSet { + NSURL *url = [NSURL URLWithString:@"http://test.com/image"]; + NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; + NSString *additionalIdentifier = @"filter"; + [self.cache addImage:self.testImage forRequest:request withAdditionalIdentifier:additionalIdentifier]; + + UIImage *cachedImage = [self.cache imageforRequest:request withAdditionalIdentifier:nil]; + XCTAssertNil(cachedImage, @"cached image should be nil"); +} + +- (void)testImageIsNotReturnedWhenURLDoesntMatch { + NSURL *url = [NSURL URLWithString:@"http://test.com/image"]; + NSURLRequest *originalRequest = [[NSURLRequest alloc] initWithURL:url]; + [self.cache addImage:self.testImage forRequest:originalRequest withAdditionalIdentifier:nil]; + + NSURL *newURL = [NSURL URLWithString:@"http://test.com/differentImage"]; + NSURLRequest *newRequest = [[NSURLRequest alloc] initWithURL:newURL]; + UIImage *cachedImage = [self.cache imageforRequest:newRequest withAdditionalIdentifier:nil]; + XCTAssertNil(cachedImage, @"cached image should be nil"); +} + +- (void)testDuplicateImageAddedToCacheIsReturned { + NSURL *url = [NSURL URLWithString:@"http://test.com/image"]; + NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; + [self.cache addImage:self.testImage forRequest:request withAdditionalIdentifier:nil]; + + NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:@"logo" ofType:@"png"]; + UIImage *newImage = [UIImage imageWithContentsOfFile:path]; + + [self.cache addImage:newImage forRequest:request withAdditionalIdentifier:nil]; + + UIImage *cachedImage = [self.cache imageforRequest:request withAdditionalIdentifier:nil]; + XCTAssertEqual(cachedImage, newImage); + XCTAssertNotEqual(cachedImage, self.testImage); +} + +#pragma mark - Remove Image Tests + +- (void)testImageIsRemovedWithIdentifier { + NSString *identifier = @"logo"; + [self.cache addImage:self.testImage withIdentifier:identifier]; + XCTAssertTrue([self.cache removeImageWithIdentifier:identifier], @"image should be reported as removed"); + XCTAssertFalse([self.cache removeImageWithIdentifier:identifier], @"image should be reported as removed the second time"); + UIImage *cachedImage = [self.cache imageWithIdentifier:identifier]; + XCTAssertNil(cachedImage, @"cached image should be nil"); +} + +- (void)testImageIsRemovedWithURLRequest { + NSURL *url = [NSURL URLWithString:@"http://test.com/image"]; + NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; + [self.cache addImage:self.testImage forRequest:request withAdditionalIdentifier:nil]; + XCTAssertTrue([self.cache removeImageforRequest:request withAdditionalIdentifier:nil], @"image should be reported as removed"); + XCTAssertFalse([self.cache removeImageforRequest:request withAdditionalIdentifier:nil], @"image should be reported as removed the second time"); + UIImage *cachedImage = [self.cache imageforRequest:request withAdditionalIdentifier:nil]; + XCTAssertNil(cachedImage, @"cached image should be nil"); +} + +- (void)testImageIsRemovedWithURLRequestWithAdditionalIdentifier { + NSURL *url = [NSURL URLWithString:@"http://test.com/image"]; + NSString *identifier = @"filter"; + NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; + [self.cache addImage:self.testImage forRequest:request withAdditionalIdentifier:identifier]; + XCTAssertTrue([self.cache removeImageforRequest:request withAdditionalIdentifier:identifier], @"image should be reported as removed"); + XCTAssertFalse([self.cache removeImageforRequest:request withAdditionalIdentifier:identifier], @"image should be reported as removed the second time"); + UIImage *cachedImage = [self.cache imageforRequest:request withAdditionalIdentifier:identifier]; + XCTAssertNil(cachedImage, @"cached image should be nil"); +} + +- (void)testImageIsNotRemovedWithURLRequestAndNilIdentifier { + NSURL *url = [NSURL URLWithString:@"http://test.com/image"]; + NSString *identifier = @"filter"; + NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; + [self.cache addImage:self.testImage forRequest:request withAdditionalIdentifier:identifier]; + XCTAssertFalse([self.cache removeImageforRequest:request withAdditionalIdentifier:nil], @"image should not be reported as removed"); + UIImage *cachedImage = [self.cache imageforRequest:request withAdditionalIdentifier:identifier]; + XCTAssertNotNil(cachedImage, @"cached image should be nil"); +} + +- (void)testImageIsNotRemovedWithURLRequestAndIncorrectIdentifier { + NSURL *url = [NSURL URLWithString:@"http://test.com/image"]; + NSString *identifier = @"filter"; + NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; + [self.cache addImage:self.testImage forRequest:request withAdditionalIdentifier:identifier]; + NSString *differentIdentifier = @"nofilter"; + XCTAssertFalse([self.cache removeImageforRequest:request withAdditionalIdentifier:differentIdentifier], @"image should not be reported as removed"); + UIImage *cachedImage = [self.cache imageforRequest:request withAdditionalIdentifier:identifier]; + XCTAssertNotNil(cachedImage, @"cached image should be nil"); +} + +#pragma mark - Memory Usage +- (void)testThatMemoryUsageIncreasesWhenAddingImage { + NSString *identifier = @"logo"; + XCTAssertTrue(self.cache.memoryUsage == 0); + [self.cache addImage:self.testImage withIdentifier:identifier]; + XCTAssertTrue(self.cache.memoryUsage == 13600); +} + +- (void)testThatMemoryUsageDecreasesWhenRemovingImage { + NSString *identifier = @"logo"; + [self.cache addImage:self.testImage withIdentifier:identifier]; + UInt64 currentUsage = self.cache.memoryUsage; + [self.cache removeImageWithIdentifier:identifier]; + XCTAssertTrue(currentUsage > self.cache.memoryUsage); +} + +#pragma mark - Purging +- (void)testThatImagesArePurgedWhenCapcityIsReached { + UInt64 imageSize = 13600; + NSInteger numberOfImages = 10; + NSInteger numberOfImagesAfterPurge = 6; + self.cache = [[AFAutoPurgingImageCache alloc] initWithMemoryCapacity:numberOfImages * imageSize preferredMemoryCapacity:numberOfImagesAfterPurge * imageSize]; + NSInteger index = 1; + while (YES) { + NSString * identifier = [NSString stringWithFormat:@"image-%ld",(long)index]; + [self.cache addImage:self.testImage withIdentifier:identifier]; + if (index <= numberOfImages) { + XCTAssertTrue(self.cache.memoryUsage == index * imageSize); + } else { + XCTAssertTrue(self.cache.memoryUsage == numberOfImagesAfterPurge * imageSize); + break; + } + index++; + } +} + +- (void)testThatPrioritizedImagesWithOldestLastAccessDatesAreRemovedDuringPurge { + UInt64 imageSize = 13600; + NSInteger numberOfImages = 10; + NSInteger numberOfImagesAfterPurge = 6; + self.cache = [[AFAutoPurgingImageCache alloc] initWithMemoryCapacity:numberOfImages * imageSize preferredMemoryCapacity:numberOfImagesAfterPurge * imageSize]; + for (NSInteger index = 0; index < numberOfImages; index ++) { + NSString * identifier = [NSString stringWithFormat:@"image-%ld",(long)index]; + [self.cache addImage:self.testImage withIdentifier:identifier]; + } + + NSString * firstIdentifier = [NSString stringWithFormat:@"image-%ld",(long)0]; + UIImage *firstImage = [self.cache imageWithIdentifier:firstIdentifier]; + XCTAssertNotNil(firstImage, @"first image should not be nil"); + UInt64 prePurgeMemoryUsage = self.cache.memoryUsage; + [self.cache addImage:self.testImage withIdentifier:[NSString stringWithFormat:@"image-%ld",(long)10]]; + UInt64 postPurgeMemoryUsage = self.cache.memoryUsage; + XCTAssertTrue(postPurgeMemoryUsage < prePurgeMemoryUsage); + + for (NSInteger index = 0; index <= numberOfImages ; index++) { + NSString * identifier = [NSString stringWithFormat:@"image-%ld",(long)index]; + UIImage *cachedImage = [self.cache imageWithIdentifier:identifier]; + if (index == 0 || index >= 6) { + XCTAssertNotNil(cachedImage, @"Image for %@ should be cached", identifier); + } else { + XCTAssertNil(cachedImage, @"Image for %@ should not be cached", identifier); + } + } +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFCompoundResponseSerializerTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFCompoundResponseSerializerTests.m new file mode 100644 index 00000000..247ce8b6 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFCompoundResponseSerializerTests.m @@ -0,0 +1,89 @@ +// AFURLSessionManagerTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import "AFTestCase.h" +#import "AFURLResponseSerialization.h" + +@interface AFCompoundResponseSerializerTests : AFTestCase + +@end + +@implementation AFCompoundResponseSerializerTests + +- (void)setUp { + [super setUp]; + // Put setup code here. This method is called before the invocation of each test method in the class. +} + +- (void)tearDown { + // Put teardown code here. This method is called after the invocation of each test method in the class. + [super tearDown]; +} + +#pragma mark - Compound Serializers + +- (void)testCompoundSerializerProperlySerializesResponse { + + AFImageResponseSerializer *imageSerializer = [AFImageResponseSerializer serializer]; + AFJSONResponseSerializer *jsonSerializer = [AFJSONResponseSerializer serializer]; + AFCompoundResponseSerializer *compoundSerializer = [AFCompoundResponseSerializer compoundSerializerWithResponseSerializers:@[imageSerializer, jsonSerializer]]; + + NSData *data = [NSJSONSerialization dataWithJSONObject:@{@"key":@"value"} options:0 error:nil]; + NSURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"http://test.com"] + statusCode:200 + HTTPVersion:@"1.1" + headerFields:@{@"Content-Type":@"application/json"}]; + + NSError *error = nil; + id responseObject = [compoundSerializer responseObjectForResponse:response data:data error:&error]; + + XCTAssertTrue([responseObject isKindOfClass:[NSDictionary class]]); + XCTAssertNil(error); +} + +- (void)testCompoundSerializerCanBeCopied { + AFImageResponseSerializer *imageSerializer = [AFImageResponseSerializer serializer]; + AFJSONResponseSerializer *jsonSerializer = [AFJSONResponseSerializer serializer]; + AFCompoundResponseSerializer *compoundSerializer = [AFCompoundResponseSerializer compoundSerializerWithResponseSerializers:@[imageSerializer, jsonSerializer]]; + + AFCompoundResponseSerializer *copiedSerializer = [compoundSerializer copy]; + XCTAssertNotEqual(compoundSerializer, copiedSerializer); + XCTAssertTrue(compoundSerializer.responseSerializers.count == copiedSerializer.responseSerializers.count); + XCTAssertTrue([NSStringFromClass([[copiedSerializer.responseSerializers objectAtIndex:0] class]) isEqualToString:NSStringFromClass([AFImageResponseSerializer class])]); + XCTAssertTrue([NSStringFromClass([[copiedSerializer.responseSerializers objectAtIndex:1] class]) isEqualToString:NSStringFromClass([AFJSONResponseSerializer class])]); +} + +- (void)testCompoundSerializerCanBeArchivedAndUnarchived { + AFImageResponseSerializer *imageSerializer = [AFImageResponseSerializer serializer]; + AFJSONResponseSerializer *jsonSerializer = [AFJSONResponseSerializer serializer]; + AFCompoundResponseSerializer *compoundSerializer = [AFCompoundResponseSerializer compoundSerializerWithResponseSerializers:@[imageSerializer, jsonSerializer]]; + NSData *data = [NSKeyedArchiver archivedDataWithRootObject:compoundSerializer]; + XCTAssertNotNil(data); + AFCompoundResponseSerializer *unarchivedSerializer = [NSKeyedUnarchiver unarchiveObjectWithData:data]; + XCTAssertNotNil(unarchivedSerializer); + XCTAssertNotEqual(unarchivedSerializer, compoundSerializer); + XCTAssertTrue(compoundSerializer.responseSerializers.count == compoundSerializer.responseSerializers.count); + XCTAssertTrue([NSStringFromClass([[unarchivedSerializer.responseSerializers objectAtIndex:0] class]) isEqualToString:NSStringFromClass([AFImageResponseSerializer class])]); + XCTAssertTrue([NSStringFromClass([[unarchivedSerializer.responseSerializers objectAtIndex:1] class]) isEqualToString:NSStringFromClass([AFJSONResponseSerializer class])]); +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPRequestSerializationTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPRequestSerializationTests.m new file mode 100644 index 00000000..24ac1062 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPRequestSerializationTests.m @@ -0,0 +1,214 @@ +// AFHTTPRequestSerializationTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFTestCase.h" + +#import "AFURLRequestSerialization.h" + +@interface AFMultipartBodyStream : NSInputStream +@property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts; +@end + +@protocol AFMultipartFormDataTest +@property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream; + +- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest + stringEncoding:(NSStringEncoding)encoding; +@end + +@interface AFHTTPBodyPart : NSObject +@property (nonatomic, assign) NSStringEncoding stringEncoding; +@property (nonatomic, strong) NSDictionary *headers; +@property (nonatomic, copy) NSString *boundary; +@property (nonatomic, strong) id body; +@property (nonatomic, assign) NSUInteger bodyContentLength; +@property (nonatomic, strong) NSInputStream *inputStream; +@property (nonatomic, assign) BOOL hasInitialBoundary; +@property (nonatomic, assign) BOOL hasFinalBoundary; +@property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable; +@property (readonly, nonatomic, assign) NSUInteger contentLength; + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length; +@end + +#pragma mark - + +@interface AFHTTPRequestSerializationTests : AFTestCase +@property (nonatomic, strong) AFHTTPRequestSerializer *requestSerializer; +@end + +@implementation AFHTTPRequestSerializationTests + +- (void)setUp { + [super setUp]; + self.requestSerializer = [AFHTTPRequestSerializer serializer]; +} + +#pragma mark - + +- (void)testThatAFHTTPRequestSerializationSerializesPOSTRequestsProperly { + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]]; + request.HTTPMethod = @"POST"; + + NSURLRequest *serializedRequest = [self.requestSerializer requestBySerializingRequest:request withParameters:@{@"key":@"value"} error:nil]; + NSString *contentType = serializedRequest.allHTTPHeaderFields[@"Content-Type"]; + + XCTAssertNotNil(contentType); + XCTAssertEqualObjects(contentType, @"application/x-www-form-urlencoded"); + + XCTAssertNotNil(serializedRequest.HTTPBody); + XCTAssertEqualObjects(serializedRequest.HTTPBody, [@"key=value" dataUsingEncoding:NSUTF8StringEncoding]); +} + +- (void)testThatAFHTTPRequestSerializationSerializesPOSTRequestsProperlyWhenNoParameterIsProvided { + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]]; + request.HTTPMethod = @"POST"; + + NSURLRequest *serializedRequest = [self.requestSerializer requestBySerializingRequest:request withParameters:nil error:nil]; + NSString *contentType = serializedRequest.allHTTPHeaderFields[@"Content-Type"]; + + XCTAssertNotNil(contentType); + XCTAssertEqualObjects(contentType, @"application/x-www-form-urlencoded"); + + XCTAssertNotNil(serializedRequest.HTTPBody); + XCTAssertEqualObjects(serializedRequest.HTTPBody, [NSData data]); +} + +- (void)testThatAFHTTPRequestSerialiationSerializesQueryParametersCorrectly { + NSURLRequest *originalRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]]; + NSURLRequest *serializedRequest = [self.requestSerializer requestBySerializingRequest:originalRequest withParameters:@{@"key":@"value"} error:nil]; + + XCTAssertTrue([[[serializedRequest URL] query] isEqualToString:@"key=value"], @"Query parameters have not been serialized correctly (%@)", [[serializedRequest URL] query]); +} + +- (void)testThatAFHTTPRequestSerialiationSerializesURLEncodableQueryParametersCorrectly { + NSURLRequest *originalRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]]; + NSURLRequest *serializedRequest = [self.requestSerializer requestBySerializingRequest:originalRequest withParameters:@{@"key":@" :#[]@!$&'()*+,;=/?"} error:nil]; + + XCTAssertTrue([[[serializedRequest URL] query] isEqualToString:@"key=%20%3A%23%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D/?"], @"Query parameters have not been serialized correctly (%@)", [[serializedRequest URL] query]); +} + +- (void)testThatAFHTTPRequestSerialiationSerializesURLEncodedQueryParametersCorrectly { + NSURLRequest *originalRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]]; + NSURLRequest *serializedRequest = [self.requestSerializer requestBySerializingRequest:originalRequest withParameters:@{@"key":@"%20%21%22%23%24%25%26%27%28%29%2A%2B%2C%2F"} error:nil]; + + XCTAssertTrue([[[serializedRequest URL] query] isEqualToString:@"key=%2520%2521%2522%2523%2524%2525%2526%2527%2528%2529%252A%252B%252C%252F"], @"Query parameters have not been serialized correctly (%@)", [[serializedRequest URL] query]); +} + +- (void)testThatAFHTTPRequestSerialiationSerializesQueryParametersCorrectlyFromQuerySerializationBlock { + [self.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) { + __block NSMutableString *query = [NSMutableString stringWithString:@""]; + [parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + [query appendFormat:@"%@**%@",key,obj]; + }]; + + return query; + }]; + + NSURLRequest *originalRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]]; + NSURLRequest *serializedRequest = [self.requestSerializer requestBySerializingRequest:originalRequest withParameters:@{@"key":@"value"} error:nil]; + + XCTAssertTrue([[[serializedRequest URL] query] isEqualToString:@"key**value"], @"Custom Query parameters have not been serialized correctly (%@) by the query string block.", [[serializedRequest URL] query]); +} + +- (void)testThatAFHTTPRequestSerialiationSerializesMIMETypeCorrectly { + NSMutableURLRequest *originalRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]]; + Class streamClass = NSClassFromString(@"AFStreamingMultipartFormData"); + id formData = [[streamClass alloc] initWithURLRequest:originalRequest stringEncoding:NSUTF8StringEncoding]; + + NSURL *fileURL = [NSURL fileURLWithPath:[[NSBundle bundleForClass:[self class]] pathForResource:@"ADNNetServerTrustChain/adn_0" ofType:@"cer"]]; + + [formData appendPartWithFileURL:fileURL name:@"test" error:NULL]; + + AFHTTPBodyPart *part = [formData.bodyStream.HTTPBodyParts firstObject]; + + XCTAssertTrue([part.headers[@"Content-Type"] isEqualToString:@"application/x-x509-ca-cert"], @"MIME Type has not been obtained correctly (%@)", part.headers[@"Content-Type"]); +} + +#pragma mark - + +- (void)testThatValueForHTTPHeaderFieldReturnsSetValue { + [self.requestSerializer setValue:@"Actual Value" forHTTPHeaderField:@"Set-Header"]; + NSString *value = [self.requestSerializer valueForHTTPHeaderField:@"Set-Header"]; + XCTAssertTrue([value isEqualToString:@"Actual Value"]); +} + +- (void)testThatValueForHTTPHeaderFieldReturnsNilForUnsetHeader { + NSString *value = [self.requestSerializer valueForHTTPHeaderField:@"Unset-Header"]; + XCTAssertNil(value); +} + +- (void)testQueryStringSerializationCanFailWithError { + AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer]; + + NSError *serializerError = [NSError errorWithDomain:@"TestDomain" code:0 userInfo:nil]; + + [serializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) { + *error = serializerError; + return nil; + }]; + + NSError *error; + NSURLRequest *request = [serializer requestWithMethod:@"GET" URLString:@"url" parameters:@{} error:&error]; + XCTAssertNil(request); + XCTAssertEqual(error, serializerError); +} + +- (void)testThatHTTPHeaderValueCanBeRemoved { + AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer]; + NSString *headerField = @"TestHeader"; + NSString *headerValue = @"test"; + [serializer setValue:headerValue forHTTPHeaderField:headerField]; + XCTAssertTrue([serializer.HTTPRequestHeaders[headerField] isEqualToString:headerValue]); + [serializer setValue:nil forHTTPHeaderField:headerField]; + XCTAssertFalse([serializer.HTTPRequestHeaders.allKeys containsObject:headerField]); +} + +#pragma mark - Helper Methods + +- (void)testQueryStringFromParameters { + XCTAssertTrue([AFQueryStringFromParameters(@{@"key":@"value",@"key1":@"value&"}) isEqualToString:@"key=value&key1=value%26"]); +} + +- (void)testPercentEscapingString { + XCTAssertTrue([AFPercentEscapedStringFromString(@":#[]@!$&'()*+,;=?/") isEqualToString:@"%3A%23%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D?/"]); +} + +#pragma mark - #3028 tests +//https://github.com/AFNetworking/AFNetworking/pull/3028 + +- (void)testThatEmojiIsProperlyEncoded { + //Start with an odd number of characters so we can cross the 50 character boundry + NSMutableString *parameter = [NSMutableString stringWithString:@"!"]; + while (parameter.length < 50) { + [parameter appendString:@"👴🏿👷🏻👮🏽"]; + } + + AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer]; + NSURLRequest *request = [serializer requestWithMethod:@"GET" + URLString:@"http://test.com" + parameters:@{@"test":parameter} + error:nil]; + XCTAssertTrue([request.URL.query isEqualToString:@"test=%21%F0%9F%91%B4%F0%9F%8F%BF%F0%9F%91%B7%F0%9F%8F%BB%F0%9F%91%AE%F0%9F%8F%BD%F0%9F%91%B4%F0%9F%8F%BF%F0%9F%91%B7%F0%9F%8F%BB%F0%9F%91%AE%F0%9F%8F%BD%F0%9F%91%B4%F0%9F%8F%BF%F0%9F%91%B7%F0%9F%8F%BB%F0%9F%91%AE%F0%9F%8F%BD%F0%9F%91%B4%F0%9F%8F%BF%F0%9F%91%B7%F0%9F%8F%BB%F0%9F%91%AE%F0%9F%8F%BD%F0%9F%91%B4%F0%9F%8F%BF%F0%9F%91%B7%F0%9F%8F%BB%F0%9F%91%AE%F0%9F%8F%BD"]); +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPResponseSerializationTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPResponseSerializationTests.m new file mode 100644 index 00000000..8e0f2cac --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPResponseSerializationTests.m @@ -0,0 +1,89 @@ +// AFHTTPResponseSerializationTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFTestCase.h" + +#import "AFURLResponseSerialization.h" + +@interface AFHTTPResponseSerializationTests : AFTestCase +@property (nonatomic, strong) AFHTTPResponseSerializer *responseSerializer; +@end + +@implementation AFHTTPResponseSerializationTests + +- (void)setUp { + [super setUp]; + self.responseSerializer = [AFHTTPResponseSerializer serializer]; +} + +#pragma mark - + +- (void)testThatAFHTTPResponseSerializationHandlesAll2XXCodes { + NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; + [indexSet enumerateIndexesUsingBlock:^(NSUInteger statusCode, BOOL *stop) { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:statusCode HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/html"}]; + + XCTAssert([self.responseSerializer.acceptableStatusCodes containsIndex:statusCode], @"Status code %@ should be acceptable", @(statusCode)); + + NSError *error = nil; + [self.responseSerializer validateResponse:response data:[@"text" dataUsingEncoding:NSUTF8StringEncoding] error:&error]; + + XCTAssertNil(error, @"Error handling status code %@", @(statusCode)); + }]; +} + +- (void)testThatAFHTTPResponseSerializationFailsAll4XX5XXStatusCodes { + NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(400, 200)]; + [indexSet enumerateIndexesUsingBlock:^(NSUInteger statusCode, BOOL *stop) { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:statusCode HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/html"}]; + + XCTAssert(![self.responseSerializer.acceptableStatusCodes containsIndex:statusCode], @"Status code %@ should not be acceptable", @(statusCode)); + + NSError *error = nil; + [self.responseSerializer validateResponse:response data:[@"text" dataUsingEncoding:NSUTF8StringEncoding] error:&error]; + + XCTAssertNotNil(error, @"Did not fail handling status code %@",@(statusCode)); + }]; +} + +- (void)testResponseIsValidated { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"http://test.com"] + statusCode:200 + HTTPVersion:@"1.1" + headerFields:@{@"Content-Type":@"text/html"}]; + NSData *data = [@"text" dataUsingEncoding:NSUTF8StringEncoding]; + NSError *error = nil; + XCTAssertTrue([self.responseSerializer validateResponse:response data:data error:&error]); +} + +- (void)testCanBeCopied { + AFHTTPResponseSerializer *copiedSerializer = [self.responseSerializer copy]; + XCTAssertNotNil(copiedSerializer); + XCTAssertNotEqual(copiedSerializer, self.responseSerializer); + XCTAssertTrue(copiedSerializer.acceptableContentTypes.count == self.responseSerializer.acceptableContentTypes.count); + XCTAssertTrue(copiedSerializer.acceptableStatusCodes.count == self.responseSerializer.acceptableStatusCodes.count); +} + +- (void)testSupportsSecureCoding { + XCTAssertTrue([AFHTTPResponseSerializer supportsSecureCoding]); +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPSessionManagerTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPSessionManagerTests.m new file mode 100644 index 00000000..7615c822 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFHTTPSessionManagerTests.m @@ -0,0 +1,538 @@ +// AFHTTPSessionManagerTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFTestCase.h" + +#import "AFHTTPSessionManager.h" +#import "AFSecurityPolicy.h" + +@interface AFHTTPSessionManagerTests : AFTestCase +@property (readwrite, nonatomic, strong) AFHTTPSessionManager *manager; +@end + +@implementation AFHTTPSessionManagerTests + +- (void)setUp { + [super setUp]; + self.manager = [[AFHTTPSessionManager alloc] initWithBaseURL:self.baseURL]; +} + +- (void)tearDown { + [self.manager invalidateSessionCancelingTasks:YES]; + [super tearDown]; +} + +#pragma mark - init +- (void)testSharedManagerIsNotEqualToInitdManager { + XCTAssertFalse([[AFHTTPSessionManager manager] isEqual:self.manager]); +} + +#pragma mark - misc + +- (void)testThatOperationInvokesCompletionHandlerWithResponseObjectOnSuccess { + __block id blockResponseObject = nil; + __block id blockError = nil; + + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + + NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/get" relativeToURL:self.baseURL]]; + NSURLSessionDataTask *task = [self.manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + blockResponseObject = responseObject; + blockError = error; + [expectation fulfill]; + }]; + + [task resume]; + + [self waitForExpectationsWithTimeout:10.0 handler:nil]; + + XCTAssertTrue(task.state == NSURLSessionTaskStateCompleted); + XCTAssertNil(blockError); + XCTAssertNotNil(blockResponseObject); +} + +- (void)testThatOperationInvokesFailureCompletionBlockWithErrorOnFailure { + __block id blockError = nil; + + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + + NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/status/404" relativeToURL:self.baseURL]]; + NSURLSessionDataTask *task = [self.manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + blockError = error; + [expectation fulfill]; + }]; + + [task resume]; + + [self waitForExpectationsWithTimeout:10.0 handler:nil]; + + XCTAssertTrue(task.state == NSURLSessionTaskStateCompleted); + XCTAssertNotNil(blockError); +} + +- (void)testThatRedirectBlockIsCalledWhen302IsEncountered { + __block BOOL success; + __block NSError *blockError = nil; + + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + + NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/redirect/1" relativeToURL:self.baseURL]]; + NSURLSessionDataTask *task = [self.manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + blockError = error; + [expectation fulfill]; + }]; + + [self.manager setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest *(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request) { + if (response) { + success = YES; + } + + return request; + }]; + + [task resume]; + + [self waitForExpectationsWithTimeout:10.0 handler:nil]; + + XCTAssertTrue(task.state == NSURLSessionTaskStateCompleted); + XCTAssertNil(blockError); + XCTAssertTrue(success); +} + +- (void)testDownloadFileCompletionSpecifiesURLInCompletionWithManagerDidFinishBlock { + __block BOOL managerDownloadFinishedBlockExecuted = NO; + __block BOOL completionBlockExecuted = NO; + __block NSURL *downloadFilePath = nil; + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + + [self.manager setDownloadTaskDidFinishDownloadingBlock:^NSURL *(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location) { + managerDownloadFinishedBlockExecuted = YES; + NSURL *dirURL = [[[NSFileManager defaultManager] URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject]; + return [dirURL URLByAppendingPathComponent:@"t1.file"]; + }]; + + NSURLSessionDownloadTask *downloadTask; + downloadTask = [self.manager + downloadTaskWithRequest:[NSURLRequest requestWithURL:self.baseURL] + progress:nil + destination:nil + completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { + downloadFilePath = filePath; + completionBlockExecuted = YES; + [expectation fulfill]; + }]; + [downloadTask resume]; + [self waitForExpectationsWithTimeout:10.0 handler:nil]; + XCTAssertTrue(completionBlockExecuted); + XCTAssertTrue(managerDownloadFinishedBlockExecuted); + XCTAssertNotNil(downloadFilePath); +} + +- (void)testDownloadFileCompletionSpecifiesURLInCompletionBlock { + __block BOOL destinationBlockExecuted = NO; + __block BOOL completionBlockExecuted = NO; + __block NSURL *downloadFilePath = nil; + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + + NSURLSessionDownloadTask *downloadTask = [self.manager downloadTaskWithRequest:[NSURLRequest requestWithURL:self.baseURL] + progress:nil + destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { + destinationBlockExecuted = YES; + NSURL *dirURL = [[[NSFileManager defaultManager] URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject]; + return [dirURL URLByAppendingPathComponent:@"t1.file"]; + } + completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { + downloadFilePath = filePath; + completionBlockExecuted = YES; + [expectation fulfill]; + }]; + [downloadTask resume]; + [self waitForExpectationsWithTimeout:10.0 handler:nil]; + XCTAssertTrue(completionBlockExecuted); + XCTAssertTrue(destinationBlockExecuted); + XCTAssertNotNil(downloadFilePath); +} + +- (void)testThatSerializationErrorGeneratesErrorAndNullTaskForGET { + XCTestExpectation *expectation = [self expectationWithDescription:@"Serialization should fail"]; + + [self.manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) { + *error = [NSError errorWithDomain:@"Custom" code:-1 userInfo:nil]; + return @""; + }]; + + NSURLSessionTask *nilTask; + nilTask = [self.manager + GET:@"test" + parameters:@{@"key":@"value"} + progress:nil + success:nil + failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { + XCTAssertNil(task); + [expectation fulfill]; + }]; + XCTAssertNil(nilTask); + [self waitForExpectationsWithTimeout:10.0 handler:nil]; +} + +#pragma mark - NSCoding + +- (void)testSupportsSecureCoding { + XCTAssertTrue([AFHTTPSessionManager supportsSecureCoding]); +} + +- (void)testCanBeEncoded { + NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.manager]; + XCTAssertNotNil(data); +} + +- (void)testCanBeDecoded { + NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.manager]; + AFHTTPSessionManager *newManager = [NSKeyedUnarchiver unarchiveObjectWithData:data]; + XCTAssertNotNil(newManager.securityPolicy); + XCTAssertNotNil(newManager.requestSerializer); + XCTAssertNotNil(newManager.responseSerializer); + XCTAssertNotNil(newManager.baseURL); + XCTAssertNotNil(newManager.session); + XCTAssertNotNil(newManager.session.configuration); +} + +#pragma mark - NSCopying + +- (void)testCanBeCopied { + AFHTTPSessionManager *copyManager = [self.manager copy]; + XCTAssertNotNil(copyManager); +} + +#pragma mark - Progress + +- (void)testDownloadProgressIsReportedForGET { + XCTestExpectation *expectation = [self expectationWithDescription:@"Progress Should equal 1.0"]; + [self.manager + GET:@"image" + parameters:nil + progress:^(NSProgress * _Nonnull downloadProgress) { + if (downloadProgress.fractionCompleted == 1.0) { + [expectation fulfill]; + } + } + success:nil + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testUploadProgressIsReportedForPOST { + NSMutableString *payload = [NSMutableString stringWithString:@"AFNetworking"]; + while ([payload lengthOfBytesUsingEncoding:NSUTF8StringEncoding] < 20000) { + [payload appendString:@"AFNetworking"]; + } + + __weak __block XCTestExpectation *expectation = [self expectationWithDescription:@"Progress Should equal 1.0"]; + + [self.manager + POST:@"post" + parameters:payload + progress:^(NSProgress * _Nonnull uploadProgress) { + if (uploadProgress.fractionCompleted == 1.0) { + [expectation fulfill]; + expectation = nil; + } + } + success:nil + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testUploadProgressIsReportedForStreamingPost { + NSMutableString *payload = [NSMutableString stringWithString:@"AFNetworking"]; + while ([payload lengthOfBytesUsingEncoding:NSUTF8StringEncoding] < 20000) { + [payload appendString:@"AFNetworking"]; + } + + __block __weak XCTestExpectation *expectation = [self expectationWithDescription:@"Progress Should equal 1.0"]; + + [self.manager + POST:@"post" + parameters:nil + constructingBodyWithBlock:^(id _Nonnull formData) { + [formData appendPartWithFileData:[payload dataUsingEncoding:NSUTF8StringEncoding] name:@"AFNetworking" fileName:@"AFNetworking" mimeType:@"text/html"]; + } + progress:^(NSProgress * _Nonnull uploadProgress) { + if (uploadProgress.fractionCompleted == 1.0) { + [expectation fulfill]; + expectation = nil; + } + } + success:nil + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +# pragma mark - HTTP Status Codes + +- (void)testThatSuccessBlockIsCalledFor200 { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + GET:@"status/200" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testThatFailureBlockIsCalledFor404 { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + GET:@"status/404" + parameters:nil + progress:nil + success:nil + failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) { + [expectation fulfill]; + }]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testThatResponseObjectIsEmptyFor204 { + __block id urlResponseObject = nil; + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + GET:@"status/204" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + urlResponseObject = responseObject; + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertNil(urlResponseObject); +} + +#pragma mark - Rest Interface + +- (void)testGET { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + GET:@"get" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTAssertNotNil(responseObject); + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testHEAD { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + HEAD:@"get" + parameters:nil + success:^(NSURLSessionDataTask * _Nonnull task) { + XCTAssertNotNil(task); + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testPOST { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + POST:@"post" + parameters:@{@"key":@"value"} + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTAssertTrue([responseObject[@"form"][@"key"] isEqualToString:@"value"]); + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testPOSTWithConstructingBody { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + POST:@"post" + parameters:@{@"key":@"value"} + constructingBodyWithBlock:^(id _Nonnull formData) { + [formData appendPartWithFileData:[@"Data" dataUsingEncoding:NSUTF8StringEncoding] + name:@"DataName" + fileName:@"DataFileName" + mimeType:@"data"]; + } + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTAssertTrue([responseObject[@"files"][@"DataName"] isEqualToString:@"Data"]); + XCTAssertTrue([responseObject[@"form"][@"key"] isEqualToString:@"value"]); + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testPUT { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + PUT:@"put" + parameters:@{@"key":@"value"} + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTAssertTrue([responseObject[@"form"][@"key"] isEqualToString:@"value"]); + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testDELETE { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + DELETE:@"delete" + parameters:@{@"key":@"value"} + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTAssertTrue([responseObject[@"args"][@"key"] isEqualToString:@"value"]); + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testPATCH { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.manager + PATCH:@"patch" + parameters:@{@"key":@"value"} + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTAssertTrue([responseObject[@"form"][@"key"] isEqualToString:@"value"]); + [expectation fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +#pragma mark - Deprecated Rest Interface + +- (void)testDeprecatedGET { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + [self.manager + GET:@"get" + parameters:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTAssertNotNil(responseObject); + [expectation fulfill]; + } + failure:nil]; +#pragma clang diagnostic pop + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testDeprecatedPOST { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + [self.manager + POST:@"post" + parameters:@{@"key":@"value"} + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTAssertTrue([responseObject[@"form"][@"key"] isEqualToString:@"value"]); + [expectation fulfill]; + } + failure:nil]; +#pragma clang diagnostic pop + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testDeprecatedPOSTWithConstructingBody { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + [self.manager + POST:@"post" + parameters:@{@"key":@"value"} + constructingBodyWithBlock:^(id _Nonnull formData) { + [formData appendPartWithFileData:[@"Data" dataUsingEncoding:NSUTF8StringEncoding] + name:@"DataName" + fileName:@"DataFileName" + mimeType:@"data"]; + } + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTAssertTrue([responseObject[@"files"][@"DataName"] isEqualToString:@"Data"]); + XCTAssertTrue([responseObject[@"form"][@"key"] isEqualToString:@"value"]); + [expectation fulfill]; + } + failure:nil]; +#pragma clang diagnostic pop + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +#pragma mark - Auth + +- (void)testHiddenBasicAuthentication { + __weak XCTestExpectation *expectation = [self expectationWithDescription:@"Request should finish"]; + [self.manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"user" password:@"password"]; + [self.manager + GET:@"hidden-basic-auth/user/password" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + [expectation fulfill]; + } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { + XCTFail(@"Request should succeed"); + [expectation fulfill]; + }]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +# pragma mark - Server Trust + +- (void)testInvalidServerTrustProducesCorrectError { + __weak XCTestExpectation *expectation = [self expectationWithDescription:@"Request should fail"]; + NSURL *googleCertificateURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"google.com" withExtension:@"cer"]; + NSData *googleCertificateData = [NSData dataWithContentsOfURL:googleCertificateURL]; + AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"https://apple.com/"]]; + [manager setResponseSerializer:[AFHTTPResponseSerializer serializer]]; + manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:[NSSet setWithObject:googleCertificateData]]; + [manager + GET:@"AFNetworking/AFNetworking" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + XCTFail(@"Request should fail"); + [expectation fulfill]; + } + failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { + XCTAssertEqualObjects(error.domain, NSURLErrorDomain); + XCTAssertEqual(error.code, NSURLErrorServerCertificateUntrusted); + [expectation fulfill]; + }]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + [manager invalidateSessionCancelingTasks:YES]; +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFImageDownloaderTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFImageDownloaderTests.m new file mode 100644 index 00000000..ac112f6e --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFImageDownloaderTests.m @@ -0,0 +1,428 @@ +// AFImageDownloaderTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFTestCase.h" +#import "AFImageDownloader.h" + +@interface AFImageDownloaderTests : AFTestCase +@property (nonatomic, strong) NSURLRequest *pngRequest; +@property (nonatomic, strong) NSURLRequest *jpegRequest; +@property (nonatomic, strong) AFImageDownloader *downloader; +@end + +@implementation AFImageDownloaderTests + +- (void)setUp { + [super setUp]; + self.downloader = [[AFImageDownloader alloc] init]; + [[AFImageDownloader defaultURLCache] removeAllCachedResponses]; + [[[AFImageDownloader defaultInstance] imageCache] removeAllImages]; + NSURL *pngURL = [NSURL URLWithString:@"https://httpbin.org/image/png"]; + self.pngRequest = [NSURLRequest requestWithURL:pngURL]; + NSURL *jpegURL = [NSURL URLWithString:@"https://httpbin.org/image/jpeg"]; + self.jpegRequest = [NSURLRequest requestWithURL:jpegURL]; +} + +- (void)tearDown { + [self.downloader.sessionManager invalidateSessionCancelingTasks:YES]; + self.downloader = nil; + // Put teardown code here. This method is called after the invocation of each test method in the class. + [super tearDown]; + self.pngRequest = nil; +} + +#pragma mark - Image Download + +- (void)testThatImageDownloaderSingletonCanBeInitialized { + AFImageDownloader *downloader = [AFImageDownloader defaultInstance]; + XCTAssertNotNil(downloader, @"Downloader should not be nil"); +} + +- (void)testThatImageDownloaderCanBeInitializedAndDeinitializedWithActiveDownloads { + [self.downloader downloadImageForURLRequest:self.pngRequest + success:nil + failure:nil]; + self.downloader = nil; + XCTAssertNil(self.downloader, @"Downloader should be nil"); +} + +- (void)testThatImageDownloaderCanDownloadImage { + XCTestExpectation *expectation = [self expectationWithDescription:@"image download should succeed"]; + + __block NSHTTPURLResponse *urlResponse = nil; + __block UIImage *responseImage = nil; + + [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse = response; + responseImage = responseObject; + [expectation fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTAssertNotNil(urlResponse, @"HTTPURLResponse should not be nil"); + XCTAssertNotNil(responseImage, @"Response image should not be nil"); +} + +- (void)testThatItCanDownloadMultipleImagesSimultaneously { + XCTestExpectation *expectation1 = [self expectationWithDescription:@"image 1 download should succeed"]; + __block NSHTTPURLResponse *urlResponse1 = nil; + __block UIImage *responseImage1 = nil; + + [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse1 = response; + responseImage1 = responseObject; + [expectation1 fulfill]; + } + failure:nil]; + + XCTestExpectation *expectation2 = [self expectationWithDescription:@"image 2 download should succeed"]; + __block NSHTTPURLResponse *urlResponse2 = nil; + __block UIImage *responseImage2 = nil; + + [self.downloader + downloadImageForURLRequest:self.jpegRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse2 = response; + responseImage2 = responseObject; + [expectation2 fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTAssertNotNil(urlResponse1, @"HTTPURLResponse should not be nil"); + XCTAssertNotNil(responseImage1, @"Respone image should not be nil"); + + XCTAssertNotNil(urlResponse2, @"HTTPURLResponse should not be nil"); + XCTAssertNotNil(responseImage2, @"Respone image should not be nil"); +} + +- (void)testThatSimultaneouslyRequestsForTheSameAssetReceiveSameResponse { + XCTestExpectation *expectation1 = [self expectationWithDescription:@"image 1 download should succeed"]; + __block NSHTTPURLResponse *urlResponse1 = nil; + __block UIImage *responseImage1 = nil; + + [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse1 = response; + responseImage1 = responseObject; + [expectation1 fulfill]; + } + failure:nil]; + + XCTestExpectation *expectation2 = [self expectationWithDescription:@"image 2 download should succeed"]; + __block NSHTTPURLResponse *urlResponse2 = nil; + __block UIImage *responseImage2 = nil; + + [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse2 = response; + responseImage2 = responseObject; + [expectation2 fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTAssertEqual(urlResponse1, urlResponse2, @"responses should be equal"); + XCTAssertEqual(responseImage2, responseImage2, @"responses should be equal"); +} + +- (void)testThatImageBehindRedirectCanBeDownloaded { + XCTestExpectation *expectation = [self expectationWithDescription:@"image download should succeed"]; + NSURL *redirectURL = [self.jpegRequest URL]; + NSURLRequest *request = [NSURLRequest requestWithURL:redirectURL]; + + __block NSHTTPURLResponse *urlResponse = nil; + __block UIImage *responseImage = nil; + + [self.downloader + downloadImageForURLRequest:request + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse = response; + responseImage = responseObject; + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertNotNil(urlResponse); + XCTAssertNotNil(responseImage); + +} + +#pragma mark - Caching +- (void)testThatResponseIsNilWhenReturnedFromCache { + XCTestExpectation *expectation1 = [self expectationWithDescription:@"image 1 download should succeed"]; + __block NSHTTPURLResponse *urlResponse1 = nil; + __block UIImage *responseImage1 = nil; + + [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse1 = response; + responseImage1 = responseObject; + [expectation1 fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTestExpectation *expectation2 = [self expectationWithDescription:@"image 2 download should succeed"]; + __block NSHTTPURLResponse *urlResponse2 = nil; + __block UIImage *responseImage2 = nil; + + [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse2 = response; + responseImage2 = responseObject; + [expectation2 fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTAssertNotNil(urlResponse1); + XCTAssertNotNil(responseImage1); + XCTAssertNil(urlResponse2); + XCTAssertEqual(responseImage1, responseImage2); +} + +- (void)testThatImageDownloadReceiptIsNilForCachedImage { + XCTestExpectation *expectation1 = [self expectationWithDescription:@"image 1 download should succeed"]; + AFImageDownloadReceipt *receipt1; + receipt1 = [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + [expectation1 fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTestExpectation *expectation2 = [self expectationWithDescription:@"image 2 download should succeed"]; + + AFImageDownloadReceipt *receipt2; + receipt2 = [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + [expectation2 fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTAssertNotNil(receipt1); + XCTAssertNil(receipt2); +} + +- (void)testThatCacheIsIgnoredIfCacheIgnoredInRequest { + XCTestExpectation *expectation1 = [self expectationWithDescription:@"image 1 download should succeed"]; + + __block NSHTTPURLResponse *urlResponse1 = nil; + __block UIImage *responseImage1 = nil; + AFImageDownloadReceipt *receipt1; + receipt1 = [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse1 = response; + responseImage1 = responseObject; + [expectation1 fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTestExpectation *expectation2 = [self expectationWithDescription:@"image 2 download should succeed"]; + NSMutableURLRequest *alteredRequest = [self.pngRequest mutableCopy]; + alteredRequest.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData; + + AFImageDownloadReceipt *receipt2; + __block NSHTTPURLResponse *urlResponse2 = nil; + __block UIImage *responseImage2 = nil; + receipt2 = [self.downloader + downloadImageForURLRequest:alteredRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse2 = response; + responseImage2 = responseObject; + [expectation2 fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTAssertNotNil(receipt1); + XCTAssertNotNil(receipt2); + XCTAssertNotEqual(receipt1, receipt2); + + XCTAssertNotNil(urlResponse1); + XCTAssertNotNil(responseImage1); + + XCTAssertNotNil(urlResponse2); + XCTAssertNotNil(responseImage2); + + XCTAssertNotEqual(responseImage1, responseImage2); +} + +#pragma mark - Cancellation + +- (void)testThatCancellingDownloadCallsCompletionWithCancellationError { + AFImageDownloadReceipt *receipt; + XCTestExpectation *expectation = [self expectationWithDescription:@"image download should fail"]; + __block NSError *responseError = nil; + receipt = [self.downloader + downloadImageForURLRequest:self.pngRequest + success:nil + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + responseError = error; + [expectation fulfill]; + }]; + [self.downloader cancelTaskForImageDownloadReceipt:receipt]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTAssertTrue(responseError.code == NSURLErrorCancelled); + XCTAssertTrue([responseError.domain isEqualToString:NSURLErrorDomain]); +} + +- (void)testThatCancellingDownloadWithMultipleResponseHandlersCancelsFirstYetAllowsSecondToComplete { + XCTestExpectation *expectation1 = [self expectationWithDescription:@"image 1 download should succeed"]; + __block NSHTTPURLResponse *urlResponse = nil; + __block UIImage *responseImage = nil; + + [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + urlResponse = response; + responseImage = responseObject; + [expectation1 fulfill]; + } + failure:nil]; + + XCTestExpectation *expectation2 = [self expectationWithDescription:@"image 2 download should fail"]; + __block NSError *responseError = nil; + AFImageDownloadReceipt *receipt; + receipt = [self.downloader + downloadImageForURLRequest:self.pngRequest + success:nil + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + responseError = error; + [expectation2 fulfill]; + }]; + [self.downloader cancelTaskForImageDownloadReceipt:receipt]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + XCTAssertTrue(responseError.code == NSURLErrorCancelled); + XCTAssertTrue([responseError.domain isEqualToString:NSURLErrorDomain]); + XCTAssertNotNil(urlResponse); + XCTAssertNotNil(responseImage); +} + +- (void)testThatItCanDownloadAndCancelAndDownloadAgain { + NSArray *imageURLStrings = @[ + @"https://secure.gravatar.com/avatar/5a105e8b9d40e1329780d62ea2265d8a?d=identicon", + @"https://secure.gravatar.com/avatar/6a105e8b9d40e1329780d62ea2265d8a?d=identicon", + @"https://secure.gravatar.com/avatar/7a105e8b9d40e1329780d62ea2265d8a?d=identicon", + @"https://secure.gravatar.com/avatar/8a105e8b9d40e1329780d62ea2265d8a?d=identicon", + @"https://secure.gravatar.com/avatar/9a105e8b9d40e1329780d62ea2265d8a?d=identicon" + ]; + + for (NSString *imageURLString in imageURLStrings) { + XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"Request %@ should be cancelled", imageURLString]]; + AFImageDownloadReceipt *receipt = [self.downloader + downloadImageForURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageURLString]] + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + XCTFail(@"Request %@ succeeded when it should have failed", request); + } + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + XCTAssertTrue([error.domain isEqualToString:NSURLErrorDomain]); + XCTAssertTrue([error code] == NSURLErrorCancelled); + [expectation fulfill]; + }]; + [self.downloader cancelTaskForImageDownloadReceipt:receipt]; + } + + for (NSString *imageURLString in imageURLStrings) { + XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"Request %@ should succeed", imageURLString]]; + [self.downloader + downloadImageForURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageURLString]] + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + [expectation fulfill]; + } failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + XCTFail(@"Request %@ failed with error %@", request, error); + }]; + } + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +#pragma mark - Threading +- (void)testThatItAlwaysCallsTheSuccessHandlerOnTheMainQueue { + XCTestExpectation *expectation = [self expectationWithDescription:@"image download should succeed"]; + __block BOOL successIsOnMainThread = false; + [self.downloader + downloadImageForURLRequest:self.pngRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + successIsOnMainThread = [[NSThread currentThread] isMainThread]; + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertTrue(successIsOnMainThread); +} + +- (void)testThatItAlwaysCallsTheFailureHandlerOnTheMainQueue { + NSURL *url = [NSURL URLWithString:@"https://httpbin.org/status/404"]; + NSURLRequest *request = [NSURLRequest requestWithURL:url]; + XCTestExpectation *expectation = [self expectationWithDescription:@"image download should fail"]; + __block BOOL failureIsOnMainThread = false; + [self.downloader + downloadImageForURLRequest:request + success:nil + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + failureIsOnMainThread = [[NSThread currentThread] isMainThread]; + [expectation fulfill]; + }]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertTrue(failureIsOnMainThread); +} + +#pragma mark - misc + +- (void)testThatReceiptIDMatchesReturnedID { + NSUUID *receiptId = [NSUUID UUID]; + AFImageDownloadReceipt *receipt = [self.downloader + downloadImageForURLRequest:self.jpegRequest + withReceiptID:receiptId + success:nil + failure:nil]; + XCTAssertEqual(receiptId, receipt.receiptID); + [self.downloader cancelTaskForImageDownloadReceipt:receipt]; +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFJSONSerializationTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFJSONSerializationTests.m new file mode 100644 index 00000000..1ce27fba --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFJSONSerializationTests.m @@ -0,0 +1,171 @@ +// AFJSONSerializationTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFTestCase.h" + +#import "AFURLRequestSerialization.h" +#import "AFURLResponseSerialization.h" + +static NSData * AFJSONTestData() { + return [NSJSONSerialization dataWithJSONObject:@{@"foo": @"bar"} options:0 error:nil]; +} + +#pragma mark - + +@interface AFJSONRequestSerializationTests : AFTestCase +@property (nonatomic, strong) AFJSONRequestSerializer *requestSerializer; +@end + +@implementation AFJSONRequestSerializationTests + +- (void)setUp { + self.requestSerializer = [[AFJSONRequestSerializer alloc] init]; +} + +#pragma mark - + +- (void)testThatJSONRequestSerializationHandlesParametersDictionary { + NSDictionary *parameters = @{@"key":@"value"}; + NSError *error = nil; + NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:AFNetworkingTestsBaseURLString parameters:parameters error:&error]; + + XCTAssertNil(error, @"Serialization error should be nil"); + + NSString *body = [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]; + + XCTAssertTrue([@"{\"key\":\"value\"}" isEqualToString:body], @"Parameters were not encoded correctly"); +} + +- (void)testThatJSONRequestSerializationHandlesParametersArray { + NSArray *parameters = @[@{@"key":@"value"}]; + NSError *error = nil; + NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:AFNetworkingTestsBaseURLString parameters:parameters error:&error]; + + XCTAssertNil(error, @"Serialization error should be nil"); + + NSString *body = [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]; + + XCTAssertTrue([@"[{\"key\":\"value\"}]" isEqualToString:body], @"Parameters were not encoded correctly"); +} + +@end + +#pragma mark - + +@interface AFJSONResponseSerializationTests : AFTestCase +@property (nonatomic, strong) AFJSONResponseSerializer *responseSerializer; +@end + +@implementation AFJSONResponseSerializationTests + +- (void)setUp { + [super setUp]; + self.responseSerializer = [AFJSONResponseSerializer serializer]; +} + +#pragma mark - + +- (void)testThatJSONResponseSerializerAcceptsApplicationJSONMimeType { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"application/json"}]; + + NSError *error = nil; + [self.responseSerializer validateResponse:response data:AFJSONTestData() error:&error]; + + XCTAssertNil(error, @"Error handling application/json"); +} + +- (void)testThatJSONResponseSerializerAcceptsTextJSONMimeType { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/json"}]; + NSError *error = nil; + [self.responseSerializer validateResponse:response data:AFJSONTestData()error:&error]; + + XCTAssertNil(error, @"Error handling text/json"); +} + +- (void)testThatJSONResponseSerializerAcceptsTextJavaScriptMimeType { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/javascript"}]; + NSError *error = nil; + [self.responseSerializer validateResponse:response data:AFJSONTestData() error:&error]; + + XCTAssertNil(error, @"Error handling text/javascript"); +} + +- (void)testThatJSONResponseSerializerDoesNotAcceptNonStandardJSONMimeType { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"nonstandard/json"}]; + NSError *error = nil; + [self.responseSerializer validateResponse:response data:AFJSONTestData() error:&error]; + + XCTAssertNotNil(error, @"Error should have been thrown for nonstandard/json"); +} + +- (void)testThatJSONResponseSerializerReturnsDictionaryForValidJSONDictionary { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"text/json"}]; + NSError *error = nil; + id responseObject = [self.responseSerializer responseObjectForResponse:response data:AFJSONTestData() error:&error]; + + XCTAssertNil(error, @"Serialization error should be nil"); + XCTAssert([responseObject isKindOfClass:[NSDictionary class]], @"Expected response to be a NSDictionary"); +} + +- (void)testThatJSONResponseSerializerReturnsErrorForInvalidJSON { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type":@"text/json"}]; + NSError *error = nil; + [self.responseSerializer responseObjectForResponse:response data:[@"{invalid}" dataUsingEncoding:NSUTF8StringEncoding] error:&error]; + + XCTAssertNotNil(error, @"Serialization error should not be nil"); +} + +- (void)testThatJSONResponseSerializerReturnsNilObjectAndNilErrorForEmptyData { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type":@"text/json"}]; + NSData *data = [NSData data]; + NSError *error = nil; + id responseObject = [self.responseSerializer responseObjectForResponse:response data:data error:&error]; + XCTAssertNil(responseObject); + XCTAssertNil(error); +} + +- (void)testThatJSONResponseSerializerReturnsNilObjectAndNilErrorForSingleSpace { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type":@"text/json"}]; + NSData *data = [@" " dataUsingEncoding:NSUTF8StringEncoding]; + NSError *error = nil; + id responseObject = [self.responseSerializer responseObjectForResponse:response data:data error:&error]; + XCTAssertNil(responseObject); + XCTAssertNil(error); +} + +- (void)testThatJSONRemovesKeysWithNullValues { + self.responseSerializer.removesKeysWithNullValues = YES; + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:200 HTTPVersion:@"1.1" headerFields:@{@"Content-Type":@"text/json"}]; + NSData *data = [NSJSONSerialization dataWithJSONObject:@{@"key":@"value",@"nullkey":[NSNull null],@"array":@[@{@"subnullkey":[NSNull null]}]} + options:0 + error:nil]; + + NSError *error = nil; + NSDictionary *responseObject = [self.responseSerializer responseObjectForResponse:response + data:data + error:&error]; + XCTAssertNil(error); + XCTAssertNotNil(responseObject[@"key"]); + XCTAssertNil(responseObject[@"nullkey"]); + XCTAssertNil(responseObject[@"array"][0][@"subnullkey"]); +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFNetworkActivityManagerTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFNetworkActivityManagerTests.m new file mode 100644 index 00000000..d12e6467 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFNetworkActivityManagerTests.m @@ -0,0 +1,181 @@ +// AFNetworkActivityManagerTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFTestCase.h" + +#import "AFNetworkActivityIndicatorManager.h" +#import "AFHTTPSessionManager.h" + +@interface AFNetworkActivityManagerTests : AFTestCase +@property (nonatomic, strong) AFNetworkActivityIndicatorManager *networkActivityIndicatorManager; +@property (nonatomic, strong) AFHTTPSessionManager *sessionManager; +@end + +#pragma mark - + +@implementation AFNetworkActivityManagerTests + +- (void)setUp { + [super setUp]; + + self.sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:self.baseURL sessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + + self.networkActivityIndicatorManager = [[AFNetworkActivityIndicatorManager alloc] init]; + self.networkActivityIndicatorManager.enabled = YES; +} + +- (void)tearDown { + [super tearDown]; + self.networkActivityIndicatorManager = nil; + + [self.sessionManager invalidateSessionCancelingTasks:YES]; +} + +#pragma mark - + +- (void)testThatNetworkActivityIndicatorTurnsOnAndOffIndicatorWhenRequestSucceeds { + self.networkActivityIndicatorManager.activationDelay = 0.0; + self.networkActivityIndicatorManager.completionDelay = 0.0; + + XCTestExpectation *startExpectation = [self expectationWithDescription:@"Indicator Visible"]; + XCTestExpectation *endExpectation = [self expectationWithDescription:@"Indicator Hidden"]; + [self.networkActivityIndicatorManager setNetworkingActivityActionWithBlock:^(BOOL networkActivityIndicatorVisible) { + if (networkActivityIndicatorVisible) { + [startExpectation fulfill]; + } else { + [endExpectation fulfill]; + } + }]; + + XCTestExpectation *requestExpectation = [self expectationWithDescription:@"Request should succeed"]; + [self.sessionManager + GET:@"/delay/1" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) { + [requestExpectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testThatNetworkActivityIndicatorTurnsOnAndOffIndicatorWhenRequestFails { + self.networkActivityIndicatorManager.activationDelay = 0.0; + self.networkActivityIndicatorManager.completionDelay = 0.0; + + XCTestExpectation *startExpectation = [self expectationWithDescription:@"Indicator Visible"]; + XCTestExpectation *endExpectation = [self expectationWithDescription:@"Indicator Hidden"]; + [self.networkActivityIndicatorManager setNetworkingActivityActionWithBlock:^(BOOL networkActivityIndicatorVisible) { + if (networkActivityIndicatorVisible) { + [startExpectation fulfill]; + } else { + [endExpectation fulfill]; + } + }]; + + XCTestExpectation *requestExpectation = [self expectationWithDescription:@"Request should fail"]; + [self.sessionManager + GET:@"/status/404" + parameters:nil + progress:nil + success:nil + failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { + [requestExpectation fulfill]; + }]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testThatVisibilityDelaysAreApplied { + + self.networkActivityIndicatorManager.activationDelay = 1.0; + self.networkActivityIndicatorManager.completionDelay = 1.0; + + CFTimeInterval requestStartTime = CACurrentMediaTime(); + __block CFTimeInterval requestEndTime; + __block CFTimeInterval indicatorVisbleTime; + __block CFTimeInterval indicatorHiddenTime; + XCTestExpectation *startExpectation = [self expectationWithDescription:@"Indicator Visible"]; + XCTestExpectation *endExpectation = [self expectationWithDescription:@"Indicator Hidden"]; + [self.networkActivityIndicatorManager setNetworkingActivityActionWithBlock:^(BOOL networkActivityIndicatorVisible) { + if (networkActivityIndicatorVisible) { + indicatorVisbleTime = CACurrentMediaTime(); + [startExpectation fulfill]; + } else { + indicatorHiddenTime = CACurrentMediaTime(); + [endExpectation fulfill]; + } + }]; + + XCTestExpectation *requestExpectation = [self expectationWithDescription:@"Request should succeed"]; + [self.sessionManager + GET:@"/delay/2" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) { + requestEndTime = CACurrentMediaTime(); + [requestExpectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertTrue((indicatorVisbleTime - requestStartTime) > self.networkActivityIndicatorManager.activationDelay); + XCTAssertTrue((indicatorHiddenTime - requestEndTime) > self.networkActivityIndicatorManager.completionDelay); +} + +- (void)testThatIndicatorBlockIsOnlyCalledOnceEachForStartAndEndForMultipleRequests { + self.networkActivityIndicatorManager.activationDelay = 1.0; + self.networkActivityIndicatorManager.completionDelay = 1.0; + + XCTestExpectation *startExpectation = [self expectationWithDescription:@"Indicator Visible"]; + XCTestExpectation *endExpectation = [self expectationWithDescription:@"Indicator Hidden"]; + [self.networkActivityIndicatorManager setNetworkingActivityActionWithBlock:^(BOOL networkActivityIndicatorVisible) { + if (networkActivityIndicatorVisible) { + [startExpectation fulfill]; + } else { + [endExpectation fulfill]; + } + }]; + + XCTestExpectation *requestExpectation = [self expectationWithDescription:@"Request should succeed"]; + [self.sessionManager + GET:@"/delay/4" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) { + [requestExpectation fulfill]; + } + failure:nil]; + + XCTestExpectation *secondRequestExpectation = [self expectationWithDescription:@"Request should succeed"]; + [self.sessionManager + GET:@"/delay/2" + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) { + + [secondRequestExpectation fulfill]; + } + failure:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFNetworkReachabilityManagerTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFNetworkReachabilityManagerTests.m new file mode 100644 index 00000000..05b3c94e --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFNetworkReachabilityManagerTests.m @@ -0,0 +1,124 @@ +// AFNetworkReachabilityManagerTests.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFTestCase.h" + +#import "AFNetworkReachabilityManager.h" +#import + +@interface AFNetworkReachabilityManagerTests : AFTestCase +@property (nonatomic, strong) AFNetworkReachabilityManager *addressReachability; +@property (nonatomic, strong) AFNetworkReachabilityManager *domainReachability; +@end + +@implementation AFNetworkReachabilityManagerTests + +- (void)setUp { + [super setUp]; + + //both of these manager objects should always be reachable when the tests are run + self.domainReachability = [AFNetworkReachabilityManager managerForDomain:@"localhost"]; + self.addressReachability = [AFNetworkReachabilityManager manager]; +} + +- (void)tearDown +{ + [self.addressReachability stopMonitoring]; + [self.domainReachability stopMonitoring]; + + [super tearDown]; +} + +- (void)testAddressReachabilityStartsInUnknownState { + XCTAssertEqual(self.addressReachability.networkReachabilityStatus, AFNetworkReachabilityStatusUnknown, + @"Reachability should start in an unknown state"); +} + +- (void)testDomainReachabilityStartsInUnknownState { + XCTAssertEqual(self.domainReachability.networkReachabilityStatus, AFNetworkReachabilityStatusUnknown, + @"Reachability should start in an unknown state"); +} + +- (void)verifyReachabilityNotificationGetsPostedWithManager:(AFNetworkReachabilityManager *)manager +{ + [self expectationForNotification:AFNetworkingReachabilityDidChangeNotification + object:nil + handler:^BOOL(NSNotification *note) { + AFNetworkReachabilityStatus status; + status = [note.userInfo[AFNetworkingReachabilityNotificationStatusItem] integerValue]; + BOOL reachable = (status == AFNetworkReachabilityStatusReachableViaWiFi + || status == AFNetworkReachabilityStatusReachableViaWWAN); + + if (reachable) { + XCTAssert(reachable, + @"Expected network to be reachable but got '%@'", + AFStringFromNetworkReachabilityStatus(status)); + XCTAssertEqual(reachable, manager.isReachable, @"Expected status to match 'isReachable'"); + } + + return reachable; + }]; + + [manager startMonitoring]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testAddressReachabilityNotification { + [self verifyReachabilityNotificationGetsPostedWithManager:self.addressReachability]; +} + +//Commenting out for Travis Stability +//- (void)testDomainReachabilityNotification { +// [self verifyReachabilityNotificationGetsPostedWithManager:self.domainReachability]; +//} + +- (void)verifyReachabilityStatusBlockGetsCalledWithManager:(AFNetworkReachabilityManager *)manager +{ + __weak XCTestExpectation *expectation = [self expectationWithDescription:@"reachability status change block gets called"]; + + typeof(manager) __weak weakManager = manager; + [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { + BOOL reachable = (status == AFNetworkReachabilityStatusReachableViaWiFi + || status == AFNetworkReachabilityStatusReachableViaWWAN); + + XCTAssert(reachable, @"Expected network to be reachable but got '%@'", AFStringFromNetworkReachabilityStatus(status)); + XCTAssertEqual(reachable, weakManager.isReachable, @"Expected status to match 'isReachable'"); + + [expectation fulfill]; + }]; + + [manager startMonitoring]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + [manager setReachabilityStatusChangeBlock:nil]; + +} + +- (void)testAddressReachabilityBlock { + [self verifyReachabilityStatusBlockGetsCalledWithManager:self.addressReachability]; +} + +- (void)testDomainReachabilityBlock { + [self verifyReachabilityStatusBlockGetsCalledWithManager:self.domainReachability]; +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFPropertyListResponseSerializerTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFPropertyListResponseSerializerTests.m new file mode 100644 index 00000000..9a9212bf --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFPropertyListResponseSerializerTests.m @@ -0,0 +1,66 @@ +// AFPropertyListResponseSerializerTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFTestCase.h" + +#import "AFURLResponseSerialization.h" + +@interface AFPropertyListResponseSerializerTests : AFTestCase +@property (nonatomic, strong) AFPropertyListResponseSerializer *responseSerializer; +@end + +@implementation AFPropertyListResponseSerializerTests + +- (void)setUp { + [super setUp]; + self.responseSerializer = [AFPropertyListResponseSerializer serializer]; +} + +#pragma mark - + +- (void)testThatPropertyListResponseSerializerHandles204 { + NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.baseURL statusCode:204 HTTPVersion:@"1.1" headerFields:@{@"Content-Type": @"application/x-plist"}]; + NSError *error; + id responseObject = [self.responseSerializer responseObjectForResponse:response data:nil error:&error]; + + XCTAssertNil(responseObject, @"Response should be nil when handling 204 with application/x-plist"); + XCTAssertNil(error, @"Error handling application/x-plist"); +} + +- (void)testResponseSerializerCanBeCopied { + AFPropertyListResponseSerializer *copiedSerializer = [self.responseSerializer copy]; + XCTAssertNotNil(copiedSerializer); + XCTAssertNotEqual(copiedSerializer, self.responseSerializer); + XCTAssertTrue(copiedSerializer.format == self.responseSerializer.format); + XCTAssertTrue(copiedSerializer.readOptions == self.responseSerializer.readOptions); +} + +- (void)testResponseSerializerCanBeArchivedAndUnarchived { + NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:self.responseSerializer]; + XCTAssertNotNil(archive); + AFPropertyListResponseSerializer *unarchivedSerializer = [NSKeyedUnarchiver unarchiveObjectWithData:archive]; + XCTAssertNotNil(unarchivedSerializer); + XCTAssertNotEqual(unarchivedSerializer, self.responseSerializer); + XCTAssertTrue(unarchivedSerializer.format == self.responseSerializer.format); + XCTAssertTrue(unarchivedSerializer.readOptions == self.responseSerializer.readOptions); +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFSecurityPolicyTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFSecurityPolicyTests.m new file mode 100644 index 00000000..4d660eb5 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFSecurityPolicyTests.m @@ -0,0 +1,654 @@ +// AFSecurityPolicyTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFTestCase.h" +#import "AFSecurityPolicy.h" + +@interface AFSecurityPolicyTests : AFTestCase + +@end + +static SecTrustRef AFUTTrustChainForCertsInDirectory(NSString *directoryPath) { + NSArray *certFileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:nil]; + NSMutableArray *certs = [NSMutableArray arrayWithCapacity:[certFileNames count]]; + for (NSString *path in certFileNames) { + NSData *certData = [NSData dataWithContentsOfFile:[directoryPath stringByAppendingPathComponent:path]]; + SecCertificateRef cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); + [certs addObject:(__bridge id)(cert)]; + } + + SecPolicyRef policy = SecPolicyCreateBasicX509(); + SecTrustRef trust = NULL; + SecTrustCreateWithCertificates((__bridge CFTypeRef)(certs), policy, &trust); + CFRelease(policy); + + return trust; +} + +static SecTrustRef AFUTHTTPBinOrgServerTrust() { + NSString *bundlePath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] resourcePath]; + NSString *serverCertDirectoryPath = [bundlePath stringByAppendingPathComponent:@"HTTPBinOrgServerTrustChain"]; + + return AFUTTrustChainForCertsInDirectory(serverCertDirectoryPath); +} + +static SecTrustRef AFUTADNNetServerTrust() { + NSString *bundlePath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] resourcePath]; + NSString *serverCertDirectoryPath = [bundlePath stringByAppendingPathComponent:@"ADNNetServerTrustChain"]; + + return AFUTTrustChainForCertsInDirectory(serverCertDirectoryPath); +} + +static SecTrustRef AFUTGoogleComServerTrustPath1() { + NSString *bundlePath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] resourcePath]; + NSString *serverCertDirectoryPath = [bundlePath stringByAppendingPathComponent:@"GoogleComServerTrustChainPath1"]; + + return AFUTTrustChainForCertsInDirectory(serverCertDirectoryPath); +} + +static SecTrustRef AFUTGoogleComServerTrustPath2() { + NSString *bundlePath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] resourcePath]; + NSString *serverCertDirectoryPath = [bundlePath stringByAppendingPathComponent:@"GoogleComServerTrustChainPath2"]; + + return AFUTTrustChainForCertsInDirectory(serverCertDirectoryPath); +} + +static SecCertificateRef AFUTHTTPBinOrgCertificate() { + NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"httpbinorg_01192017" ofType:@"cer"]; + NSCAssert(certPath != nil, @"Path for certificate should not be nil"); + NSData *certData = [NSData dataWithContentsOfFile:certPath]; + + return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); +} + +static SecCertificateRef AFUTCOMODORSADomainValidationSecureServerCertificate() { + NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"COMODO_RSA_Domain_Validation_Secure_Server_CA" ofType:@"cer"]; + NSCAssert(certPath != nil, @"Path for certificate should not be nil"); + NSData *certData = [NSData dataWithContentsOfFile:certPath]; + + return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); +} + +static SecCertificateRef AFUTCOMODORSACertificate() { + NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"COMODO_RSA_Certification_Authority" ofType:@"cer"]; + NSCAssert(certPath != nil, @"Path for certificate should not be nil"); + NSData *certData = [NSData dataWithContentsOfFile:certPath]; + + return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); +} + +static SecCertificateRef AFUTAddTrustExternalRootCertificate() { + NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"AddTrust_External_CA_Root" ofType:@"cer"]; + NSCAssert(certPath != nil, @"Path for certificate should not be nil"); + NSData *certData = [NSData dataWithContentsOfFile:certPath]; + + return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); +} + +static SecCertificateRef AFUTGoogleComEquifaxSecureCARootCertificate() { + NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"Equifax_Secure_Certificate_Authority_Root" ofType:@"cer"]; + NSCAssert(certPath != nil, @"Path for certificate should not be nil"); + NSData *certData = [NSData dataWithContentsOfFile:certPath]; + + return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); +} + +static SecCertificateRef AFUTGoogleComGeoTrustGlobalCARootCertificate() { + NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"GeoTrust_Global_CA_Root" ofType:@"cer"]; + NSCAssert(certPath != nil, @"Path for certificate should not be nil"); + NSData *certData = [NSData dataWithContentsOfFile:certPath]; + + return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); +} + +static SecCertificateRef AFUTSelfSignedCertificateWithoutDomain() { + NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"NoDomains" ofType:@"cer"]; + NSCAssert(certPath != nil, @"Path for certificate should not be nil"); + NSData *certData = [NSData dataWithContentsOfFile:certPath]; + + return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); +} + +static SecCertificateRef AFUTSelfSignedCertificateWithCommonNameDomain() { + NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"foobar.com" ofType:@"cer"]; + NSCAssert(certPath != nil, @"Path for certificate should not be nil"); + NSData *certData = [NSData dataWithContentsOfFile:certPath]; + + return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); +} + +static SecCertificateRef AFUTSelfSignedCertificateWithDNSNameDomain() { + NSString *certPath = [[NSBundle bundleForClass:[AFSecurityPolicyTests class]] pathForResource:@"AltName" ofType:@"cer"]; + NSCAssert(certPath != nil, @"Path for certificate should not be nil"); + NSData *certData = [NSData dataWithContentsOfFile:certPath]; + + return SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); +} + +static SecTrustRef AFUTTrustWithCertificate(SecCertificateRef certificate) { + NSArray *certs = @[(__bridge id)(certificate)]; + + SecPolicyRef policy = SecPolicyCreateBasicX509(); + SecTrustRef trust = NULL; + SecTrustCreateWithCertificates((__bridge CFTypeRef)(certs), policy, &trust); + CFRelease(policy); + + return trust; +} + +@implementation AFSecurityPolicyTests + +#pragma mark - Default Policy Tests +#pragma mark Default Values Test + +- (void)testDefaultPolicyPinningModeIsSetToNone { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + XCTAssertTrue(policy.SSLPinningMode == AFSSLPinningModeNone, @"Pinning Mode should be set to by default"); +} + +- (void)testDefaultPolicyHasInvalidCertificatesAreDisabledByDefault { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + XCTAssertFalse(policy.allowInvalidCertificates, @"Invalid Certificates Should Be Disabled by Default"); +} + +- (void)testDefaultPolicyHasDomainNamesAreValidatedByDefault { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + XCTAssertTrue(policy.validatesDomainName, @"Domain names should be validated by default"); +} + +- (void)testDefaultPolicyHasNoPinnedCertificates { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + XCTAssertTrue(policy.pinnedCertificates.count == 0, @"The default policy should not have any pinned certificates"); +} + +#pragma mark Positive Server Trust Evaluation Tests + +- (void)testDefaultPolicyDoesAllowHTTPBinOrgCertificate { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + SecTrustRef trust = AFUTHTTPBinOrgServerTrust(); + XCTAssertTrue([policy evaluateServerTrust:trust forDomain:nil], @"Valid Certificate should be allowed by default."); +} + +- (void)testDefaultPolicyDoesAllowHTTPBinOrgCertificateForValidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + SecTrustRef trust = AFUTHTTPBinOrgServerTrust(); + XCTAssertTrue([policy evaluateServerTrust:trust forDomain:@"httpbin.org"], @"Valid Certificate should be allowed by default."); +} + +#pragma mark Negative Server Trust Evaluation Tests + +- (void)testDefaultPolicyDoesNotAllowInvalidCertificate { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + SecCertificateRef certificate = AFUTSelfSignedCertificateWithoutDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + XCTAssertFalse([policy evaluateServerTrust:trust forDomain:nil], @"Invalid Certificates should not be allowed"); +} + +- (void)testDefaultPolicyDoesNotAllowCertificateWithInvalidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + SecTrustRef trust = AFUTHTTPBinOrgServerTrust(); + XCTAssertFalse([policy evaluateServerTrust:trust forDomain:@"apple.com"], @"Certificate should not be allowed because the domain names do not match."); +} + +#pragma mark - Public Key Pinning Tests +#pragma mark Default Values Tests + +- (void)testPolicyWithPublicKeyPinningModeHasPinnedCertificates { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + XCTAssertTrue(policy.pinnedCertificates > 0, @"Policy should contain default pinned certificates"); +} + +- (void)testPolicyWithPublicKeyPinningModeHasHTTPBinOrgPinnedCertificate { + NSBundle *bundle = [NSBundle bundleForClass:[self class]]; + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey withPinnedCertificates:[AFSecurityPolicy certificatesInBundle:bundle]]; + + SecCertificateRef cert = AFUTHTTPBinOrgCertificate(); + NSData *certData = (__bridge NSData *)(SecCertificateCopyData(cert)); + CFRelease(cert); + NSSet *set = [policy.pinnedCertificates objectsPassingTest:^BOOL(NSData *data, BOOL *stop) { + return [data isEqualToData:certData]; + }]; + + XCTAssertEqual(set.count, 1, @"HTTPBin.org certificate not found in the default certificates"); +} + +#pragma mark Positive Server Trust Evaluation Tests +- (void)testPolicyWithPublicKeyPinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgLeafCertificatePinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef certificate = AFUTHTTPBinOrgCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow server trust"); +} + +- (void)testPolicyWithPublicKeyPinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgIntermediate1CertificatePinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef certificate = AFUTCOMODORSADomainValidationSecureServerCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow server trust"); +} + +- (void)testPolicyWithPublicKeyPinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgIntermediate2CertificatePinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef certificate = AFUTCOMODORSACertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow server trust"); +} + +- (void)testPolicyWithPublicKeyPinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgRootCertificatePinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef certificate = AFUTAddTrustExternalRootCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow server trust"); +} + +- (void)testPolicyWithPublicKeyPinningAllowsHTTPBinOrgServerTrustWithEntireCertificateChainPinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef httpBinCertificate = AFUTHTTPBinOrgCertificate(); + SecCertificateRef intermedaite1Certificate = AFUTCOMODORSADomainValidationSecureServerCertificate(); + SecCertificateRef intermedaite2Certificate = AFUTCOMODORSACertificate(); + SecCertificateRef rootCertificate = AFUTAddTrustExternalRootCertificate(); + [policy setPinnedCertificates:[NSSet setWithObjects:(__bridge_transfer NSData *)SecCertificateCopyData(httpBinCertificate), + (__bridge_transfer NSData *)SecCertificateCopyData(intermedaite1Certificate), + (__bridge_transfer NSData *)SecCertificateCopyData(intermedaite2Certificate), + (__bridge_transfer NSData *)SecCertificateCopyData(rootCertificate), nil]]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow HTTPBinOrg server trust because at least one of the pinned certificates is valid"); + +} + +- (void)testPolicyWithPublicKeyPinningAllowsHTTPBirnOrgServerTrustWithHTTPbinOrgPinnedCertificateAndAdditionalPinnedCertificates { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef httpBinCertificate = AFUTHTTPBinOrgCertificate(); + SecCertificateRef selfSignedCertificate = AFUTSelfSignedCertificateWithCommonNameDomain(); + [policy setPinnedCertificates:[NSSet setWithObjects:(__bridge_transfer NSData *)SecCertificateCopyData(httpBinCertificate), + (__bridge_transfer NSData *)SecCertificateCopyData(selfSignedCertificate), nil]]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow HTTPBinOrg server trust because at least one of the pinned certificates is valid"); +} + +- (void)testPolicyWithPublicKeyPinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgLeafCertificatePinnedAndValidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef certificate = AFUTHTTPBinOrgCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:@"httpbin.org"], @"Policy should allow server trust"); +} + +#pragma mark Negative Server Trust Evaluation Tests + +- (void)testPolicyWithPublicKeyPinningAndNoPinnedCertificatesDoesNotAllowHTTPBinOrgServerTrust { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + policy.pinnedCertificates = [NSSet set]; + XCTAssertFalse([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should not allow server trust because the policy is set to public key pinning and it does not contain any pinned certificates."); +} + +- (void)testPolicyWithPublicKeyPinningDoesNotAllowADNServerTrustWithHTTPBinOrgPinnedCertificate { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef certificate = AFUTHTTPBinOrgCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertFalse([policy evaluateServerTrust:AFUTADNNetServerTrust() forDomain:nil], @"Policy should not allow ADN server trust for pinned HTTPBin.org certificate"); +} + +- (void)testPolicyWithPublicKeyPinningDoesNotAllowHTTPBinOrgServerTrustWithHTTPBinOrgLeafCertificatePinnedAndInvalidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef certificate = AFUTHTTPBinOrgCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertFalse([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:@"invaliddomainname.com"], @"Policy should not allow server trust"); +} + +- (void)testPolicyWithPublicKeyPinningDoesNotAllowADNServerTrustWithMultipleInvalidPinnedCertificates { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef httpBinCertificate = AFUTHTTPBinOrgCertificate(); + SecCertificateRef selfSignedCertificate = AFUTSelfSignedCertificateWithCommonNameDomain(); + [policy setPinnedCertificates:[NSSet setWithObjects:(__bridge_transfer NSData *)SecCertificateCopyData(httpBinCertificate), + (__bridge_transfer NSData *)SecCertificateCopyData(selfSignedCertificate), nil]]; + XCTAssertFalse([policy evaluateServerTrust:AFUTADNNetServerTrust() forDomain:nil], @"Policy should not allow ADN server trust because there are no matching pinned certificates"); +} + +#pragma mark - Certificate Pinning Tests +#pragma mark Default Values Tests + +- (void)testPolicyWithCertificatePinningModeHasPinnedCertificates { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + XCTAssertTrue(policy.pinnedCertificates > 0, @"Policy should contain default pinned certificates"); +} + +- (void)testPolicyWithCertificatePinningModeHasHTTPBinOrgPinnedCertificate { + NSBundle *bundle = [NSBundle bundleForClass:[self class]]; + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:[AFSecurityPolicy certificatesInBundle:bundle]]; + + SecCertificateRef cert = AFUTHTTPBinOrgCertificate(); + NSData *certData = (__bridge NSData *)(SecCertificateCopyData(cert)); + CFRelease(cert); + NSSet *set = [policy.pinnedCertificates objectsPassingTest:^BOOL(NSData *data, BOOL *stop) { + return [data isEqualToData:certData]; + }]; + + XCTAssertEqual(set.count, 1, @"HTTPBin.org certificate not found in the default certificates"); +} + +#pragma mark Positive Server Trust Evaluation Tests +- (void)testPolicyWithCertificatePinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgLeafCertificatePinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef certificate = AFUTHTTPBinOrgCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow server trust"); +} + +- (void)testPolicyWithCertificatePinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgIntermediate1CertificatePinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef certificate = AFUTCOMODORSADomainValidationSecureServerCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow server trust"); +} + +- (void)testPolicyWithCertificatePinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgIntermediate2CertificatePinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef certificate = AFUTCOMODORSACertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow server trust"); +} + +- (void)testPolicyWithCertificatePinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgRootCertificatePinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef certificate = AFUTAddTrustExternalRootCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow server trust"); +} + +- (void)testPolicyWithCertificatePinningAllowsHTTPBinOrgServerTrustWithEntireCertificateChainPinned { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef httpBinCertificate = AFUTHTTPBinOrgCertificate(); + SecCertificateRef intermedaite1Certificate = AFUTCOMODORSADomainValidationSecureServerCertificate(); + SecCertificateRef intermedaite2Certificate = AFUTCOMODORSACertificate(); + SecCertificateRef rootCertificate = AFUTAddTrustExternalRootCertificate(); + [policy setPinnedCertificates:[NSSet setWithObjects:(__bridge_transfer NSData *)SecCertificateCopyData(httpBinCertificate), + (__bridge_transfer NSData *)SecCertificateCopyData(intermedaite1Certificate), + (__bridge_transfer NSData *)SecCertificateCopyData(intermedaite2Certificate), + (__bridge_transfer NSData *)SecCertificateCopyData(rootCertificate), nil]]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow HTTPBinOrg server trust because at least one of the pinned certificates is valid"); + +} + +- (void)testPolicyWithCertificatePinningAllowsHTTPBirnOrgServerTrustWithHTTPbinOrgPinnedCertificateAndAdditionalPinnedCertificates { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef httpBinCertificate = AFUTHTTPBinOrgCertificate(); + SecCertificateRef selfSignedCertificate = AFUTSelfSignedCertificateWithCommonNameDomain(); + [policy setPinnedCertificates:[NSSet setWithObjects:(__bridge_transfer NSData *)SecCertificateCopyData(httpBinCertificate), + (__bridge_transfer NSData *)SecCertificateCopyData(selfSignedCertificate), nil]]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should allow HTTPBinOrg server trust because at least one of the pinned certificates is valid"); +} + +- (void)testPolicyWithCertificatePinningAllowsHTTPBinOrgServerTrustWithHTTPBinOrgLeafCertificatePinnedAndValidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef certificate = AFUTHTTPBinOrgCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:@"httpbin.org"], @"Policy should allow server trust"); +} + +//- (void)testPolicyWithCertificatePinningAllowsGoogleComServerTrustIncompleteChainWithRootCertificatePinnedAndValidDomainName { +// //TODO THIS TEST HAS BEEN DISABLED UNTIL CERTS HAVE BEEN UPDATED. +// //Please see conversation here: https://github.com/AFNetworking/AFNetworking/pull/3159#issuecomment-178647437 +// // +// // Fix certificate validation for servers providing incomplete chains (#3159) - test case +// // +// // google.com has two certification paths and both send incomplete certificate chains, i.e. don't include the Root CA +// // (this can be validated in https://www.ssllabs.com/ssltest/analyze.html?d=google.com) +// // +// // The two certification paths are: +// // - Path 1: *.google.com, Google Internet Authority G2 (with GeoTrust Global CA Root) +// // - Path 2: *.google.com, Google Internet Authority G2, GeoTrust Global CA (cross signed) (with Equifax Secure CA Root) +// // +// // The common goal of using certificate pinning is to prevent MiTM (man-in-the-middle) attacks, so the Root CA's should be pinned to protect the entire chains. +// // Since there's no Root CA being sent, when `-evaluateServerTrust:` invokes `AFCertificateTrustChainForServerTrust(serverTrust)`, the Root CA isn't present +// // Therefore, even though `AFServerTrustIsValid(serverTrust)` succeeds, the next validation fails since no pinned certificate matches the `pinnedCertificates`. +// // By fetching the `AFCertificateTrustChainForServerTrust(serverTrust)` *after* the `AFServerTrustIsValid(serverTrust)` validation, the complete chain is obtained and the Root CA's match. +// +// AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; +// +// // certification path 1 +// SecCertificateRef certificate = AFUTGoogleComGeoTrustGlobalCARootCertificate(); +// policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; +// +// XCTAssertTrue([policy evaluateServerTrust:AFUTGoogleComServerTrustPath1() forDomain:@"google.com"], @"Policy should allow server trust"); +// +// // certification path 2 +// certificate = AFUTGoogleComEquifaxSecureCARootCertificate(); +// policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; +// +// XCTAssertTrue([policy evaluateServerTrust:AFUTGoogleComServerTrustPath2() forDomain:@"google.com"], @"Policy should allow server trust"); +//} + +#pragma mark Negative Server Trust Evaluation Tests + +- (void)testPolicyWithCertificatePinningAndNoPinnedCertificatesDoesNotAllowHTTPBinOrgServerTrust { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + policy.pinnedCertificates = [NSSet set]; + XCTAssertFalse([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:nil], @"Policy should not allow server trust because the policy does not contain any pinned certificates."); +} + +- (void)testPolicyWithCertificatePinningDoesNotAllowADNServerTrustWithHTTPBinOrgPinnedCertificate { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef certificate = AFUTHTTPBinOrgCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertFalse([policy evaluateServerTrust:AFUTADNNetServerTrust() forDomain:nil], @"Policy should not allow ADN server trust for pinned HTTPBin.org certificate"); +} + +- (void)testPolicyWithCertificatePinningDoesNotAllowHTTPBinOrgServerTrustWithHTTPBinOrgLeafCertificatePinnedAndInvalidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef certificate = AFUTHTTPBinOrgCertificate(); + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(certificate)]; + XCTAssertFalse([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:@"invaliddomainname.com"], @"Policy should not allow server trust"); +} + +- (void)testPolicyWithCertificatePinningDoesNotAllowADNServerTrustWithMultipleInvalidPinnedCertificates { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef httpBinCertificate = AFUTHTTPBinOrgCertificate(); + SecCertificateRef selfSignedCertificate = AFUTSelfSignedCertificateWithCommonNameDomain(); + [policy setPinnedCertificates:[NSSet setWithObjects:(__bridge_transfer NSData *)SecCertificateCopyData(httpBinCertificate), + (__bridge_transfer NSData *)SecCertificateCopyData(selfSignedCertificate), nil]]; + XCTAssertFalse([policy evaluateServerTrust:AFUTADNNetServerTrust() forDomain:nil], @"Policy should not allow ADN server trust because there are no matching pinned certificates"); +} + +#pragma mark - Domain Name Validation Tests +#pragma mark Positive Evaluation Tests + +- (void)testThatPolicyWithoutDomainNameValidationAllowsServerTrustWithInvalidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + [policy setValidatesDomainName:NO]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:@"invalid.org"], @"Policy should allow server trust because domain name validation is disabled"); +} + +- (void)testThatPolicyWithDomainNameValidationAllowsServerTrustWithValidWildcardDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + XCTAssertTrue([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:@"test.httpbin.org"], @"Policy should allow server trust"); +} + +- (void)testThatPolicyWithDomainNameValidationAndSelfSignedCommonNameCertificateAllowsServerTrust { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef certificate = AFUTSelfSignedCertificateWithCommonNameDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + [policy setPinnedCertificates:[NSSet setWithObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]]; + [policy setAllowInvalidCertificates:YES]; + + XCTAssertTrue([policy evaluateServerTrust:trust forDomain:@"foobar.com"], @"Policy should allow server trust"); +} + +- (void)testThatPolicyWithDomainNameValidationAndSelfSignedDNSCertificateAllowsServerTrust { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + + SecCertificateRef certificate = AFUTSelfSignedCertificateWithDNSNameDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + [policy setPinnedCertificates:[NSSet setWithObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]]; + [policy setAllowInvalidCertificates:YES]; + + XCTAssertTrue([policy evaluateServerTrust:trust forDomain:@"foobar.com"], @"Policy should allow server trust"); +} + +#pragma mark Negative Evaluation Tests + +- (void)testThatPolicyWithDomainNameValidationDoesNotAllowServerTrustWithInvalidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + XCTAssertFalse([policy evaluateServerTrust:AFUTHTTPBinOrgServerTrust() forDomain:@"invalid.org"], @"Policy should not allow allow server trust"); +} + +- (void)testThatPolicyWithDomainNameValidationAndSelfSignedNoDomainCertificateDoesNotAllowServerTrust { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + + SecCertificateRef certificate = AFUTSelfSignedCertificateWithoutDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + [policy setPinnedCertificates:[NSSet setWithObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]]; + [policy setAllowInvalidCertificates:YES]; + + XCTAssertFalse([policy evaluateServerTrust:trust forDomain:@"foobar.com"], @"Policy should not allow server trust"); +} + +#pragma mark - Self Signed Certificate Tests +#pragma mark Positive Test Cases + +- (void)testThatPolicyWithInvalidCertificatesAllowedAllowsSelfSignedServerTrust { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + [policy setAllowInvalidCertificates:YES]; + + SecCertificateRef certificate = AFUTSelfSignedCertificateWithDNSNameDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + + XCTAssertTrue([policy evaluateServerTrust:trust forDomain:nil], @"Policy should allow server trust because invalid certificates are allowed"); +} + +- (void)testThatPolicyWithInvalidCertificatesAllowedAndValidPinnedCertificatesDoesAllowSelfSignedServerTrustForValidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + [policy setAllowInvalidCertificates:YES]; + SecCertificateRef certificate = AFUTSelfSignedCertificateWithDNSNameDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + [policy setPinnedCertificates:[NSSet setWithObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]]; + + XCTAssertTrue([policy evaluateServerTrust:trust forDomain:@"foobar.com"], @"Policy should allow server trust because invalid certificates are allowed"); +} + +- (void)testThatPolicyWithInvalidCertificatesAllowedAndNoSSLPinningAndDomainNameValidationDisabledDoesAllowSelfSignedServerTrustForValidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; + [policy setAllowInvalidCertificates:YES]; + [policy setValidatesDomainName:NO]; + + SecCertificateRef certificate = AFUTSelfSignedCertificateWithDNSNameDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + + XCTAssertTrue([policy evaluateServerTrust:trust forDomain:@"foobar.com"], @"Policy should allow server trust because invalid certificates are allowed"); +} + +#pragma mark Negative Test Cases + +- (void)testThatPolicyWithInvalidCertificatesDisabledDoesNotAllowSelfSignedServerTrust { + AFSecurityPolicy *policy = [AFSecurityPolicy defaultPolicy]; + + SecCertificateRef certificate = AFUTSelfSignedCertificateWithDNSNameDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + + XCTAssertFalse([policy evaluateServerTrust:trust forDomain:nil], @"Policy should not allow server trust because invalid certificates are not allowed"); +} + +- (void)testThatPolicyWithInvalidCertificatesAllowedAndNoPinnedCertificatesAndPublicKeyPinningModeDoesNotAllowSelfSignedServerTrustForValidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey]; + [policy setAllowInvalidCertificates:YES]; + [policy setPinnedCertificates:[NSSet set]]; + SecCertificateRef certificate = AFUTSelfSignedCertificateWithDNSNameDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + + XCTAssertFalse([policy evaluateServerTrust:trust forDomain:@"foobar.com"], @"Policy should not allow server trust because invalid certificates are allowed but there are no pinned certificates"); +} + +- (void)testThatPolicyWithInvalidCertificatesAllowedAndValidPinnedCertificatesAndNoPinningModeDoesNotAllowSelfSignedServerTrustForValidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; + [policy setAllowInvalidCertificates:YES]; + SecCertificateRef certificate = AFUTSelfSignedCertificateWithDNSNameDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + [policy setPinnedCertificates:[NSSet setWithObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]]; + + XCTAssertFalse([policy evaluateServerTrust:trust forDomain:@"foobar.com"], @"Policy should not allow server trust because invalid certificates are allowed but there are no pinned certificates"); +} + +- (void)testThatPolicyWithInvalidCertificatesAllowedAndNoValidPinnedCertificatesAndNoPinningModeAndDomainValidationDoesNotAllowSelfSignedServerTrustForValidDomainName { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; + [policy setAllowInvalidCertificates:YES]; + [policy setPinnedCertificates:[NSSet set]]; + + SecCertificateRef certificate = AFUTSelfSignedCertificateWithDNSNameDomain(); + SecTrustRef trust = AFUTTrustWithCertificate(certificate); + + XCTAssertFalse([policy evaluateServerTrust:trust forDomain:@"foobar.com"], @"Policy should not allow server trust because invalid certificates are allowed but there are no pinned certificates"); +} + +#pragma mark - NSCopying +- (void)testThatPolicyCanBeCopied { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + policy.allowInvalidCertificates = YES; + policy.validatesDomainName = NO; + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(AFUTHTTPBinOrgCertificate())]; + + AFSecurityPolicy *copiedPolicy = [policy copy]; + XCTAssertNotEqual(copiedPolicy, policy); + XCTAssertEqual(copiedPolicy.allowInvalidCertificates, policy.allowInvalidCertificates); + XCTAssertEqual(copiedPolicy.validatesDomainName, policy.validatesDomainName); + XCTAssertEqual(copiedPolicy.SSLPinningMode, policy.SSLPinningMode); + XCTAssertTrue([copiedPolicy.pinnedCertificates isEqualToSet:policy.pinnedCertificates]); +} + +- (void)testThatPolicyCanBeEncodedAndDecoded { + AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; + policy.allowInvalidCertificates = YES; + policy.validatesDomainName = NO; + policy.pinnedCertificates = [NSSet setWithObject:(__bridge_transfer id)SecCertificateCopyData(AFUTHTTPBinOrgCertificate())]; + + NSMutableData *archiveData = [NSMutableData new]; + NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:archiveData]; + [archiver encodeObject:policy forKey:@"policy"]; + [archiver finishEncoding]; + + NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:archiveData]; + AFSecurityPolicy *unarchivedPolicy = [unarchiver decodeObjectOfClass:[AFSecurityPolicy class] forKey:@"policy"]; + + XCTAssertNotEqual(unarchivedPolicy, policy); + XCTAssertEqual(unarchivedPolicy.allowInvalidCertificates, policy.allowInvalidCertificates); + XCTAssertEqual(unarchivedPolicy.validatesDomainName, policy.validatesDomainName); + XCTAssertEqual(unarchivedPolicy.SSLPinningMode, policy.SSLPinningMode); + XCTAssertTrue([unarchivedPolicy.pinnedCertificates isEqualToSet:policy.pinnedCertificates]); +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFTestCase.h b/its/plugin/projects/AFNetworking/Tests/Tests/AFTestCase.h new file mode 100644 index 00000000..4f0d02ec --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFTestCase.h @@ -0,0 +1,33 @@ +// AFTestCase.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +extern NSString * const AFNetworkingTestsBaseURLString; + +@interface AFTestCase : XCTestCase + +@property (nonatomic, strong, readonly) NSURL *baseURL; +@property (nonatomic, assign) NSTimeInterval networkTimeout; + +- (void)waitForExpectationsWithCommonTimeoutUsingHandler:(XCWaitCompletionHandler)handler; + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFTestCase.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFTestCase.m new file mode 100644 index 00000000..489c8ab0 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFTestCase.m @@ -0,0 +1,47 @@ +// AFTestCase.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFTestCase.h" + +NSString * const AFNetworkingTestsBaseURLString = @"https://httpbin.org/"; + +@implementation AFTestCase + +- (void)setUp { + [super setUp]; + self.networkTimeout = 20.0; +} + +- (void)tearDown { + [super tearDown]; +} + +#pragma mark - + +- (NSURL *)baseURL { + return [NSURL URLWithString:AFNetworkingTestsBaseURLString]; +} + +- (void)waitForExpectationsWithCommonTimeoutUsingHandler:(XCWaitCompletionHandler)handler { + [self waitForExpectationsWithTimeout:self.networkTimeout handler:handler]; +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFUIActivityIndicatorViewTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIActivityIndicatorViewTests.m new file mode 100644 index 00000000..89202f3e --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIActivityIndicatorViewTests.m @@ -0,0 +1,111 @@ +// AFUIActivityIndicatorViewTests.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFTestCase.h" +#import "UIActivityIndicatorView+AFNetworking.h" +#import "AFURLSessionManager.h" + +@interface AFUIActivityIndicatorViewTests : AFTestCase +@property (nonatomic, strong) NSURLRequest *request; +@property (nonatomic, strong) UIActivityIndicatorView *activityIndicatorView; +@property (nonatomic, strong) AFURLSessionManager *sessionManager; +@end + +@implementation AFUIActivityIndicatorViewTests + +- (void)setUp { + [super setUp]; + self.activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]; + self.request = [NSURLRequest requestWithURL:[self.baseURL URLByAppendingPathComponent:@"delay/1"]]; + self.sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:nil]; +} + +- (void)tearDown { + [super tearDown]; + [self.sessionManager invalidateSessionCancelingTasks:YES]; + self.sessionManager = nil; +} + +- (void)testTaskDidResumeNotificationDoesNotCauseCrashForAIVWithTask { + XCTestExpectation *expectation = [self expectationWithDescription:@"No Crash"]; + [self expectationForNotification:AFNetworkingTaskDidResumeNotification object:nil handler:nil]; + NSURLSessionDataTask *task = [self.sessionManager + dataTaskWithRequest:self.request + completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + [expectation fulfill]; + }]; + + [self.activityIndicatorView setAnimatingWithStateOfTask:task]; + self.activityIndicatorView = nil; + + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + [task cancel]; +} + + +- (void)testTaskDidCompleteNotificationDoesNotCauseCrashForAIVWithTask { + XCTestExpectation *expectation = [self expectationWithDescription:@"No Crash"]; + [self expectationForNotification:AFNetworkingTaskDidCompleteNotification object:nil handler:nil]; + NSURLSessionDataTask *task = [self.sessionManager + dataTaskWithRequest:self.request + completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + //Without the dispatch after, this test would PASS errorenously because the test + //would finish before the notification was posted to all objects that were + //observing it. + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [expectation fulfill]; + }); + }]; + + [self.activityIndicatorView setAnimatingWithStateOfTask:task]; + self.activityIndicatorView = nil; + + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + [task cancel]; +} + +- (void)testTaskDidSuspendNotificationDoesNotCauseCrashForAIVWithTask { + XCTestExpectation *expectation = [self expectationWithDescription:@"No Crash"]; + [self expectationForNotification:AFNetworkingTaskDidSuspendNotification object:nil handler:nil]; + NSURLSessionDataTask *task = [self.sessionManager + dataTaskWithRequest:self.request + completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + //Without the dispatch after, this test would PASS errorenously because the test + //would finish before the notification was posted to all objects that were + //observing it. + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [expectation fulfill]; + }); + }]; + + [self.activityIndicatorView setAnimatingWithStateOfTask:task]; + self.activityIndicatorView = nil; + + [task resume]; + [task suspend]; + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + [task cancel]; +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFUIButtonTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIButtonTests.m new file mode 100644 index 00000000..6aea93b0 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIButtonTests.m @@ -0,0 +1,115 @@ +// AFUIButtonTests.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import "AFTestCase.h" +#import "UIButton+AFNetworking.h" +#import "AFImageDownloader.h" + +@interface AFUIButtonTests : AFTestCase +@property (nonatomic, strong) UIImage *cachedImage; +@property (nonatomic, strong) NSURLRequest *cachedImageRequest; +@property (nonatomic, strong) UIButton *button; + +@property (nonatomic, strong) NSURL *error404URL; +@property (nonatomic, strong) NSURLRequest *error404URLRequest; + +@property (nonatomic, strong) NSURL *jpegURL; +@property (nonatomic, strong) NSURLRequest *jpegURLRequest; +@end + +@implementation AFUIButtonTests + +- (void)setUp { + [super setUp]; + [[UIButton sharedImageDownloader].imageCache removeAllImages]; + [[[[[[UIButton sharedImageDownloader] sessionManager] session] configuration] URLCache] removeAllCachedResponses]; + [UIButton setSharedImageDownloader:[[AFImageDownloader alloc] init]]; + + self.button = [UIButton new]; + + self.jpegURL = [NSURL URLWithString:@"https://httpbin.org/image/jpeg"]; + self.jpegURLRequest = [NSURLRequest requestWithURL:self.jpegURL]; + + self.error404URL = [NSURL URLWithString:@"https://httpbin.org/status/404"]; + self.error404URLRequest = [NSURLRequest requestWithURL:self.error404URL]; + +} + +- (void)tearDown { + self.button = nil; + [super tearDown]; + +} + +- (void)testThatBackgroundImageChanges { + XCTAssertNil([self.button backgroundImageForState:UIControlStateNormal]); + [self.button setBackgroundImageForState:UIControlStateNormal withURL:self.jpegURL]; + NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(UIButton * _Nonnull button, NSDictionary * _Nullable bindings) { + return [button backgroundImageForState:UIControlStateNormal] != nil; + }]; + + [self expectationForPredicate:predicate + evaluatedWithObject:self.button + handler:nil]; + + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testThatForegroundImageCanBeCancelledAndDownloadedImmediately { + //https://github.com/Alamofire/AlamofireImage/issues/55 + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.button setImageForState:UIControlStateNormal withURL:self.jpegURL]; + [self.button cancelImageDownloadTaskForState:UIControlStateNormal]; + __block UIImage *responseImage; + [self.button + setImageForState:UIControlStateNormal + withURLRequest:self.jpegURLRequest + placeholderImage:nil + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) { + responseImage = image; + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertNotNil(responseImage); +} + +- (void)testThatBackgroundImageCanBeCancelledAndDownloadedImmediately { + //https://github.com/Alamofire/AlamofireImage/issues/55 + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.button setBackgroundImageForState:UIControlStateNormal withURL:self.jpegURL]; + [self.button cancelBackgroundImageDownloadTaskForState:UIControlStateNormal]; + __block UIImage *responseImage; + [self.button + setBackgroundImageForState:UIControlStateNormal + withURLRequest:self.jpegURLRequest + placeholderImage:nil + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) { + responseImage = image; + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertNotNil(responseImage); +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFUIImageViewTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIImageViewTests.m new file mode 100644 index 00000000..9261fc5c --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIImageViewTests.m @@ -0,0 +1,155 @@ +// AFUIImageViewTests.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFTestCase.h" +#import "UIImageView+AFNetworking.h" +#import "AFImageDownloader.h" + +@interface AFUIImageViewTests : AFTestCase +@property (nonatomic, strong) UIImage *cachedImage; +@property (nonatomic, strong) NSURLRequest *cachedImageRequest; +@property (nonatomic, strong) UIImageView *imageView; + +@property (nonatomic, strong) NSURL *error404URL; +@property (nonatomic, strong) NSURLRequest *error404URLRequest; + +@property (nonatomic, strong) NSURL *jpegURL; +@property (nonatomic, strong) NSURLRequest *jpegURLRequest; + +@end + +@implementation AFUIImageViewTests + +- (void)setUp { + [super setUp]; + [[UIImageView sharedImageDownloader].imageCache removeAllImages]; + [[[[[[UIImageView sharedImageDownloader] sessionManager] session] configuration] URLCache] removeAllCachedResponses]; + [UIImageView setSharedImageDownloader:[[AFImageDownloader alloc] init]]; + + self.imageView = [UIImageView new]; + + self.jpegURL = [NSURL URLWithString:@"https://httpbin.org/image/jpeg"]; + self.jpegURLRequest = [NSURLRequest requestWithURL:self.jpegURL]; + + self.error404URL = [NSURL URLWithString:@"https://httpbin.org/status/404"]; + self.error404URLRequest = [NSURLRequest requestWithURL:self.error404URL]; + +} + +- (void)tearDown { + self.imageView = nil; + [super tearDown]; + +} + +- (void)testThatImageCanBeDownloadedFromURL { + XCTAssertNil(self.imageView.image); + [self.imageView setImageWithURL:self.jpegURL]; + [self expectationForPredicate:[NSPredicate predicateWithFormat:@"image != nil"] + evaluatedWithObject:self.imageView + handler:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testThatImageDownloadSucceedsWhenDuplicateRequestIsSentToImageView { + XCTAssertNil(self.imageView.image); + [self.imageView setImageWithURL:self.jpegURL]; + [self.imageView setImageWithURL:self.jpegURL]; + [self expectationForPredicate:[NSPredicate predicateWithFormat:@"image != nil"] + evaluatedWithObject:self.imageView + handler:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testThatPlaceholderImageIsSetIfRequestFails { + UIImage *placeholder = [UIImage imageNamed:@"logo"]; + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should fail"]; + + [self.imageView setImageWithURLRequest:self.error404URLRequest + placeholderImage:placeholder + success:nil + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + [expectation fulfill]; + }]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertEqual(self.imageView.image, placeholder); +} + +- (void)testResponseIsNilWhenLoadedFromCache { + AFImageDownloader *downloader = [UIImageView sharedImageDownloader]; + XCTestExpectation *cacheExpectation = [self expectationWithDescription:@"Cache request should succeed"]; + __block UIImage *downloadImage = nil; + [downloader + downloadImageForURLRequest:self.jpegURLRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + downloadImage = responseObject; + [cacheExpectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + + __block UIImage *cachedImage = nil; + __block NSHTTPURLResponse *urlResponse; + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.imageView + setImageWithURLRequest:self.jpegURLRequest + placeholderImage:nil + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) { + urlResponse = response; + cachedImage = image; + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertNil(urlResponse); + XCTAssertNotNil(cachedImage); + XCTAssertEqual(cachedImage, downloadImage); +} + +- (void)testThatImageCanBeCancelledAndDownloadedImmediately { + //https://github.com/Alamofire/AlamofireImage/issues/55 + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.imageView setImageWithURL:self.jpegURL]; + [self.imageView cancelImageDownloadTask]; + __block UIImage *responseImage; + [self.imageView + setImageWithURLRequest:self.jpegURLRequest + placeholderImage:nil + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) { + responseImage = image; + [expectation fulfill]; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + XCTAssertNotNil(responseImage); +} + +- (void)testThatNilURLDoesntCrash { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnonnull" + [self.imageView setImageWithURL:nil]; +#pragma clang diagnostic pop + +} + + + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFUIRefreshControlTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIRefreshControlTests.m new file mode 100644 index 00000000..6459fc1b --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIRefreshControlTests.m @@ -0,0 +1,110 @@ +// AFUIRefreshControlTests.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFTestCase.h" +#import "UIRefreshControl+AFNetworking.h" +#import "AFURLSessionManager.h" + +@interface AFUIRefreshControlTests : AFTestCase +@property (nonatomic, strong) NSURLRequest *request; +@property (nonatomic, strong) UIRefreshControl *refreshControl; +@property (nonatomic, strong) AFURLSessionManager *sessionManager; +@end + +@implementation AFUIRefreshControlTests + +- (void)setUp { + [super setUp]; + self.refreshControl = [[UIRefreshControl alloc] init]; + self.request = [NSURLRequest requestWithURL:[self.baseURL URLByAppendingPathComponent:@"delay/1"]]; + self.sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:nil]; +} + +- (void)tearDown { + [super tearDown]; + [self.sessionManager invalidateSessionCancelingTasks:YES]; + self.sessionManager = nil; +} + +- (void)testTaskDidResumeNotificationDoesNotCauseCrashForUIRCWithTask { + XCTestExpectation *expectation = [self expectationWithDescription:@"No Crash"]; + [self expectationForNotification:AFNetworkingTaskDidResumeNotification object:nil handler:nil]; + NSURLSessionDataTask *task = [self.sessionManager + dataTaskWithRequest:self.request + completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + [expectation fulfill]; + }]; + + [self.refreshControl setRefreshingWithStateOfTask:task]; + self.refreshControl = nil; + + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + [task cancel]; +} + +- (void)testTaskDidCompleteNotificationDoesNotCauseCrashForUIRCWithTask { + XCTestExpectation *expectation = [self expectationWithDescription:@"No Crash"]; + [self expectationForNotification:AFNetworkingTaskDidCompleteNotification object:nil handler:nil]; + NSURLSessionDataTask *task = [self.sessionManager + dataTaskWithRequest:self.request + completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + //Without the dispatch after, this test would PASS errorenously because the test + //would finish before the notification was posted to all objects that were + //observing it. + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [expectation fulfill]; + }); + }]; + + [self.refreshControl setRefreshingWithStateOfTask:task]; + self.refreshControl = nil; + + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + [task cancel]; +} + +- (void)testTaskDidSuspendNotificationDoesNotCauseCrashForUIRCWithTask { + XCTestExpectation *expectation = [self expectationWithDescription:@"No Crash"]; + [self expectationForNotification:AFNetworkingTaskDidSuspendNotification object:nil handler:nil]; + NSURLSessionDataTask *task = [self.sessionManager + dataTaskWithRequest:self.request + completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + //Without the dispatch after, this test would PASS errorenously because the test + //would finish before the notification was posted to all objects that were + //observing it. + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [expectation fulfill]; + }); + }]; + + [self.refreshControl setRefreshingWithStateOfTask:task]; + self.refreshControl = nil; + + [task resume]; + [task suspend]; + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; + [task cancel]; +} + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFUIWebViewTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIWebViewTests.m new file mode 100644 index 00000000..c43b3f90 --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFUIWebViewTests.m @@ -0,0 +1,85 @@ +// AFUIWebViewTests.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import "AFTestCase.h" +#import "UIWebView+AFNetworking.h" + +@interface AFUIWebViewTests : AFTestCase +@property (nonatomic, strong) UIWebView *webView; +@property (nonatomic, strong) NSURLRequest *HTMLRequest; + +@end + +@implementation AFUIWebViewTests + +- (void)setUp { + [super setUp]; + self.webView = [UIWebView new]; + self.HTMLRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/html"]]; +} + +- (void)testNilProgressDoesNotCauseCrash { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.webView + loadRequest:self.HTMLRequest + progress:nil + success:^NSString * _Nonnull(NSHTTPURLResponse * _Nonnull response, NSString * _Nonnull HTML) { + [expectation fulfill]; + return HTML; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testNULLProgressDoesNotCauseCrash { + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.webView + loadRequest:self.HTMLRequest + progress:NULL + success:^NSString * _Nonnull(NSHTTPURLResponse * _Nonnull response, NSString * _Nonnull HTML) { + [expectation fulfill]; + return HTML; + } + failure:nil]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testProgressIsSet { + NSProgress* progress = nil; + XCTestExpectation *expectation = [self expectationWithDescription:@"Request should succeed"]; + [self.webView + loadRequest:self.HTMLRequest + progress:&progress + success:^NSString * _Nonnull(NSHTTPURLResponse * _Nonnull response, NSString * _Nonnull HTML) { + [expectation fulfill]; + return HTML; + } + failure:nil]; + [self keyValueObservingExpectationForObject:progress + keyPath:@"fractionCompleted" + expectedValue:@(1.0)]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + + + +@end diff --git a/its/plugin/projects/AFNetworking/Tests/Tests/AFURLSessionManagerTests.m b/its/plugin/projects/AFNetworking/Tests/Tests/AFURLSessionManagerTests.m new file mode 100644 index 00000000..b239267e --- /dev/null +++ b/its/plugin/projects/AFNetworking/Tests/Tests/AFURLSessionManagerTests.m @@ -0,0 +1,473 @@ +// AFURLSessionManagerTests.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import "AFTestCase.h" + +#import "AFURLSessionManager.h" + +@interface AFURLSessionManagerTests : AFTestCase +@property (readwrite, nonatomic, strong) AFURLSessionManager *localManager; +@property (readwrite, nonatomic, strong) AFURLSessionManager *backgroundManager; +@end + + +@implementation AFURLSessionManagerTests + +- (NSURLRequest *)bigImageURLRequest { + NSURL *url = [NSURL URLWithString:@"http://scitechdaily.com/images/New-Image-of-the-Galaxy-Messier-94-also-Known-as-NGC-4736.jpg"]; + NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0]; + return request; +} + +- (void)setUp { + [super setUp]; + self.localManager = [[AFURLSessionManager alloc] init]; + [self.localManager.session.configuration.URLCache removeAllCachedResponses]; + + //Unfortunately, iOS 7 throws an exception when trying to create a background URL Session inside this test target, which means our tests here can only run on iOS 8+ + //Travis actually needs the try catch here. Just doing if ([NSURLSessionConfiguration respondsToSelector:@selector(backgroundSessionWithIdentifier)]) wasn't good enough. + @try { + NSString *identifier = [NSString stringWithFormat:@"com.afnetworking.tests.urlsession.%@", [[NSUUID UUID] UUIDString]]; + NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:identifier]; + self.backgroundManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; + } + @catch (NSException *exception) { + + } +} + +- (void)tearDown { + [super tearDown]; + [self.localManager.session.configuration.URLCache removeAllCachedResponses]; + [self.localManager invalidateSessionCancelingTasks:YES]; + self.localManager = nil; + + [self.backgroundManager invalidateSessionCancelingTasks:YES]; + self.backgroundManager = nil; +} + +#pragma mark Progress - + +- (void)testDataTaskDoesReportDownloadProgress { + NSURLSessionDataTask *task; + + __weak XCTestExpectation *expectation = [self expectationWithDescription:@"Progress should equal 1.0"]; + task = [self.localManager + dataTaskWithRequest:[self bigImageURLRequest] + uploadProgress:nil + downloadProgress:^(NSProgress * _Nonnull downloadProgress) { + if (downloadProgress.fractionCompleted == 1.0) { + [expectation fulfill]; + } + } + completionHandler:nil]; + + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testDataTaskDownloadProgressCanBeKVOd { + NSURLSessionDataTask *task; + + task = [self.localManager + dataTaskWithRequest:[self bigImageURLRequest] + uploadProgress:nil + downloadProgress:nil + completionHandler:nil]; + + NSProgress *progress = [self.localManager downloadProgressForTask:task]; + [self keyValueObservingExpectationForObject:progress keyPath:@"fractionCompleted" + handler:^BOOL(NSProgress *observedProgress, NSDictionary * _Nonnull change) { + double new = [change[@"new"] doubleValue]; + double old = [change[@"old"] doubleValue]; + return new == 1.0 && old != 0.0; + }]; + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testDownloadTaskDoesReportProgress { + __weak XCTestExpectation *expectation = [self expectationWithDescription:@"Progress should equal 1.0"]; + NSURLSessionTask *task; + task = [self.localManager + downloadTaskWithRequest:[self bigImageURLRequest] + progress:^(NSProgress * _Nonnull downloadProgress) { + if (downloadProgress.fractionCompleted == 1.0) { + [expectation fulfill]; + } + } + destination:nil + completionHandler:nil]; + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testUploadTaskDoesReportProgress { + NSMutableString *payload = [NSMutableString stringWithString:@"AFNetworking"]; + while ([payload lengthOfBytesUsingEncoding:NSUTF8StringEncoding] < 20000) { + [payload appendString:@"AFNetworking"]; + } + + NSURL *url = [NSURL URLWithString:[[self.baseURL absoluteString] stringByAppendingString:@"/post"]]; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0]; + [request setHTTPMethod:@"POST"]; + + __weak XCTestExpectation *expectation = [self expectationWithDescription:@"Progress should equal 1.0"]; + + NSURLSessionTask *task; + task = [self.localManager + uploadTaskWithRequest:request + fromData:[payload dataUsingEncoding:NSUTF8StringEncoding] + progress:^(NSProgress * _Nonnull uploadProgress) { + NSLog(@"%@", uploadProgress.localizedDescription); + if ([uploadProgress fractionCompleted] == 1.0) { + [expectation fulfill]; + } + } + completionHandler:nil]; + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +- (void)testUploadProgressCanBeKVOd { + NSMutableString *payload = [NSMutableString stringWithString:@"AFNetworking"]; + while ([payload lengthOfBytesUsingEncoding:NSUTF8StringEncoding] < 20000) { + [payload appendString:@"AFNetworking"]; + } + + NSURL *url = [NSURL URLWithString:[[self.baseURL absoluteString] stringByAppendingString:@"/post"]]; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0]; + [request setHTTPMethod:@"POST"]; + + NSURLSessionTask *task; + task = [self.localManager + uploadTaskWithRequest:request + fromData:[payload dataUsingEncoding:NSUTF8StringEncoding] + progress:nil + completionHandler:nil]; + + NSProgress *uploadProgress = [self.localManager uploadProgressForTask:task]; + [self keyValueObservingExpectationForObject:uploadProgress keyPath:NSStringFromSelector(@selector(fractionCompleted)) expectedValue:@(1.0)]; + + [task resume]; + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +#pragma mark - rdar://17029580 + +- (void)testRDAR17029580IsFixed { + //https://github.com/AFNetworking/AFNetworking/issues/2093 + //https://github.com/AFNetworking/AFNetworking/pull/3205 + //http://openradar.appspot.com/radar?id=5871104061079552 + dispatch_queue_t serial_queue = dispatch_queue_create("com.alamofire.networking.test.RDAR17029580", DISPATCH_QUEUE_SERIAL); + NSMutableArray *taskIDs = [[NSMutableArray alloc] init]; + for (NSInteger i = 0; i < 100; i++) { + XCTestExpectation *expectation = [self expectationWithDescription:@"Wait for task creation"]; + __block NSURLSessionTask *task; + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + task = [self.localManager + dataTaskWithRequest:[NSURLRequest requestWithURL:self.baseURL] + completionHandler:nil]; + dispatch_sync(serial_queue, ^{ + XCTAssertFalse([taskIDs containsObject:@(task.taskIdentifier)]); + [taskIDs addObject:@(task.taskIdentifier)]; + }); + [task cancel]; + [expectation fulfill]; + }); + } + [self waitForExpectationsWithCommonTimeoutUsingHandler:nil]; +} + +#pragma mark - Issue #2702 Tests +// The following tests are all releated to issue #2702 + +- (void)testDidResumeNotificationIsReceivedByLocalDataTaskAfterResume { + NSURLSessionDataTask *task = [self.localManager dataTaskWithRequest:[self _delayURLRequest] + completionHandler:nil]; + [self _testResumeNotificationForTask:task]; +} + +- (void)testDidSuspendNotificationIsReceivedByLocalDataTaskAfterSuspend { + NSURLSessionDataTask *task = [self.localManager dataTaskWithRequest:[self _delayURLRequest] + completionHandler:nil]; + [self _testSuspendNotificationForTask:task]; +} + +- (void)testDidResumeNotificationIsReceivedByBackgroundDataTaskAfterResume { + if (self.backgroundManager) { + NSURLSessionDataTask *task = [self.backgroundManager dataTaskWithRequest:[self _delayURLRequest] + completionHandler:nil]; + [self _testResumeNotificationForTask:task]; + } +} + +- (void)testDidSuspendNotificationIsReceivedByBackgroundDataTaskAfterSuspend { + if (self.backgroundManager) { + NSURLSessionDataTask *task = [self.backgroundManager dataTaskWithRequest:[self _delayURLRequest] + completionHandler:nil]; + [self _testSuspendNotificationForTask:task]; + } +} + +- (void)testDidResumeNotificationIsReceivedByLocalUploadTaskAfterResume { + NSURLSessionUploadTask *task = [self.localManager uploadTaskWithRequest:[self _delayURLRequest] + fromData:[NSData data] + progress:nil + completionHandler:nil]; + [self _testResumeNotificationForTask:task]; +} + +- (void)testDidSuspendNotificationIsReceivedByLocalUploadTaskAfterSuspend { + NSURLSessionUploadTask *task = [self.localManager uploadTaskWithRequest:[self _delayURLRequest] + fromData:[NSData data] + progress:nil + completionHandler:nil]; + [self _testSuspendNotificationForTask:task]; +} + +- (void)testDidResumeNotificationIsReceivedByBackgroundUploadTaskAfterResume { + if (self.backgroundManager) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnonnull" + NSURLSessionUploadTask *task = [self.backgroundManager uploadTaskWithRequest:[self _delayURLRequest] + fromFile:nil + progress:nil + completionHandler:nil]; +#pragma clang diagnostic pop + [self _testResumeNotificationForTask:task]; + } +} + +- (void)testDidSuspendNotificationIsReceivedByBackgroundUploadTaskAfterSuspend { + if (self.backgroundManager) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnonnull" + NSURLSessionUploadTask *task = [self.backgroundManager uploadTaskWithRequest:[self _delayURLRequest] + fromFile:nil + progress:nil + completionHandler:nil]; +#pragma clang diagnostic pop + [self _testSuspendNotificationForTask:task]; + } +} + +- (void)testDidResumeNotificationIsReceivedByLocalDownloadTaskAfterResume { + NSURLSessionDownloadTask *task = [self.localManager downloadTaskWithRequest:[self _delayURLRequest] + progress:nil + destination:nil + completionHandler:nil]; + [self _testResumeNotificationForTask:task]; +} + +- (void)testDidSuspendNotificationIsReceivedByLocalDownloadTaskAfterSuspend { + NSURLSessionDownloadTask *task = [self.localManager downloadTaskWithRequest:[self _delayURLRequest] + progress:nil + destination:nil + completionHandler:nil]; + [self _testSuspendNotificationForTask:task]; +} + +- (void)testDidResumeNotificationIsReceivedByBackgroundDownloadTaskAfterResume { + if (self.backgroundManager) { + NSURLSessionDownloadTask *task = [self.backgroundManager downloadTaskWithRequest:[self _delayURLRequest] + progress:nil + destination:nil + completionHandler:nil]; + [self _testResumeNotificationForTask:task]; + } +} + +- (void)testDidSuspendNotificationIsReceivedByBackgroundDownloadTaskAfterSuspend { + if (self.backgroundManager) { + NSURLSessionDownloadTask *task = [self.backgroundManager downloadTaskWithRequest:[self _delayURLRequest] + progress:nil + destination:nil + completionHandler:nil]; + [self _testSuspendNotificationForTask:task]; + } +} + +- (void)testSwizzlingIsProperlyConfiguredForDummyClass { + IMP originalAFResumeIMP = [self _originalAFResumeImplementation]; + IMP originalAFSuspendIMP = [self _originalAFSuspendImplementation]; + XCTAssert(originalAFResumeIMP, @"Swizzled af_resume Method Not Found"); + XCTAssert(originalAFSuspendIMP, @"Swizzled af_suspend Method Not Found"); + XCTAssertNotEqual(originalAFResumeIMP, originalAFSuspendIMP, @"af_resume and af_suspend should not be equal"); +} + +- (void)testSwizzlingIsWorkingAsExpectedForForegroundDataTask { + NSURLSessionTask *task = [self.localManager dataTaskWithRequest:[self _delayURLRequest] + completionHandler:nil]; + [self _testSwizzlingForTask:task]; + [task cancel]; +} + +- (void)testSwizzlingIsWorkingAsExpectedForForegroundUpload { + NSURLSessionTask *task = [self.localManager uploadTaskWithRequest:[self _delayURLRequest] + fromData:[NSData data] + progress:nil + completionHandler:nil]; + [self _testSwizzlingForTask:task]; + [task cancel]; +} + +- (void)testSwizzlingIsWorkingAsExpectedForForegroundDownload { + NSURLSessionTask *task = [self.localManager downloadTaskWithRequest:[self _delayURLRequest] + progress:nil + destination:nil + completionHandler:nil]; + [self _testSwizzlingForTask:task]; + [task cancel]; +} + +- (void)testSwizzlingIsWorkingAsExpectedForBackgroundDataTask { + //iOS 7 doesn't let us use a background manager in these tests, so reference these + //classes directly. There are tests below to confirm background manager continues + //to return the exepcted classes going forward. If those fail in a future iOS version, + //it should point us to a problem here. + [self _testSwizzlingForTaskClass:NSClassFromString(@"__NSCFBackgroundDataTask")]; +} + +- (void)testSwizzlingIsWorkingAsExpectedForBackgroundUploadTask { + //iOS 7 doesn't let us use a background manager in these tests, so reference these + //classes directly. There are tests below to confirm background manager continues + //to return the exepcted classes going forward. If those fail in a future iOS version, + //it should point us to a problem here. + [self _testSwizzlingForTaskClass:NSClassFromString(@"__NSCFBackgroundUploadTask")]; +} + +- (void)testSwizzlingIsWorkingAsExpectedForBackgroundDownloadTask { + //iOS 7 doesn't let us use a background manager in these tests, so reference these + //classes directly. There are tests below to confirm background manager continues + //to return the exepcted classes going forward. If those fail in a future iOS version, + //it should point us to a problem here. + [self _testSwizzlingForTaskClass:NSClassFromString(@"__NSCFBackgroundDownloadTask")]; +} + +- (void)testBackgroundManagerReturnsExpectedClassForDataTask { + if (self.backgroundManager) { + NSURLSessionTask *task = [self.backgroundManager dataTaskWithRequest:[self _delayURLRequest] + completionHandler:nil]; + XCTAssert([NSStringFromClass([task class]) isEqualToString:@"__NSCFBackgroundDataTask"]); + } else { + NSLog(@"Unable to run %@ because self.backgroundManager is nil", NSStringFromSelector(_cmd)); + } +} + +- (void)testBackgroundManagerReturnsExpectedClassForUploadTask { + if (self.backgroundManager) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnonnull" + NSURLSessionTask *task = [self.backgroundManager uploadTaskWithRequest:[self _delayURLRequest] + fromFile:nil + progress:nil + completionHandler:nil]; +#pragma clang diagnostic pop + XCTAssert([NSStringFromClass([task class]) isEqualToString:@"__NSCFBackgroundUploadTask"]); + } else { + NSLog(@"Unable to run %@ because self.backgroundManager is nil", NSStringFromSelector(_cmd)); + } +} + +- (void)testBackgroundManagerReturnsExpectedClassForDownloadTask { + if (self.backgroundManager) { + NSURLSessionTask *task = [self.backgroundManager downloadTaskWithRequest:[self _delayURLRequest] + progress:nil + destination:nil + completionHandler:nil]; + XCTAssert([NSStringFromClass([task class]) isEqualToString:@"__NSCFBackgroundDownloadTask"]); + } else { + NSLog(@"Unable to run %@ because self.backgroundManager is nil", NSStringFromSelector(_cmd)); + } +} + +#pragma mark - private + +- (void)_testResumeNotificationForTask:(NSURLSessionTask *)task { + [self expectationForNotification:AFNetworkingTaskDidResumeNotification + object:nil + handler:nil]; + [task resume]; + [task suspend]; + [task resume]; + [self waitForExpectationsWithTimeout:2.0 handler:nil]; + [task cancel]; +} + +- (void)_testSuspendNotificationForTask:(NSURLSessionTask *)task { + [self expectationForNotification:AFNetworkingTaskDidSuspendNotification + object:nil + handler:nil]; + [task resume]; + [task suspend]; + [task resume]; + [self waitForExpectationsWithTimeout:2.0 handler:nil]; + [task cancel]; +} + +- (NSURLRequest *)_delayURLRequest { + return [NSURLRequest requestWithURL:[self.baseURL URLByAppendingPathComponent:@"delay/1"]]; +} + +- (IMP)_implementationForTask:(NSURLSessionTask *)task selector:(SEL)selector { + return [self _implementationForClass:[task class] selector:selector]; +} + +- (IMP)_implementationForClass:(Class)class selector:(SEL)selector { + return method_getImplementation(class_getInstanceMethod(class, selector)); +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wundeclared-selector" +- (IMP)_originalAFResumeImplementation { + return method_getImplementation(class_getInstanceMethod(NSClassFromString(@"_AFURLSessionTaskSwizzling"), @selector(af_resume))); +} + +- (IMP)_originalAFSuspendImplementation { + return method_getImplementation(class_getInstanceMethod(NSClassFromString(@"_AFURLSessionTaskSwizzling"), @selector(af_suspend))); +} + +- (void)_testSwizzlingForTask:(NSURLSessionTask *)task { + [self _testSwizzlingForTaskClass:[task class]]; +} + +- (void)_testSwizzlingForTaskClass:(Class)class { + IMP originalAFResumeIMP = [self _originalAFResumeImplementation]; + IMP originalAFSuspendIMP = [self _originalAFSuspendImplementation]; + + IMP taskResumeImp = [self _implementationForClass:class selector:@selector(resume)]; + IMP taskSuspendImp = [self _implementationForClass:class selector:@selector(suspend)]; + XCTAssertEqual(originalAFResumeIMP, taskResumeImp, @"resume has not been properly swizzled for %@", NSStringFromClass(class)); + XCTAssertEqual(originalAFSuspendIMP, taskSuspendImp, @"suspend has not been properly swizzled for %@", NSStringFromClass(class)); + + IMP taskAFResumeImp = [self _implementationForClass:class selector:@selector(af_resume)]; + IMP taskAFSuspendImp = [self _implementationForClass:class selector:@selector(af_suspend)]; + XCTAssert(taskAFResumeImp != NULL, @"af_resume is nil. Something has not been been swizzled right for %@", NSStringFromClass(class)); + XCTAssertNotEqual(taskAFResumeImp, taskResumeImp, @"af_resume has not been properly swizzled for %@", NSStringFromClass(class)); + XCTAssert(taskAFSuspendImp != NULL, @"af_suspend is nil. Something has not been been swizzled right for %@", NSStringFromClass(class)); + XCTAssertNotEqual(taskAFSuspendImp, taskSuspendImp, @"af_suspend has not been properly swizzled for %@", NSStringFromClass(class)); +} +#pragma clang diagnostic pop + +@end diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h new file mode 100644 index 00000000..16139dad --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h @@ -0,0 +1,149 @@ +// AFAutoPurgingImageCache.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import + +#if TARGET_OS_IOS || TARGET_OS_TV +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + The `AFImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache synchronously. + */ +@protocol AFImageCache + +/** + Adds the image to the cache with the given identifier. + + @param image The image to cache. + @param identifier The unique identifier for the image in the cache. + */ +- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier; + +/** + Removes the image from the cache matching the given identifier. + + @param identifier The unique identifier for the image in the cache. + + @return A BOOL indicating whether or not the image was removed from the cache. + */ +- (BOOL)removeImageWithIdentifier:(NSString *)identifier; + +/** + Removes all images from the cache. + + @return A BOOL indicating whether or not all images were removed from the cache. + */ +- (BOOL)removeAllImages; + +/** + Returns the image in the cache associated with the given identifier. + + @param identifier The unique identifier for the image in the cache. + + @return An image for the matching identifier, or nil. + */ +- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier; +@end + + +/** + The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and fetching images from a cache given an `NSURLRequest` and additional identifier. + */ +@protocol AFImageRequestCache + +/** + Adds the image to the cache using an identifier created from the request and additional identifier. + + @param image The image to cache. + @param request The unique URL request identifing the image asset. + @param identifier The additional identifier to apply to the URL request to identify the image. + */ +- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; + +/** + Removes the image from the cache using an identifier created from the request and additional identifier. + + @param request The unique URL request identifing the image asset. + @param identifier The additional identifier to apply to the URL request to identify the image. + + @return A BOOL indicating whether or not all images were removed from the cache. + */ +- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; + +/** + Returns the image from the cache associated with an identifier created from the request and additional identifier. + + @param request The unique URL request identifing the image asset. + @param identifier The additional identifier to apply to the URL request to identify the image. + + @return An image for the matching request and identifier, or nil. + */ +- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; + +@end + +/** + The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the internal access date of the image is updated. + */ +@interface AFAutoPurgingImageCache : NSObject + +/** + The total memory capacity of the cache in bytes. + */ +@property (nonatomic, assign) UInt64 memoryCapacity; + +/** + The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory capacity drops below this limit. + */ +@property (nonatomic, assign) UInt64 preferredMemoryUsageAfterPurge; + +/** + The current total memory usage in bytes of all images stored within the cache. + */ +@property (nonatomic, assign, readonly) UInt64 memoryUsage; + +/** + Initialies the `AutoPurgingImageCache` instance with default values for memory capacity and preferred memory usage after purge limit. `memoryCapcity` defaults to `100 MB`. `preferredMemoryUsageAfterPurge` defaults to `60 MB`. + + @return The new `AutoPurgingImageCache` instance. + */ +- (instancetype)init; + +/** + Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage + after purge limit. + + @param memoryCapacity The total memory capacity of the cache in bytes. + @param preferredMemoryUsageAfterPurge The preferred memory usage after purge in bytes. + + @return The new `AutoPurgingImageCache` instance. + */ +- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity; + +@end + +NS_ASSUME_NONNULL_END + +#endif + diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m new file mode 100644 index 00000000..99ad3d65 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m @@ -0,0 +1,201 @@ +// AFAutoPurgingImageCache.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFAutoPurgingImageCache.h" + +@interface AFCachedImage : NSObject + +@property (nonatomic, strong) UIImage *image; +@property (nonatomic, strong) NSString *identifier; +@property (nonatomic, assign) UInt64 totalBytes; +@property (nonatomic, strong) NSDate *lastAccessDate; +@property (nonatomic, assign) UInt64 currentMemoryUsage; + +@end + +@implementation AFCachedImage + +-(instancetype)initWithImage:(UIImage *)image identifier:(NSString *)identifier { + if (self = [self init]) { + self.image = image; + self.identifier = identifier; + + CGSize imageSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale); + CGFloat bytesPerPixel = 4.0; + CGFloat bytesPerRow = imageSize.width * bytesPerPixel; + self.totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerRow; + self.lastAccessDate = [NSDate date]; + } + return self; +} + +- (UIImage*)accessImage { + self.lastAccessDate = [NSDate date]; + return self.image; +} + +- (NSString *)description { + NSString *descriptionString = [NSString stringWithFormat:@"Idenfitier: %@ lastAccessDate: %@ ", self.identifier, self.lastAccessDate]; + return descriptionString; + +} + +@end + +@interface AFAutoPurgingImageCache () +@property (nonatomic, strong) NSMutableDictionary *cachedImages; +@property (nonatomic, assign) UInt64 currentMemoryUsage; +@property (nonatomic, strong) dispatch_queue_t synchronizationQueue; +@end + +@implementation AFAutoPurgingImageCache + +- (instancetype)init { + return [self initWithMemoryCapacity:100 * 1024 * 1024 preferredMemoryCapacity:60 * 1024 * 1024]; +} + +- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity { + if (self = [super init]) { + self.memoryCapacity = memoryCapacity; + self.preferredMemoryUsageAfterPurge = preferredMemoryCapacity; + self.cachedImages = [[NSMutableDictionary alloc] init]; + + NSString *queueName = [NSString stringWithFormat:@"com.alamofire.autopurgingimagecache-%@", [[NSUUID UUID] UUIDString]]; + self.synchronizationQueue = dispatch_queue_create([queueName cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT); + + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(removeAllImages) + name:UIApplicationDidReceiveMemoryWarningNotification + object:nil]; + + } + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +- (UInt64)memoryUsage { + __block UInt64 result = 0; + dispatch_sync(self.synchronizationQueue, ^{ + result = self.currentMemoryUsage; + }); + return result; +} + +- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier { + dispatch_barrier_async(self.synchronizationQueue, ^{ + AFCachedImage *cacheImage = [[AFCachedImage alloc] initWithImage:image identifier:identifier]; + + AFCachedImage *previousCachedImage = self.cachedImages[identifier]; + if (previousCachedImage != nil) { + self.currentMemoryUsage -= previousCachedImage.totalBytes; + } + + self.cachedImages[identifier] = cacheImage; + self.currentMemoryUsage += cacheImage.totalBytes; + }); + + dispatch_barrier_async(self.synchronizationQueue, ^{ + if (self.currentMemoryUsage > self.memoryCapacity) { + UInt64 bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge; + NSMutableArray *sortedImages = [NSMutableArray arrayWithArray:self.cachedImages.allValues]; + NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastAccessDate" + ascending:YES]; + [sortedImages sortUsingDescriptors:@[sortDescriptor]]; + + UInt64 bytesPurged = 0; + + for (AFCachedImage *cachedImage in sortedImages) { + [self.cachedImages removeObjectForKey:cachedImage.identifier]; + bytesPurged += cachedImage.totalBytes; + if (bytesPurged >= bytesToPurge) { + break ; + } + } + self.currentMemoryUsage -= bytesPurged; + } + }); +} + +- (BOOL)removeImageWithIdentifier:(NSString *)identifier { + __block BOOL removed = NO; + dispatch_barrier_sync(self.synchronizationQueue, ^{ + AFCachedImage *cachedImage = self.cachedImages[identifier]; + if (cachedImage != nil) { + [self.cachedImages removeObjectForKey:identifier]; + self.currentMemoryUsage -= cachedImage.totalBytes; + removed = YES; + } + }); + return removed; +} + +- (BOOL)removeAllImages { + __block BOOL removed = NO; + dispatch_barrier_sync(self.synchronizationQueue, ^{ + if (self.cachedImages.count > 0) { + [self.cachedImages removeAllObjects]; + self.currentMemoryUsage = 0; + removed = YES; + } + }); + return removed; +} + +- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier { + __block UIImage *image = nil; + dispatch_sync(self.synchronizationQueue, ^{ + AFCachedImage *cachedImage = self.cachedImages[identifier]; + image = [cachedImage accessImage]; + }); + return image; +} + +- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { + [self addImage:image withIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; +} + +- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { + return [self removeImageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; +} + +- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { + return [self imageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; +} + +- (NSString *)imageCacheKeyFromURLRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)additionalIdentifier { + NSString *key = request.URL.absoluteString; + if (additionalIdentifier != nil) { + key = [key stringByAppendingString:additionalIdentifier]; + } + return key; +} + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h new file mode 100644 index 00000000..a368ad8f --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h @@ -0,0 +1,157 @@ +// AFImageDownloader.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import +#import "AFAutoPurgingImageCache.h" +#import "AFHTTPSessionManager.h" + +NS_ASSUME_NONNULL_BEGIN + +typedef NS_ENUM(NSInteger, AFImageDownloadPrioritization) { + AFImageDownloadPrioritizationFIFO, + AFImageDownloadPrioritizationLIFO +}; + +/** + The `AFImageDownloadReceipt` is an object vended by the `AFImageDownloader` when starting a data task. It can be used to cancel active tasks running on the `AFImageDownloader` session. As a general rule, image data tasks should be cancelled using the `AFImageDownloadReceipt` instead of calling `cancel` directly on the `task` itself. The `AFImageDownloader` is optimized to handle duplicate task scenarios as well as pending versus active downloads. + */ +@interface AFImageDownloadReceipt : NSObject + +/** + The data task created by the `AFImageDownloader`. +*/ +@property (nonatomic, strong) NSURLSessionDataTask *task; + +/** + The unique identifier for the success and failure blocks when duplicate requests are made. + */ +@property (nonatomic, strong) NSUUID *receiptID; +@end + +/** The `AFImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded image is cached in the underlying `NSURLCache` as well as the in-memory image cache. By default, any download request with a cached image equivalent in the image cache will automatically be served the cached image representation. + */ +@interface AFImageDownloader : NSObject + +/** + The image cache used to store all downloaded images in. `AFAutoPurgingImageCache` by default. + */ +@property (nonatomic, strong, nullable) id imageCache; + +/** + The `AFHTTPSessionManager` used to download images. By default, this is configured with an `AFImageResponseSerializer`, and a shared `NSURLCache` for all image downloads. + */ +@property (nonatomic, strong) AFHTTPSessionManager *sessionManager; + +/** + Defines the order prioritization of incoming download requests being inserted into the queue. `AFImageDownloadPrioritizationFIFO` by default. + */ +@property (nonatomic, assign) AFImageDownloadPrioritization downloadPrioritizaton; + +/** + The shared default instance of `AFImageDownloader` initialized with default values. + */ ++ (instancetype)defaultInstance; + +/** + Creates a default `NSURLCache` with common usage parameter values. + + @returns The default `NSURLCache` instance. + */ ++ (NSURLCache *)defaultURLCache; + +/** + Default initializer + + @return An instance of `AFImageDownloader` initialized with default values. + */ +- (instancetype)init; + +/** + Initializes the `AFImageDownloader` instance with the given session manager, download prioritization, maximum active download count and image cache. + + @param sessionManager The session manager to use to download images. + @param downloadPrioritization The download prioritization of the download queue. + @param maximumActiveDownloads The maximum number of active downloads allowed at any given time. Recommend `4`. + @param imageCache The image cache used to store all downloaded images in. + + @return The new `AFImageDownloader` instance. + */ +- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager + downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization + maximumActiveDownloads:(NSInteger)maximumActiveDownloads + imageCache:(nullable id )imageCache; + +/** + Creates a data task using the `sessionManager` instance for the specified URL request. + + If the same data task is already in the queue or currently being downloaded, the success and failure blocks are + appended to the already existing task. Once the task completes, all success or failure blocks attached to the + task are executed in the order they were added. + + @param request The URL request. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + + @return The image download receipt for the data task if available. `nil` if the image is stored in the cache. + cache and the URL request cache policy allows the cache to be used. + */ +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + +/** + Creates a data task using the `sessionManager` instance for the specified URL request. + + If the same data task is already in the queue or currently being downloaded, the success and failure blocks are + appended to the already existing task. Once the task completes, all success or failure blocks attached to the + task are executed in the order they were added. + + @param request The URL request. + @param request The identifier to use for the download receipt that will be created for this request. This must be a unique identifier that does not represent any other request. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + + @return The image download receipt for the data task if available. `nil` if the image is stored in the cache. + cache and the URL request cache policy allows the cache to be used. + */ +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + withReceiptID:(NSUUID *)receiptID + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + +/** + Cancels the data task in the receipt by removing the corresponding success and failure blocks and cancelling the data task if necessary. + + If the data task is pending in the queue, it will be cancelled if no other success and failure blocks are registered with the data task. If the data task is currently executing or is already completed, the success and failure blocks are removed and will not be called when the task finishes. + + @param imageDownloadReceipt The image download receipt to cancel. + */ +- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt; + +@end + +#endif + +NS_ASSUME_NONNULL_END diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m new file mode 100644 index 00000000..f7aa3d31 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m @@ -0,0 +1,382 @@ +// AFImageDownloader.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFImageDownloader.h" +#import "AFHTTPSessionManager.h" + +@interface AFImageDownloaderResponseHandler : NSObject +@property (nonatomic, strong) NSUUID *uuid; +@property (nonatomic, copy) void (^successBlock)(NSURLRequest*, NSHTTPURLResponse*, UIImage*); +@property (nonatomic, copy) void (^failureBlock)(NSURLRequest*, NSHTTPURLResponse*, NSError*); +@end + +@implementation AFImageDownloaderResponseHandler + +- (instancetype)initWithUUID:(NSUUID *)uuid + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure { + if (self = [self init]) { + self.uuid = uuid; + self.successBlock = success; + self.failureBlock = failure; + } + return self; +} + +- (NSString *)description { + return [NSString stringWithFormat: @"UUID: %@", [self.uuid UUIDString]]; +} + +@end + +@interface AFImageDownloaderMergedTask : NSObject +@property (nonatomic, strong) NSString *URLIdentifier; +@property (nonatomic, strong) NSUUID *identifier; +@property (nonatomic, strong) NSURLSessionDataTask *task; +@property (nonatomic, strong) NSMutableArray *responseHandlers; + +@end + +@implementation AFImageDownloaderMergedTask + +- (instancetype)initWithURLIdentifier:(NSString *)URLIdentifier identifier:(NSUUID *)identifier task:(NSURLSessionDataTask *)task { + if (self = [self init]) { + self.URLIdentifier = URLIdentifier; + self.task = task; + self.identifier = identifier; + self.responseHandlers = [[NSMutableArray alloc] init]; + } + return self; +} + +- (void)addResponseHandler:(AFImageDownloaderResponseHandler*)handler { + [self.responseHandlers addObject:handler]; +} + +- (void)removeResponseHandler:(AFImageDownloaderResponseHandler*)handler { + [self.responseHandlers removeObject:handler]; +} + +@end + +@implementation AFImageDownloadReceipt + +- (instancetype)initWithReceiptID:(NSUUID *)receiptID task:(NSURLSessionDataTask *)task { + if (self = [self init]) { + self.receiptID = receiptID; + self.task = task; + } + return self; +} + +@end + +@interface AFImageDownloader () + +@property (nonatomic, strong) dispatch_queue_t synchronizationQueue; +@property (nonatomic, strong) dispatch_queue_t responseQueue; + +@property (nonatomic, assign) NSInteger maximumActiveDownloads; +@property (nonatomic, assign) NSInteger activeRequestCount; + +@property (nonatomic, strong) NSMutableArray *queuedMergedTasks; +@property (nonatomic, strong) NSMutableDictionary *mergedTasks; + +@end + + +@implementation AFImageDownloader + ++ (NSURLCache *)defaultURLCache { + return [[NSURLCache alloc] initWithMemoryCapacity:20 * 1024 * 1024 + diskCapacity:150 * 1024 * 1024 + diskPath:@"com.alamofire.imagedownloader"]; +} + ++ (NSURLSessionConfiguration *)defaultURLSessionConfiguration { + NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; + + //TODO set the default HTTP headers + + configuration.HTTPShouldSetCookies = YES; + configuration.HTTPShouldUsePipelining = NO; + + configuration.requestCachePolicy = NSURLRequestUseProtocolCachePolicy; + configuration.allowsCellularAccess = YES; + configuration.timeoutIntervalForRequest = 60.0; + configuration.URLCache = [AFImageDownloader defaultURLCache]; + + return configuration; +} + +- (instancetype)init { + NSURLSessionConfiguration *defaultConfiguration = [self.class defaultURLSessionConfiguration]; + AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:defaultConfiguration]; + sessionManager.responseSerializer = [AFImageResponseSerializer serializer]; + + return [self initWithSessionManager:sessionManager + downloadPrioritization:AFImageDownloadPrioritizationFIFO + maximumActiveDownloads:4 + imageCache:[[AFAutoPurgingImageCache alloc] init]]; +} + +- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager + downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization + maximumActiveDownloads:(NSInteger)maximumActiveDownloads + imageCache:(id )imageCache { + if (self = [super init]) { + self.sessionManager = sessionManager; + + self.downloadPrioritizaton = downloadPrioritization; + self.maximumActiveDownloads = maximumActiveDownloads; + self.imageCache = imageCache; + + self.queuedMergedTasks = [[NSMutableArray alloc] init]; + self.mergedTasks = [[NSMutableDictionary alloc] init]; + self.activeRequestCount = 0; + + NSString *name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.synchronizationqueue-%@", [[NSUUID UUID] UUIDString]]; + self.synchronizationQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_SERIAL); + + name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.responsequeue-%@", [[NSUUID UUID] UUIDString]]; + self.responseQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT); + } + + return self; +} + ++ (instancetype)defaultInstance { + static AFImageDownloader *sharedInstance = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedInstance = [[self alloc] init]; + }); + return sharedInstance; +} + +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + success:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, UIImage * _Nonnull))success + failure:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, NSError * _Nonnull))failure { + return [self downloadImageForURLRequest:request withReceiptID:[NSUUID UUID] success:success failure:failure]; +} + +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + withReceiptID:(nonnull NSUUID *)receiptID + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure { + __block NSURLSessionDataTask *task = nil; + dispatch_sync(self.synchronizationQueue, ^{ + NSString *URLIdentifier = request.URL.absoluteString; + + // 1) Append the success and failure blocks to a pre-existing request if it already exists + AFImageDownloaderMergedTask *existingMergedTask = self.mergedTasks[URLIdentifier]; + if (existingMergedTask != nil) { + AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID success:success failure:failure]; + [existingMergedTask addResponseHandler:handler]; + task = existingMergedTask.task; + return; + } + + // 2) Attempt to load the image from the image cache if the cache policy allows it + switch (request.cachePolicy) { + case NSURLRequestUseProtocolCachePolicy: + case NSURLRequestReturnCacheDataElseLoad: + case NSURLRequestReturnCacheDataDontLoad: { + UIImage *cachedImage = [self.imageCache imageforRequest:request withAdditionalIdentifier:nil]; + if (cachedImage != nil) { + if (success) { + dispatch_async(dispatch_get_main_queue(), ^{ + success(request, nil, cachedImage); + }); + } + return; + } + break; + } + default: + break; + } + + // 3) Create the request and set up authentication, validation and response serialization + NSUUID *mergedTaskIdentifier = [NSUUID UUID]; + NSURLSessionDataTask *createdTask; + __weak __typeof__(self) weakSelf = self; + + createdTask = [self.sessionManager + dataTaskWithRequest:request + completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + dispatch_async(self.responseQueue, ^{ + __strong __typeof__(weakSelf) strongSelf = weakSelf; + AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier]; + if ([mergedTask.identifier isEqual:mergedTaskIdentifier]) { + mergedTask = [strongSelf safelyRemoveMergedTaskWithURLIdentifier:URLIdentifier]; + if (error) { + for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) { + if (handler.failureBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler.failureBlock(request, (NSHTTPURLResponse*)response, error); + }); + } + } + } else { + [strongSelf.imageCache addImage:responseObject forRequest:request withAdditionalIdentifier:nil]; + + for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) { + if (handler.successBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler.successBlock(request, (NSHTTPURLResponse*)response, responseObject); + }); + } + } + + } + } + [strongSelf safelyDecrementActiveTaskCount]; + [strongSelf safelyStartNextTaskIfNecessary]; + }); + }]; + + // 4) Store the response handler for use when the request completes + AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID + success:success + failure:failure]; + AFImageDownloaderMergedTask *mergedTask = [[AFImageDownloaderMergedTask alloc] + initWithURLIdentifier:URLIdentifier + identifier:mergedTaskIdentifier + task:createdTask]; + [mergedTask addResponseHandler:handler]; + self.mergedTasks[URLIdentifier] = mergedTask; + + // 5) Either start the request or enqueue it depending on the current active request count + if ([self isActiveRequestCountBelowMaximumLimit]) { + [self startMergedTask:mergedTask]; + } else { + [self enqueueMergedTask:mergedTask]; + } + + task = mergedTask.task; + }); + if (task) { + return [[AFImageDownloadReceipt alloc] initWithReceiptID:receiptID task:task]; + } else { + return nil; + } +} + +- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt { + dispatch_sync(self.synchronizationQueue, ^{ + NSString *URLIdentifier = imageDownloadReceipt.task.originalRequest.URL.absoluteString; + AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier]; + NSUInteger index = [mergedTask.responseHandlers indexOfObjectPassingTest:^BOOL(AFImageDownloaderResponseHandler * _Nonnull handler, __unused NSUInteger idx, __unused BOOL * _Nonnull stop) { + return handler.uuid == imageDownloadReceipt.receiptID; + }]; + + if (index != NSNotFound) { + AFImageDownloaderResponseHandler *handler = mergedTask.responseHandlers[index]; + [mergedTask removeResponseHandler:handler]; + NSString *failureReason = [NSString stringWithFormat:@"ImageDownloader cancelled URL request: %@",imageDownloadReceipt.task.originalRequest.URL.absoluteString]; + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey:failureReason}; + NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]; + if (handler.failureBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler.failureBlock(imageDownloadReceipt.task.originalRequest, nil, error); + }); + } + } + + if (mergedTask.responseHandlers.count == 0 && mergedTask.task.state == NSURLSessionTaskStateSuspended) { + [mergedTask.task cancel]; + [self removeMergedTaskWithURLIdentifier:URLIdentifier]; + } + }); +} + +- (AFImageDownloaderMergedTask*)safelyRemoveMergedTaskWithURLIdentifier:(NSString *)URLIdentifier { + __block AFImageDownloaderMergedTask *mergedTask = nil; + dispatch_sync(self.synchronizationQueue, ^{ + mergedTask = [self removeMergedTaskWithURLIdentifier:URLIdentifier]; + }); + return mergedTask; +} + +//This method should only be called from safely within the synchronizationQueue +- (AFImageDownloaderMergedTask *)removeMergedTaskWithURLIdentifier:(NSString *)URLIdentifier { + AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier]; + [self.mergedTasks removeObjectForKey:URLIdentifier]; + return mergedTask; +} + +- (void)safelyDecrementActiveTaskCount { + dispatch_sync(self.synchronizationQueue, ^{ + if (self.activeRequestCount > 0) { + self.activeRequestCount -= 1; + } + }); +} + +- (void)safelyStartNextTaskIfNecessary { + dispatch_sync(self.synchronizationQueue, ^{ + if ([self isActiveRequestCountBelowMaximumLimit]) { + while (self.queuedMergedTasks.count > 0) { + AFImageDownloaderMergedTask *mergedTask = [self dequeueMergedTask]; + if (mergedTask.task.state == NSURLSessionTaskStateSuspended) { + [self startMergedTask:mergedTask]; + break; + } + } + } + }); +} + +- (void)startMergedTask:(AFImageDownloaderMergedTask *)mergedTask { + [mergedTask.task resume]; + ++self.activeRequestCount; +} + +- (void)enqueueMergedTask:(AFImageDownloaderMergedTask *)mergedTask { + switch (self.downloadPrioritizaton) { + case AFImageDownloadPrioritizationFIFO: + [self.queuedMergedTasks addObject:mergedTask]; + break; + case AFImageDownloadPrioritizationLIFO: + [self.queuedMergedTasks insertObject:mergedTask atIndex:0]; + break; + } +} + +- (AFImageDownloaderMergedTask *)dequeueMergedTask { + AFImageDownloaderMergedTask *mergedTask = nil; + mergedTask = [self.queuedMergedTasks firstObject]; + [self.queuedMergedTasks removeObject:mergedTask]; + return mergedTask; +} + +- (BOOL)isActiveRequestCountBelowMaximumLimit { + return self.activeRequestCount < self.maximumActiveDownloads; +} + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h new file mode 100644 index 00000000..8b05ad3b --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h @@ -0,0 +1,103 @@ +// AFNetworkActivityIndicatorManager.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + `AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a session task 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. + + 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: + + [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; + + 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. + + See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information: + http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44 + */ +NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropriate instead.") +@interface AFNetworkActivityIndicatorManager : NSObject + +/** + A Boolean value indicating whether the manager is enabled. + + If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO. + */ +@property (nonatomic, assign, getter = isEnabled) BOOL enabled; + +/** + A Boolean value indicating whether the network activity indicator manager is currently active. +*/ +@property (readonly, nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; + +/** + A time interval indicating the minimum duration of networking activity that should occur before the activity indicator is displayed. The default value 1 second. If the network activity indicator should be displayed immediately when network activity occurs, this value should be set to 0 seconds. + + Apple's HIG describes the following: + + > Display the network activity indicator to provide feedback when your app accesses the network for more than a couple of seconds. If the operation finishes sooner than that, you don’t have to show the network activity indicator, because the indicator is likely to disappear before users notice its presence. + + */ +@property (nonatomic, assign) NSTimeInterval activationDelay; + +/** + A time interval indicating the duration of time of no networking activity required before the activity indicator is disabled. This allows for continuous display of the network activity indicator across multiple requests. The default value is 0.17 seconds. + */ + +@property (nonatomic, assign) NSTimeInterval completionDelay; + +/** + Returns the shared network activity indicator manager object for the system. + + @return The systemwide network activity indicator manager. + */ ++ (instancetype)sharedManager; + +/** + Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator. + */ +- (void)incrementActivityCount; + +/** + Decrements the number of active network requests. If this number becomes zero after decrementing, this will stop animating the status bar network activity indicator. + */ +- (void)decrementActivityCount; + +/** + Set the a custom method to be executed when the network activity indicator manager should be hidden/shown. By default, this is null, and the UIApplication Network Activity Indicator will be managed automatically. If this block is set, it is the responsiblity of the caller to manager the network activity indicator going forward. + + @param block A block to be executed when the network activity indicator status changes. + */ +- (void)setNetworkingActivityActionWithBlock:(nullable void (^)(BOOL networkActivityIndicatorVisible))block; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m new file mode 100644 index 00000000..440cf7db --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m @@ -0,0 +1,261 @@ +// AFNetworkActivityIndicatorManager.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFNetworkActivityIndicatorManager.h" + +#if TARGET_OS_IOS +#import "AFURLSessionManager.h" + +typedef NS_ENUM(NSInteger, AFNetworkActivityManagerState) { + AFNetworkActivityManagerStateNotActive, + AFNetworkActivityManagerStateDelayingStart, + AFNetworkActivityManagerStateActive, + AFNetworkActivityManagerStateDelayingEnd +}; + +static NSTimeInterval const kDefaultAFNetworkActivityManagerActivationDelay = 1.0; +static NSTimeInterval const kDefaultAFNetworkActivityManagerCompletionDelay = 0.17; + +static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) { + if ([[notification object] respondsToSelector:@selector(originalRequest)]) { + return [(NSURLSessionTask *)[notification object] originalRequest]; + } else { + return nil; + } +} + +typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisible); + +@interface AFNetworkActivityIndicatorManager () +@property (readwrite, nonatomic, assign) NSInteger activityCount; +@property (readwrite, nonatomic, strong) NSTimer *activationDelayTimer; +@property (readwrite, nonatomic, strong) NSTimer *completionDelayTimer; +@property (readonly, nonatomic, getter = isNetworkActivityOccurring) BOOL networkActivityOccurring; +@property (nonatomic, copy) AFNetworkActivityActionBlock networkActivityActionBlock; +@property (nonatomic, assign) AFNetworkActivityManagerState currentState; +@property (nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; + +- (void)updateCurrentStateForNetworkActivityChange; +@end + +@implementation AFNetworkActivityIndicatorManager + ++ (instancetype)sharedManager { + static AFNetworkActivityIndicatorManager *_sharedManager = nil; + static dispatch_once_t oncePredicate; + dispatch_once(&oncePredicate, ^{ + _sharedManager = [[self alloc] init]; + }); + + return _sharedManager; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + self.currentState = AFNetworkActivityManagerStateNotActive; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidResumeNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidCompleteNotification object:nil]; + self.activationDelay = kDefaultAFNetworkActivityManagerActivationDelay; + self.completionDelay = kDefaultAFNetworkActivityManagerCompletionDelay; + + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; + + [_activationDelayTimer invalidate]; + [_completionDelayTimer invalidate]; +} + +- (void)setEnabled:(BOOL)enabled { + _enabled = enabled; + if (enabled == NO) { + [self setCurrentState:AFNetworkActivityManagerStateNotActive]; + } +} + +- (void)setNetworkingActivityActionWithBlock:(void (^)(BOOL networkActivityIndicatorVisible))block { + self.networkActivityActionBlock = block; +} + +- (BOOL)isNetworkActivityOccurring { + @synchronized(self) { + return self.activityCount > 0; + } +} + +- (void)setNetworkActivityIndicatorVisible:(BOOL)networkActivityIndicatorVisible { + if (_networkActivityIndicatorVisible != networkActivityIndicatorVisible) { + [self willChangeValueForKey:@"networkActivityIndicatorVisible"]; + @synchronized(self) { + _networkActivityIndicatorVisible = networkActivityIndicatorVisible; + } + [self didChangeValueForKey:@"networkActivityIndicatorVisible"]; + if (self.networkActivityActionBlock) { + self.networkActivityActionBlock(networkActivityIndicatorVisible); + } else { + [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:networkActivityIndicatorVisible]; + } + } +} + +- (void)setActivityCount:(NSInteger)activityCount { + @synchronized(self) { + _activityCount = activityCount; + } + + dispatch_async(dispatch_get_main_queue(), ^{ + [self updateCurrentStateForNetworkActivityChange]; + }); +} + +- (void)incrementActivityCount { + [self willChangeValueForKey:@"activityCount"]; + @synchronized(self) { + _activityCount++; + } + [self didChangeValueForKey:@"activityCount"]; + + dispatch_async(dispatch_get_main_queue(), ^{ + [self updateCurrentStateForNetworkActivityChange]; + }); +} + +- (void)decrementActivityCount { + [self willChangeValueForKey:@"activityCount"]; + @synchronized(self) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + _activityCount = MAX(_activityCount - 1, 0); +#pragma clang diagnostic pop + } + [self didChangeValueForKey:@"activityCount"]; + + dispatch_async(dispatch_get_main_queue(), ^{ + [self updateCurrentStateForNetworkActivityChange]; + }); +} + +- (void)networkRequestDidStart:(NSNotification *)notification { + if ([AFNetworkRequestFromNotification(notification) URL]) { + [self incrementActivityCount]; + } +} + +- (void)networkRequestDidFinish:(NSNotification *)notification { + if ([AFNetworkRequestFromNotification(notification) URL]) { + [self decrementActivityCount]; + } +} + +#pragma mark - Internal State Management +- (void)setCurrentState:(AFNetworkActivityManagerState)currentState { + @synchronized(self) { + if (_currentState != currentState) { + [self willChangeValueForKey:@"currentState"]; + _currentState = currentState; + switch (currentState) { + case AFNetworkActivityManagerStateNotActive: + [self cancelActivationDelayTimer]; + [self cancelCompletionDelayTimer]; + [self setNetworkActivityIndicatorVisible:NO]; + break; + case AFNetworkActivityManagerStateDelayingStart: + [self startActivationDelayTimer]; + break; + case AFNetworkActivityManagerStateActive: + [self cancelCompletionDelayTimer]; + [self setNetworkActivityIndicatorVisible:YES]; + break; + case AFNetworkActivityManagerStateDelayingEnd: + [self startCompletionDelayTimer]; + break; + } + } + [self didChangeValueForKey:@"currentState"]; + } +} + +- (void)updateCurrentStateForNetworkActivityChange { + if (self.enabled) { + switch (self.currentState) { + case AFNetworkActivityManagerStateNotActive: + if (self.isNetworkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateDelayingStart]; + } + break; + case AFNetworkActivityManagerStateDelayingStart: + //No op. Let the delay timer finish out. + break; + case AFNetworkActivityManagerStateActive: + if (!self.isNetworkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateDelayingEnd]; + } + break; + case AFNetworkActivityManagerStateDelayingEnd: + if (self.isNetworkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateActive]; + } + break; + } + } +} + +- (void)startActivationDelayTimer { + self.activationDelayTimer = [NSTimer + timerWithTimeInterval:self.activationDelay target:self selector:@selector(activationDelayTimerFired) userInfo:nil repeats:NO]; + [[NSRunLoop mainRunLoop] addTimer:self.activationDelayTimer forMode:NSRunLoopCommonModes]; +} + +- (void)activationDelayTimerFired { + if (self.networkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateActive]; + } else { + [self setCurrentState:AFNetworkActivityManagerStateNotActive]; + } +} + +- (void)startCompletionDelayTimer { + [self.completionDelayTimer invalidate]; + self.completionDelayTimer = [NSTimer timerWithTimeInterval:self.completionDelay target:self selector:@selector(completionDelayTimerFired) userInfo:nil repeats:NO]; + [[NSRunLoop mainRunLoop] addTimer:self.completionDelayTimer forMode:NSRunLoopCommonModes]; +} + +- (void)completionDelayTimerFired { + [self setCurrentState:AFNetworkActivityManagerStateNotActive]; +} + +- (void)cancelActivationDelayTimer { + [self.activationDelayTimer invalidate]; +} + +- (void)cancelCompletionDelayTimer { + [self.completionDelayTimer invalidate]; +} + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h new file mode 100644 index 00000000..82973475 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h @@ -0,0 +1,48 @@ +// UIActivityIndicatorView+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +/** + 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 session task. + */ +@interface UIActivityIndicatorView (AFNetworking) + +///---------------------------------- +/// @name Animating for Session Tasks +///---------------------------------- + +/** + Binds the animating state to the state of the specified task. + + @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. + */ +- (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task; + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m new file mode 100644 index 00000000..24c8c76d --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m @@ -0,0 +1,124 @@ +// UIActivityIndicatorView+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "UIActivityIndicatorView+AFNetworking.h" +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFURLSessionManager.h" + +@interface AFActivityIndicatorViewNotificationObserver : NSObject +@property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView; +- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView; + +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task; + +@end + +@implementation UIActivityIndicatorView (AFNetworking) + +- (AFActivityIndicatorViewNotificationObserver *)af_notificationObserver { + AFActivityIndicatorViewNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver)); + if (notificationObserver == nil) { + notificationObserver = [[AFActivityIndicatorViewNotificationObserver alloc] initWithActivityIndicatorView:self]; + objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return notificationObserver; +} + +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { + [[self af_notificationObserver] setAnimatingWithStateOfTask:task]; +} + +@end + +@implementation AFActivityIndicatorViewNotificationObserver + +- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView +{ + self = [super init]; + if (self) { + _activityIndicatorView = activityIndicatorView; + } + return self; +} + +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + + if (task) { + if (task.state != NSURLSessionTaskStateCompleted) { + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" +#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" + if (task.state == NSURLSessionTaskStateRunning) { + [self.activityIndicatorView startAnimating]; + } else { + [self.activityIndicatorView stopAnimating]; + } +#pragma clang diagnostic pop + + [notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingTaskDidResumeNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidCompleteNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidSuspendNotification object:task]; + } + } +} + +#pragma mark - + +- (void)af_startAnimating { + dispatch_async(dispatch_get_main_queue(), ^{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" + [self.activityIndicatorView startAnimating]; +#pragma clang diagnostic pop + }); +} + +- (void)af_stopAnimating { + dispatch_async(dispatch_get_main_queue(), ^{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" + [self.activityIndicatorView stopAnimating]; +#pragma clang diagnostic pop + }); +} + +#pragma mark - + +- (void)dealloc { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; +} + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h new file mode 100644 index 00000000..2f4cdab7 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h @@ -0,0 +1,175 @@ +// UIButton+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFImageDownloader; + +/** + This category adds methods to the UIKit framework's `UIButton` class. The methods in this category provide support for loading remote images and background images asynchronously from a URL. + + @warning Compound values for control `state` (such as `UIControlStateHighlighted | UIControlStateDisabled`) are unsupported. + */ +@interface UIButton (AFNetworking) + +///------------------------------------ +/// @name Accessing the Image Downloader +///------------------------------------ + +/** + Set the shared image downloader used to download images. + + @param imageDownloader The shared image downloader used to download images. +*/ ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; + +/** + The shared image downloader used to download images. + */ ++ (AFImageDownloader *)sharedImageDownloader; + +///-------------------- +/// @name Setting Image +///-------------------- + +/** + Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the image request. + */ +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url; + +/** + Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. + */ +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage; + +/** + Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setImage:forState:` is applied. + + @param state The control state. + @param urlRequest The URL request used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + */ +- (void)setImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + + +///------------------------------- +/// @name Setting Background Image +///------------------------------- + +/** + Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous background image request for the receiver will be cancelled. + + If the background image is cached locally, the background image is set immediately, otherwise the specified placeholder background image will be set immediately, and then the remote background image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the background image request. + */ +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url; + +/** + Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the background image request. + @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. + */ +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage; + +/** + Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setBackgroundImage:forState:` is applied. + + @param state The control state. + @param urlRequest The URL request used for the image request. + @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + */ +- (void)setBackgroundImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + + +///------------------------------ +/// @name Canceling Image Loading +///------------------------------ + +/** + Cancels any executing image task for the specified control state of the receiver, if one exists. + + @param state The control state. + */ +- (void)cancelImageDownloadTaskForState:(UIControlState)state; + +/** + Cancels any executing background image task for the specified control state of the receiver, if one exists. + + @param state The control state. + */ +- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m new file mode 100644 index 00000000..9ea2b995 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m @@ -0,0 +1,305 @@ +// UIButton+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "UIButton+AFNetworking.h" + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "UIImageView+AFNetworking.h" +#import "AFImageDownloader.h" + +@interface UIButton (_AFNetworking) +@end + +@implementation UIButton (_AFNetworking) + +#pragma mark - + +static char AFImageDownloadReceiptNormal; +static char AFImageDownloadReceiptHighlighted; +static char AFImageDownloadReceiptSelected; +static char AFImageDownloadReceiptDisabled; + +static const char * af_imageDownloadReceiptKeyForState(UIControlState state) { + switch (state) { + case UIControlStateHighlighted: + return &AFImageDownloadReceiptHighlighted; + case UIControlStateSelected: + return &AFImageDownloadReceiptSelected; + case UIControlStateDisabled: + return &AFImageDownloadReceiptDisabled; + case UIControlStateNormal: + default: + return &AFImageDownloadReceiptNormal; + } +} + +- (AFImageDownloadReceipt *)af_imageDownloadReceiptForState:(UIControlState)state { + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_imageDownloadReceiptKeyForState(state)); +} + +- (void)af_setImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt + forState:(UIControlState)state +{ + objc_setAssociatedObject(self, af_imageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +static char AFBackgroundImageDownloadReceiptNormal; +static char AFBackgroundImageDownloadReceiptHighlighted; +static char AFBackgroundImageDownloadReceiptSelected; +static char AFBackgroundImageDownloadReceiptDisabled; + +static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState state) { + switch (state) { + case UIControlStateHighlighted: + return &AFBackgroundImageDownloadReceiptHighlighted; + case UIControlStateSelected: + return &AFBackgroundImageDownloadReceiptSelected; + case UIControlStateDisabled: + return &AFBackgroundImageDownloadReceiptDisabled; + case UIControlStateNormal: + default: + return &AFBackgroundImageDownloadReceiptNormal; + } +} + +- (AFImageDownloadReceipt *)af_backgroundImageDownloadReceiptForState:(UIControlState)state { + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state)); +} + +- (void)af_setBackgroundImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt + forState:(UIControlState)state +{ + objc_setAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#pragma mark - + +@implementation UIButton (AFNetworking) + ++ (AFImageDownloader *)sharedImageDownloader { + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; +#pragma clang diagnostic pop +} + ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { + objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url +{ + [self setImageForState:state withURL:url placeholderImage:nil]; +} + +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(UIImage *)placeholderImage +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; + + [self setImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; +} + +- (void)setImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure +{ + if ([self isActiveTaskURLEqualToURLRequest:urlRequest forState:state]) { + return; + } + + [self cancelImageDownloadTaskForState:state]; + + AFImageDownloader *downloader = [[self class] sharedImageDownloader]; + id imageCache = downloader.imageCache; + + //Use the image from the image cache if it exists + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; + if (cachedImage) { + if (success) { + success(urlRequest, nil, cachedImage); + } else { + [self setImage:cachedImage forState:state]; + } + [self af_setImageDownloadReceipt:nil forState:state]; + } else { + if (placeholderImage) { + [self setImage:placeholderImage forState:state]; + } + + __weak __typeof(self)weakSelf = self; + NSUUID *downloadID = [NSUUID UUID]; + AFImageDownloadReceipt *receipt; + receipt = [downloader + downloadImageForURLRequest:urlRequest + withReceiptID:downloadID + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (success) { + success(request, response, responseObject); + } else if(responseObject) { + [strongSelf setImage:responseObject forState:state]; + } + [strongSelf af_setImageDownloadReceipt:nil forState:state]; + } + + } + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (failure) { + failure(request, response, error); + } + [strongSelf af_setImageDownloadReceipt:nil forState:state]; + } + }]; + + [self af_setImageDownloadReceipt:receipt forState:state]; + } +} + +#pragma mark - + +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url +{ + [self setBackgroundImageForState:state withURL:url placeholderImage:nil]; +} + +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; + + [self setBackgroundImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; +} + +- (void)setBackgroundImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure +{ + if ([self isActiveBackgroundTaskURLEqualToURLRequest:urlRequest forState:state]) { + return; + } + + [self cancelImageDownloadTaskForState:state]; + + AFImageDownloader *downloader = [[self class] sharedImageDownloader]; + id imageCache = downloader.imageCache; + + //Use the image from the image cache if it exists + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; + if (cachedImage) { + if (success) { + success(urlRequest, nil, cachedImage); + } else { + [self setBackgroundImage:cachedImage forState:state]; + } + [self af_setBackgroundImageDownloadReceipt:nil forState:state]; + } else { + if (placeholderImage) { + [self setBackgroundImage:placeholderImage forState:state]; + } + + __weak __typeof(self)weakSelf = self; + NSUUID *downloadID = [NSUUID UUID]; + AFImageDownloadReceipt *receipt; + receipt = [downloader + downloadImageForURLRequest:urlRequest + withReceiptID:downloadID + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (success) { + success(request, response, responseObject); + } else if(responseObject) { + [strongSelf setBackgroundImage:responseObject forState:state]; + } + [strongSelf af_setImageDownloadReceipt:nil forState:state]; + } + + } + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (failure) { + failure(request, response, error); + } + [strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state]; + } + }]; + + [self af_setBackgroundImageDownloadReceipt:receipt forState:state]; + } +} + +#pragma mark - + +- (void)cancelImageDownloadTaskForState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state]; + if (receipt != nil) { + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt]; + [self af_setImageDownloadReceipt:nil forState:state]; + } +} + +- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state]; + if (receipt != nil) { + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt]; + [self af_setBackgroundImageDownloadReceipt:nil forState:state]; + } +} + +- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state]; + return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; +} + +- (BOOL)isActiveBackgroundTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state]; + return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; +} + + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h new file mode 100644 index 00000000..14744cdd --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h @@ -0,0 +1,35 @@ +// +// UIImage+AFNetworking.h +// +// +// Created by Paulo Ferreira on 08/07/15. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +@interface UIImage (AFNetworking) + ++ (UIImage*) safeImageWithData:(NSData*)data; + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h new file mode 100644 index 00000000..06df54ac --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h @@ -0,0 +1,109 @@ +// UIImageView+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFImageDownloader; + +/** + This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL. + */ +@interface UIImageView (AFNetworking) + +///------------------------------------ +/// @name Accessing the Image Downloader +///------------------------------------ + +/** + Set the shared image downloader used to download images. + + @param imageDownloader The shared image downloader used to download images. + */ ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; + +/** + The shared image downloader used to download images. + */ ++ (AFImageDownloader *)sharedImageDownloader; + +///-------------------- +/// @name Setting Image +///-------------------- + +/** + Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` + + @param url The URL used for the image request. + */ +- (void)setImageWithURL:(NSURL *)url; + +/** + Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` + + @param url The URL used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. + */ +- (void)setImageWithURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage; + +/** + Asynchronously downloads an image from the specified URL request, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is applied. + + @param urlRequest The URL request used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + */ +- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + +/** + Cancels any executing image operation for the receiver, if one exists. + */ +- (void)cancelImageDownloadTask; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m new file mode 100644 index 00000000..b4189305 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m @@ -0,0 +1,161 @@ +// UIImageView+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "UIImageView+AFNetworking.h" + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFImageDownloader.h" + +@interface UIImageView (_AFNetworking) +@property (readwrite, nonatomic, strong, setter = af_setActiveImageDownloadReceipt:) AFImageDownloadReceipt *af_activeImageDownloadReceipt; +@end + +@implementation UIImageView (_AFNetworking) + +- (AFImageDownloadReceipt *)af_activeImageDownloadReceipt { + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, @selector(af_activeImageDownloadReceipt)); +} + +- (void)af_setActiveImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt { + objc_setAssociatedObject(self, @selector(af_activeImageDownloadReceipt), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#pragma mark - + +@implementation UIImageView (AFNetworking) + ++ (AFImageDownloader *)sharedImageDownloader { + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; +#pragma clang diagnostic pop +} + ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { + objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)setImageWithURL:(NSURL *)url { + [self setImageWithURL:url placeholderImage:nil]; +} + +- (void)setImageWithURL:(NSURL *)url + placeholderImage:(UIImage *)placeholderImage +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; + + [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; +} + +- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(UIImage *)placeholderImage + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure +{ + + if ([urlRequest URL] == nil) { + [self cancelImageDownloadTask]; + self.image = placeholderImage; + return; + } + + if ([self isActiveTaskURLEqualToURLRequest:urlRequest]){ + return; + } + + [self cancelImageDownloadTask]; + + AFImageDownloader *downloader = [[self class] sharedImageDownloader]; + id imageCache = downloader.imageCache; + + //Use the image from the image cache if it exists + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; + if (cachedImage) { + if (success) { + success(urlRequest, nil, cachedImage); + } else { + self.image = cachedImage; + } + [self clearActiveDownloadInformation]; + } else { + if (placeholderImage) { + self.image = placeholderImage; + } + + __weak __typeof(self)weakSelf = self; + NSUUID *downloadID = [NSUUID UUID]; + AFImageDownloadReceipt *receipt; + receipt = [downloader + downloadImageForURLRequest:urlRequest + withReceiptID:downloadID + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { + if (success) { + success(request, response, responseObject); + } else if(responseObject) { + strongSelf.image = responseObject; + } + [strongSelf clearActiveDownloadInformation]; + } + + } + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { + if (failure) { + failure(request, response, error); + } + [strongSelf clearActiveDownloadInformation]; + } + }]; + + self.af_activeImageDownloadReceipt = receipt; + } +} + +- (void)cancelImageDownloadTask { + if (self.af_activeImageDownloadReceipt != nil) { + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:self.af_activeImageDownloadReceipt]; + [self clearActiveDownloadInformation]; + } +} + +- (void)clearActiveDownloadInformation { + self.af_activeImageDownloadReceipt = nil; +} + +- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest { + return [self.af_activeImageDownloadReceipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; +} + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h new file mode 100644 index 00000000..8f1590be --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h @@ -0,0 +1,42 @@ +// UIKit+AFNetworking.h +// +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if TARGET_OS_IOS || TARGET_OS_TV +#import + +#ifndef _UIKIT_AFNETWORKING_ + #define _UIKIT_AFNETWORKING_ + +#if TARGET_OS_IOS + #import "AFAutoPurgingImageCache.h" + #import "AFImageDownloader.h" + #import "AFNetworkActivityIndicatorManager.h" + #import "UIRefreshControl+AFNetworking.h" + #import "UIWebView+AFNetworking.h" +#endif + + #import "UIActivityIndicatorView+AFNetworking.h" + #import "UIButton+AFNetworking.h" + #import "UIImageView+AFNetworking.h" + #import "UIProgressView+AFNetworking.h" +#endif /* _UIKIT_AFNETWORKING_ */ +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h new file mode 100644 index 00000000..c9d7e3e2 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h @@ -0,0 +1,64 @@ +// UIProgressView+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +NS_ASSUME_NONNULL_BEGIN + + +/** + 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. + */ +@interface UIProgressView (AFNetworking) + +///------------------------------------ +/// @name Setting Session Task Progress +///------------------------------------ + +/** + Binds the progress to the upload progress of the specified session task. + + @param task The session task. + @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. + */ +- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task + animated:(BOOL)animated; + +/** + Binds the progress to the download progress of the specified session task. + + @param task The session task. + @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. + */ +- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task + animated:(BOOL)animated; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m new file mode 100644 index 00000000..5934a617 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m @@ -0,0 +1,118 @@ +// UIProgressView+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "UIProgressView+AFNetworking.h" + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFURLSessionManager.h" + +static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext; +static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext; + +#pragma mark - + +@implementation UIProgressView (AFNetworking) + +- (BOOL)af_uploadProgressAnimated { + return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_uploadProgressAnimated)) boolValue]; +} + +- (void)af_setUploadProgressAnimated:(BOOL)animated { + objc_setAssociatedObject(self, @selector(af_uploadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (BOOL)af_downloadProgressAnimated { + return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_downloadProgressAnimated)) boolValue]; +} + +- (void)af_setDownloadProgressAnimated:(BOOL)animated { + objc_setAssociatedObject(self, @selector(af_downloadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task + animated:(BOOL)animated +{ + [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; + [task addObserver:self forKeyPath:@"countOfBytesSent" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; + + [self af_setUploadProgressAnimated:animated]; +} + +- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task + animated:(BOOL)animated +{ + [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; + [task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; + + [self af_setDownloadProgressAnimated:animated]; +} + +#pragma mark - NSKeyValueObserving + +- (void)observeValueForKeyPath:(NSString *)keyPath + ofObject:(id)object + change:(__unused NSDictionary *)change + context:(void *)context +{ + if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) { + if ([object countOfBytesExpectedToSend] > 0) { + dispatch_async(dispatch_get_main_queue(), ^{ + [self setProgress:[object countOfBytesSent] / ([object countOfBytesExpectedToSend] * 1.0f) animated:self.af_uploadProgressAnimated]; + }); + } + } + + if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) { + if ([object countOfBytesExpectedToReceive] > 0) { + dispatch_async(dispatch_get_main_queue(), ^{ + [self setProgress:[object countOfBytesReceived] / ([object countOfBytesExpectedToReceive] * 1.0f) animated:self.af_downloadProgressAnimated]; + }); + } + } + + if ([keyPath isEqualToString:NSStringFromSelector(@selector(state))]) { + if ([(NSURLSessionTask *)object state] == NSURLSessionTaskStateCompleted) { + @try { + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(state))]; + + if (context == AFTaskCountOfBytesSentContext) { + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))]; + } + + if (context == AFTaskCountOfBytesReceivedContext) { + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))]; + } + } + @catch (NSException * __unused exception) {} + } + } + } +} + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h new file mode 100644 index 00000000..a6e598e8 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h @@ -0,0 +1,53 @@ +// UIRefreshControl+AFNetworking.m +// +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + 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 session task. + */ +@interface UIRefreshControl (AFNetworking) + +///----------------------------------- +/// @name Refreshing for Session Tasks +///----------------------------------- + +/** + Binds the refreshing state to the state of the specified task. + + @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. + */ +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m new file mode 100644 index 00000000..d40d01ff --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m @@ -0,0 +1,122 @@ +// UIRefreshControl+AFNetworking.m +// +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "UIRefreshControl+AFNetworking.h" +#import + +#if TARGET_OS_IOS + +#import "AFURLSessionManager.h" + +@interface AFRefreshControlNotificationObserver : NSObject +@property (readonly, nonatomic, weak) UIRefreshControl *refreshControl; +- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl; + +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; + +@end + +@implementation UIRefreshControl (AFNetworking) + +- (AFRefreshControlNotificationObserver *)af_notificationObserver { + AFRefreshControlNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver)); + if (notificationObserver == nil) { + notificationObserver = [[AFRefreshControlNotificationObserver alloc] initWithActivityRefreshControl:self]; + objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return notificationObserver; +} + +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { + [[self af_notificationObserver] setRefreshingWithStateOfTask:task]; +} + +@end + +@implementation AFRefreshControlNotificationObserver + +- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl +{ + self = [super init]; + if (self) { + _refreshControl = refreshControl; + } + return self; +} + +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + + if (task) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" +#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" + if (task.state == NSURLSessionTaskStateRunning) { + [self.refreshControl beginRefreshing]; + + [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingTaskDidResumeNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidCompleteNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidSuspendNotification object:task]; + } else { + [self.refreshControl endRefreshing]; + } +#pragma clang diagnostic pop + } +} + +#pragma mark - + +- (void)af_beginRefreshing { + dispatch_async(dispatch_get_main_queue(), ^{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" + [self.refreshControl beginRefreshing]; +#pragma clang diagnostic pop + }); +} + +- (void)af_endRefreshing { + dispatch_async(dispatch_get_main_queue(), ^{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreceiver-is-weak" + [self.refreshControl endRefreshing]; +#pragma clang diagnostic pop + }); +} + +#pragma mark - + +- (void)dealloc { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; +} + +@end + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h new file mode 100644 index 00000000..41c3fb21 --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h @@ -0,0 +1,80 @@ +// UIWebView+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFHTTPSessionManager; + +/** + 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. + + @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. + */ +@interface UIWebView (AFNetworking) + +/** + The session manager used to download all requests. + */ +@property (nonatomic, strong) AFHTTPSessionManager *sessionManager; + +/** + Asynchronously loads the specified request. + + @param request A URL request identifying the location of the content to load. This must not be `nil`. + @param progress A progress object monitoring the current download progress. + @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. + @param failure A block object to be executed when the data task 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. + */ +- (void)loadRequest:(NSURLRequest *)request + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success + failure:(nullable void (^)(NSError *error))failure; + +/** + Asynchronously loads the data associated with a particular request with a specified MIME type and text encoding. + + @param request A URL request identifying the location of the content to load. This must not be `nil`. + @param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified. + @param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified. +@param progress A progress object monitoring the current download progress. + @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. + @param failure A block object to be executed when the data task 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. + */ +- (void)loadRequest:(NSURLRequest *)request + MIMEType:(nullable NSString *)MIMEType + textEncodingName:(nullable NSString *)textEncodingName + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success + failure:(nullable void (^)(NSError *error))failure; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m new file mode 100644 index 00000000..5bc2c79d --- /dev/null +++ b/its/plugin/projects/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m @@ -0,0 +1,162 @@ +// UIWebView+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "UIWebView+AFNetworking.h" + +#import + +#if TARGET_OS_IOS + +#import "AFHTTPSessionManager.h" +#import "AFURLResponseSerialization.h" +#import "AFURLRequestSerialization.h" + +@interface UIWebView (_AFNetworking) +@property (readwrite, nonatomic, strong, setter = af_setURLSessionTask:) NSURLSessionDataTask *af_URLSessionTask; +@end + +@implementation UIWebView (_AFNetworking) + +- (NSURLSessionDataTask *)af_URLSessionTask { + return (NSURLSessionDataTask *)objc_getAssociatedObject(self, @selector(af_URLSessionTask)); +} + +- (void)af_setURLSessionTask:(NSURLSessionDataTask *)af_URLSessionTask { + objc_setAssociatedObject(self, @selector(af_URLSessionTask), af_URLSessionTask, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#pragma mark - + +@implementation UIWebView (AFNetworking) + +- (AFHTTPSessionManager *)sessionManager { + static AFHTTPSessionManager *_af_defaultHTTPSessionManager = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _af_defaultHTTPSessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + _af_defaultHTTPSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer]; + _af_defaultHTTPSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer]; + }); + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + return objc_getAssociatedObject(self, @selector(sessionManager)) ?: _af_defaultHTTPSessionManager; +#pragma clang diagnostic pop +} + +- (void)setSessionManager:(AFHTTPSessionManager *)sessionManager { + objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (AFHTTPResponseSerializer *)responseSerializer { + static AFHTTPResponseSerializer *_af_defaultResponseSerializer = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer]; + }); + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer; +#pragma clang diagnostic pop +} + +- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { + objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)loadRequest:(NSURLRequest *)request + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success + failure:(void (^)(NSError *error))failure +{ + [self loadRequest:request MIMEType:nil textEncodingName:nil progress:progress success:^NSData *(NSHTTPURLResponse *response, NSData *data) { + NSStringEncoding stringEncoding = NSUTF8StringEncoding; + if (response.textEncodingName) { + CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName); + if (encoding != kCFStringEncodingInvalidId) { + stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding); + } + } + + NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding]; + if (success) { + string = success(response, string); + } + + return [string dataUsingEncoding:stringEncoding]; + } failure:failure]; +} + +- (void)loadRequest:(NSURLRequest *)request + MIMEType:(NSString *)MIMEType + textEncodingName:(NSString *)textEncodingName + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(NSData * (^)(NSHTTPURLResponse *response, NSData *data))success + failure:(void (^)(NSError *error))failure +{ + NSParameterAssert(request); + + if (self.af_URLSessionTask.state == NSURLSessionTaskStateRunning || self.af_URLSessionTask.state == NSURLSessionTaskStateSuspended) { + [self.af_URLSessionTask cancel]; + } + self.af_URLSessionTask = nil; + + __weak __typeof(self)weakSelf = self; + NSURLSessionDataTask *dataTask; + dataTask = [self.sessionManager + GET:request.URL.absoluteString + parameters:nil + progress:nil + success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) { + __strong __typeof(weakSelf) strongSelf = weakSelf; + if (success) { + success((NSHTTPURLResponse *)task.response, responseObject); + } + [strongSelf loadData:responseObject MIMEType:MIMEType textEncodingName:textEncodingName baseURL:[task.currentRequest URL]]; + + if ([strongSelf.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) { + [strongSelf.delegate webViewDidFinishLoad:strongSelf]; + } + } + failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) { + if (failure) { + failure(error); + } + }]; + self.af_URLSessionTask = dataTask; + if (progress != nil) { + *progress = [self.sessionManager downloadProgressForTask:dataTask]; + } + [self.af_URLSessionTask resume]; + + if ([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) { + [self.delegate webViewDidStartLoad:self]; + } +} + +@end + +#endif \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env b/its/plugin/projects/AFNetworking/fastlane/.env new file mode 100644 index 00000000..46a98e83 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env @@ -0,0 +1,10 @@ +AF_WORKSPACE="AFNetworking.xcworkspace" + +AF_IOS_FRAMEWORK_SCHEME="AFNetworking iOS" +AF_TVOS_FRAMEWORK_SCHEME="AFNetworking tvOS" +AF_OSX_FRAMEWORK_SCHEME="AFNetworking OS X" + +AF_IOS_EXAMPLE_SCHEME="iOS Example" +AF_TVOS_EXAMPLE_SCHEME="tvOS Example" +AF_OSX_EXAMPLE_SCHEME="OS X Example" + diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.default b/its/plugin/projects/AFNetworking/fastlane/.env.default new file mode 100644 index 00000000..be94c17a --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.default @@ -0,0 +1,15 @@ +AF_IOS_SDK=iphonesimulator9.2 +AF_MAC_SDK=macosx10.11 +AF_TVOS_SDK=appletvsimulator9.1 + +AF_CONFIGURATION=Release + +SCAN_WORKSPACE=$AF_WORKSPACE +SCAN_SCHEME=$AF_IOS_FRAMEWORK_SCHEME +SCAN_DESTINATION="OS=9.2,name=iPhone 6s" +SCAN_SDK=$AF_IOS_SDK +SCAN_OUTPUT_DIRECTORY=fastlane/test-output + +EXAMPLE_WORKSPACE=$AF_WORKSPACE +EXAMPLE_SCHEME=$AF_IOS_EXAMPLE_SCHEME +EXAMPLE_DESTINATION=$SCAN_DESTINATION \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.deploy b/its/plugin/projects/AFNetworking/fastlane/.env.deploy new file mode 100644 index 00000000..a123e622 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.deploy @@ -0,0 +1,14 @@ +DEPLOY_BRANCH=master +DEPLOY_PLIST_PATH=Framework/Info.plist +DEPLOY_PODSPEC=AFNetworking.podspec +DEPLOY_REMOTE=origin + +DEPLOY_CHANGELOG_PATH=CHANGELOG.md +DEPLOY_CHANGELOG_DELIMITER=--- + +# Used for CHANGELOG Generation and Github Release Management +GITHUB_OWNER=AFNetworking +GITHUB_REPOSITORY=AFNetworking +# CI Should Provide GITHUB_API_TOKEN + +CARTHAGE_FRAMEWORK_NAME=AFNetworking \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.ios81_xcode7 b/its/plugin/projects/AFNetworking/fastlane/.env.ios81_xcode7 new file mode 100644 index 00000000..fb6f3715 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.ios81_xcode7 @@ -0,0 +1,3 @@ +SCAN_DESTINATION="OS=8.1,name=iPhone 4S" +EXAMPLE_DESTINATION=$SCAN_DESTINATION +SCAN_SDK=iphonesimulator9.0 \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.ios83 b/its/plugin/projects/AFNetworking/fastlane/.env.ios83 new file mode 100644 index 00000000..0d6dca99 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.ios83 @@ -0,0 +1,2 @@ +SCAN_DESTINATION="OS=8.3,name=iPhone 5S" +EXAMPLE_DESTINATION=$SCAN_DESTINATION \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.ios84 b/its/plugin/projects/AFNetworking/fastlane/.env.ios84 new file mode 100644 index 00000000..5c20969d --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.ios84 @@ -0,0 +1,2 @@ +SCAN_DESTINATION="OS=8.4,name=iPhone 6" +EXAMPLE_DESTINATION=$SCAN_DESTINATION \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.ios90_xcode7 b/its/plugin/projects/AFNetworking/fastlane/.env.ios90_xcode7 new file mode 100644 index 00000000..e89b458d --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.ios90_xcode7 @@ -0,0 +1,3 @@ +SCAN_DESTINATION="OS=9.0,name=iPhone 6 Plus" +EXAMPLE_DESTINATION=$SCAN_DESTINATION +SCAN_SDK=iphonesimulator9.0 \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.ios91_xcode71 b/its/plugin/projects/AFNetworking/fastlane/.env.ios91_xcode71 new file mode 100644 index 00000000..5f8dd00c --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.ios91_xcode71 @@ -0,0 +1,3 @@ +SCAN_DESTINATION="OS=9.1,name=iPhone 6s" +EXAMPLE_DESTINATION=$SCAN_DESTINATION +SCAN_SDK=iphonesimulator9.1 \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.ios92 b/its/plugin/projects/AFNetworking/fastlane/.env.ios92 new file mode 100644 index 00000000..67e5e829 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.ios92 @@ -0,0 +1,2 @@ +SCAN_DESTINATION="OS=9.2,name=iPhone 6s" +EXAMPLE_DESTINATION=$SCAN_DESTINATION \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.ios93_xcode73 b/its/plugin/projects/AFNetworking/fastlane/.env.ios93_xcode73 new file mode 100644 index 00000000..b0516eb0 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.ios93_xcode73 @@ -0,0 +1,3 @@ +SCAN_DESTINATION="OS=9.3,name=iPhone 6s" +EXAMPLE_DESTINATION=$SCAN_DESTINATION +SCAN_SDK=iphonesimulator9.3 \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.osx b/its/plugin/projects/AFNetworking/fastlane/.env.osx new file mode 100644 index 00000000..d56e363c --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.osx @@ -0,0 +1,6 @@ +SCAN_SCHEME=$AF_OSX_FRAMEWORK_SCHEME +SCAN_DESTINATION="arch=x86_64" +SCAN_SDK=$AF_OSX_SDK + +EXAMPLE_SCHEME=$AF_OSX_EXAMPLE_SCHEME +EXAMPLE_DESTINATION=$SCAN_DESTINATION \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.tvos90_xcode71 b/its/plugin/projects/AFNetworking/fastlane/.env.tvos90_xcode71 new file mode 100644 index 00000000..98da9c0c --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.tvos90_xcode71 @@ -0,0 +1,6 @@ +SCAN_SCHEME=$AF_TVOS_FRAMEWORK_SCHEME +SCAN_DESTINATION="OS=9.0,name=Apple TV 1080p" +SCAN_SDK=appletvsimulator9.0 + +EXAMPLE_SCHEME=$AF_TVOS_EXAMPLE_SCHEME +EXAMPLE_DESTINATION=$SCAN_DESTINATION \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/.env.tvos91 b/its/plugin/projects/AFNetworking/fastlane/.env.tvos91 new file mode 100644 index 00000000..54cd02b3 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/.env.tvos91 @@ -0,0 +1,6 @@ +SCAN_SCHEME=$AF_TVOS_FRAMEWORK_SCHEME +SCAN_DESTINATION="OS=9.1,name=Apple TV 1080p" +SCAN_SDK=$AF_TVOS_SDK + +EXAMPLE_SCHEME=$AF_TVOS_EXAMPLE_SCHEME +EXAMPLE_DESTINATION=$SCAN_DESTINATION \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/Fastfile b/its/plugin/projects/AFNetworking/fastlane/Fastfile new file mode 100644 index 00000000..6a63d4c4 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/Fastfile @@ -0,0 +1,337 @@ +# Customise this file, documentation can be found here: +# https://github.com/KrauseFx/fastlane/tree/master/docs +# All available actions: https://github.com/KrauseFx/fastlane/blob/master/docs/Actions.md +# can also be listed using the `fastlane actions` command + +# Change the syntax highlighting to Ruby +# All lines starting with a # are ignored when running `fastlane` + +# By default, fastlane will send which actions are used +# No personal data is shared, more information on https://github.com/fastlane/enhancer +# Uncomment the following line to opt out +# opt_out_usage + +# If you want to automatically update fastlane if a new version is available: +# update_fastlane + +# This is the minimum version number required. +# Update this, if you use features of a newer version +fastlane_version "1.37.0" +before_all do + # ENV["SLACK_URL"] = "https://hooks.slack.com/services/..." +end + +#Test Lanes +desc "Runs tests and builds example for the given environment" +desc "The lane to run by ci on every commit This lanes calls the lane `test_framework`." +desc "####Example:" +desc "```\nfastlane ci_commit configuration:Debug --env ios91\n```" +desc "####Options" +desc " * **`configuration`**: The build configuration to use. (`AF_CONFIGURATION`)" +desc "" +lane :ci_commit do |options| + if options[:configuration] + configuration = options[:configuration] + elsif ENV["AF_CONFIGURATION"] + configuration = ENV["AF_CONFIGURATION"] + else + configuration = "Release" + end + + test_framework(configuration: configuration) + + af_pod_spec_lint( + quick:true + ) +end + +desc "Runs all tests for the given environment" +desc "Set `scan` action environment variables to control test configuration" +desc "####Example:" +desc "```\nfastlane test_framework configuration:Debug --env ios91\n```" +desc "####Options" +desc " * **`configuration`**: The build configuration to use." +desc "" +lane :test_framework do |options| + scan( + configuration: options[:configuration] + ) + +end + +desc "Produces code coverage information" +desc "Set `scan` action environment variables to control test configuration" +desc "####Example:" +desc "```\nfastlane code_coverage configuration:Debug\n```" +desc "####Options" +desc " * **`configuration`**: The build configuration to use. The only supported configuration is the `Debug` configuration." +desc "" +lane :code_coverage do |options| + if options[:configuration] != "Debug" + Helper.log.info "Not running code coverage lane for #{options[:configuration]} configuration".yellow + else + scan( + configuration: options[:configuration], + xcargs: "OBJROOT=build GCC_GENERATE_TEST_COVERAGE_FILES=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES" + ) + end +end + + +#Deployment Lanes +desc "Prepares the framework for release" +desc "This lane should be run from your local machine, and will push a tag to the remote when finished." +desc " * Verifies the git branch is clean" +desc " * Ensures the lane is running on the master branch" +desc " * Verifies the Github milestone is ready for release" +desc " * Pulls the remote to verify the latest the branch is up to date" +desc " * Updates the version of the info plist path used by the framework" +desc " * Updates the the version of the podspec" +desc " * Generates a changelog based on the Github milestone" +desc " * Updates the changelog file" +desc " * Commits the changes" +desc " * Pushes the commited branch" +desc " * Creates a tag" +desc " * Pushes the tag" +desc "####Example:" +desc "```\nfastlane prepare_framework_release version:3.0.0 --env deploy\n```" +desc "####Options" +desc "It is recommended to manage these options through a .env file. See `fastlane/.env.deploy` for an example." +desc " * **`version`** (required): The new version of the framework" +desc " * **`allow_dirty_branch`**: Allows the git branch to be dirty before continuing. Defaults to false" +desc " * **`remote`**: The name of the git remote. Defaults to `origin`. (`DEPLOY_REMOTE`)" +desc " * **`allow_branch`**: The name of the branch to build from. Defaults to `master`. (`DEPLOY_BRANCH`)" +desc " * **`skip_validate_github_milestone`**: Skips validating a Github milestone. Defaults to false" +desc " * **`skip_git_pull`**: Skips pulling the git remote. Defaults to false" +desc " * **`skip_plist_update`**: Skips updating the version of the info plist. Defaults to false" +desc " * **`plist_path`**: The path of the plist file to update. (`DEPLOY_PLIST_PATH`)" +desc " * **`skip_podspec_update`**: Skips updating the version of the podspec. Defaults to false" +desc " * **`podspec`**: The path of the podspec file to update. (`DEPLOY_PODSPEC`)" +desc " * **`skip_changelog`**: Skip generating a changelog. Defaults to false." +desc " * **`changelog_path`**: The path to the changelog file. (`DEPLOY_CHANGELOG_PATH`)" +desc " * **`changelog_insert_delimiter`**: The delimiter to insert the changelog after. (`DEPLOY_CHANGELOG_DELIMITER`)" +desc "" + +lane :prepare_framework_release do |options| + if !options[:version] + raise "No version specified!".red + end + + #Ensure the branch is clean + if options[:allow_dirty_branch] != true + ensure_git_status_clean + end + + remote = options[:remote] ? options[:remote] : (ENV["DEPLOY_REMOTE"] ? ENV["DEPLOY_REMOTE"] : "origin") + allowed_branch = options[:allow_branch] ? options[:allow_branch] : (ENV["DEPLOY_BRANCH"] ? ENV["DEPLOY_BRANCH"] : "master") + + #Ensure we are on the right branch + ensure_git_branch( + branch:allowed_branch + ) + + #Verify the Github milestone is ready for release + if options[:skip_validate_github_milestone] != true + af_get_github_milestone( + title: options[:version], + verify_for_release:true + ) + end + + #Pull the latest to ensure we are up to date + if options[:skip_git_pull] != true + sh("git pull #{remote} #{allowed_branch}") + end + + #Update the framework plist + if options[:skip_plist_update] != true + plist_path = options[:plist_path] ? options[:plist_path] : ENV["DEPLOY_PLIST_PATH"] + set_info_plist_value( + path: plist_path, + key: "CFBundleVersion", + value: options[:version] + ) + end + + #Update the podspec + if options[:skip_podspec_update] != true + podspec = options[:podpsec] ? options[:podpsec] : ENV["DEPLOY_PODSPEC"] + version_bump_podspec( + path: podspec, + version_number: options[:version] + ) + + end + + #Generate a Changelog + if options[:skip_changelog] != true + changelog = af_generate_github_milestone_changelog( + milestone: options[:version] + ) + + Helper.log.info "Generated Changelog: #{changelog[:title]} #{changelog[:header]} #{changelog[:changelog]}" + + changelog_path = options[:changelog_path] ? options[:changelog_path] : ENV["DEPLOY_CHANGELOG_PATH"] + changelog_insert_delimiter = options[:changelog_insert_delimiter] ? options[:changelog_insert_delimiter] : ENV["DEPLOY_CHANGELOG_DELIMITER"] + af_insert_text_into_file( + file_path: changelog_path, + text: changelog[:title] + changelog[:header] + changelog[:changelog], + insert_delimiter: changelog_insert_delimiter + ) + end + + if prompt(text: "#{options[:version]} has been prepped for release. If you have any additional changes you would like to make to the README or CHANGELOG, please do those before continuing. Would you like to commit, tag, and push #{options[:version]} to #{remote}?".green, boolean: true,ci_input:"y") + + # commit the branch + git_commit( + path: ".", + message: "Preparing for the #{options[:version]} release" + ) + + #push the branch + push_to_git_remote( + remote: remote + ) + + # tag the repo + add_git_tag( + tag: "#{options[:version]}" + ) + + # push the tag + if options [:skip_push_tags] != true + af_push_git_tags_to_remote( + remote: remote + ) + end + + if !is_ci + notification( + title: "Release Preparation Complete", + message: "The tag #{options[:version]} is now available" + ) + end + + else + Helper.log.info "When finished, commit your changes and create your tag.".red + end +end + + +desc "Completes the framework release" +desc "This lane should be from a CI machine, after the tests have passed on the tag build. This lane does the following:" +desc " * Verifies the git branch is clean" +desc " * Ensures the lane is running on the master branch" +desc " * Pulls the remote to verify the latest the branch is up to date" +desc " * Generates a changelog for the Github Release" +desc " * Creates a Github Release" +desc " * Builds Carthage Frameworks" +desc " * Uploads Carthage Framework to Github Release" +desc " * Pushes podspec to pod trunk" +desc " * Lints the pod spec to ensure it is valid" +desc " * Closes the associated Github milestone" +desc "####Example:" +desc "```\nfastlane complete_framework_release --env deploy\n```" +desc "####Options" +desc "It is recommended to manage these options through a .env file. See `fastlane/.env.deploy` for an example." +desc " * **`version`** (required): The new version of the framework. Defaults to the last tag in the repo" +desc " * **`allow_dirty_branch`**: Allows the git branch to be dirty before continuing. Defaults to false" +desc " * **`remote`**: The name of the git remote. Defaults to `origin`. (`DEPLOY_REMOTE`)" +desc " * **`allow_branch`**: The name of the branch to build from. Defaults to `master`. (`DEPLOY_BRANCH`)" +desc " * **`skip_github_release`**: Skips creating a Github release. Defaults to false" +desc " * **`skip_carthage_framework`**: Skips creating a carthage framework. If building a swift framework, this should be disabled. Defaults to false." +desc " * **`skip_pod_push`**: Skips pushing the podspec to trunk." +desc " * **`skip_podspec_update`**: Skips updating the version of the podspec. Defaults to false" +desc " * **`skip_closing_github_milestone`**: Skips closing the associated Github milestone. Defaults to false" +desc "" +lane :complete_framework_release do |options| + if options[:skip_ci_check] != true + if !is_ci + raise "#{lane_context[SharedValues::LANE_NAME]} should be run from a CI machine. If you want to override this, pass 'skip_ci_check:true'".red + end + end + + version = options[:version] ? options[:version] : last_git_tag.strip + Helper.log.info "Using version #{version}" + + #Ensure clean branch + if options[:allow_dirty_branch] != true + ensure_git_status_clean + end + + remote = options[:remote] ? options[:remote] : (ENV["DEPLOY_REMOTE"] ? ENV["DEPLOY_REMOTE"] : "origin") + allowed_branch = options[:allow_branch] ? options[:allow_branch] : (ENV["DEPLOY_BRANCH"] ? ENV["DEPLOY_BRANCH"] : "master") + + #Ensure we are on the right branch + ensure_git_branch( + branch:allowed_branch + ) + + #Pull the latest to ensure we are up to date + if options[:skip_git_pull] != true + sh("git pull #{remote} #{allowed_branch}") + end + + # Create a release + #* Upload Notes + #* Upload Carthage Asset + if options[:skip_github_release] != true + af_generate_github_milestone_changelog( + milestone: version + ) + + body = lane_context[SharedValues::GITHUB_MILESTONE_CHANGELOG][:header] + lane_context[SharedValues::GITHUB_MILESTONE_CHANGELOG][:changelog] + af_create_github_release( + tag_name: version, + name: version, + body: body + ) + + # generate the carthage zip + if options[:skip_carthage_framework] != true + af_build_carthage_frameworks + + af_upload_asset_for_github_release( + file_path:lane_context[SharedValues::CARTHAGE_FRAMEWORK] + ) + + end + end + + #pod trunk push + if options[:skip_pod_push] != true + pod_push + + #pod spec lint + af_pod_spec_lint + end + + if options[:skip_closing_github_milestone] != true + af_get_github_milestone( + title: version + ) + + af_update_github_milestone( + state: "closed" + ) + end +end + + +after_all do |lane| + # This block is called, only if the executed lane was successful + + # slack( + # message: "Successfully deployed new App Update." + # ) +end + +error do |lane, exception| + # slack( + # message: exception.message, + # success: false + # ) +end + +# More information about multiple platforms in fastlane: https://github.com/KrauseFx/fastlane/blob/master/docs/Platforms.md +# All available actions: https://github.com/KrauseFx/fastlane/blob/master/docs/Actions.md diff --git a/its/plugin/projects/AFNetworking/fastlane/README.md b/its/plugin/projects/AFNetworking/fastlane/README.md new file mode 100644 index 00000000..f32f19ea --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/README.md @@ -0,0 +1,196 @@ +fastlane documentation +================ +# Installation +``` +sudo gem install fastlane +``` +# Available Actions +### ci_commit +``` +fastlane ci_commit +``` +Runs tests and builds example for the given environment + +The lane to run by ci on every commit This lanes calls the lane `test_framework`. + +####Example: + +``` +fastlane ci_commit configuration:Debug --env ios91 +``` + +####Options + + * **`configuration`**: The build configuration to use. (`AF_CONFIGURATION`) + + +### test_framework +``` +fastlane test_framework +``` +Runs all tests for the given environment + +Set `scan` action environment variables to control test configuration + +####Example: + +``` +fastlane test_framework configuration:Debug --env ios91 +``` + +####Options + + * **`configuration`**: The build configuration to use. + + +### code_coverage +``` +fastlane code_coverage +``` +Produces code coverage information + +Set `scan` action environment variables to control test configuration + +####Example: + +``` +fastlane code_coverage configuration:Debug +``` + +####Options + + * **`configuration`**: The build configuration to use. The only supported configuration is the `Debug` configuration. + + +### prepare_framework_release +``` +fastlane prepare_framework_release +``` +Prepares the framework for release + +This lane should be run from your local machine, and will push a tag to the remote when finished. + + * Verifies the git branch is clean + + * Ensures the lane is running on the master branch + + * Verifies the Github milestone is ready for release + + * Pulls the remote to verify the latest the branch is up to date + + * Updates the version of the info plist path used by the framework + + * Updates the the version of the podspec + + * Generates a changelog based on the Github milestone + + * Updates the changelog file + + * Commits the changes + + * Pushes the commited branch + + * Creates a tag + + * Pushes the tag + +####Example: + +``` +fastlane prepare_framework_release version:3.0.0 --env deploy +``` + +####Options + +It is recommended to manage these options through a .env file. See `fastlane/.env.deploy` for an example. + + * **`version`** (required): The new version of the framework + + * **`allow_dirty_branch`**: Allows the git branch to be dirty before continuing. Defaults to false + + * **`remote`**: The name of the git remote. Defaults to `origin`. (`DEPLOY_REMOTE`) + + * **`allow_branch`**: The name of the branch to build from. Defaults to `master`. (`DEPLOY_BRANCH`) + + * **`skip_validate_github_milestone`**: Skips validating a Github milestone. Defaults to false + + * **`skip_git_pull`**: Skips pulling the git remote. Defaults to false + + * **`skip_plist_update`**: Skips updating the version of the info plist. Defaults to false + + * **`plist_path`**: The path of the plist file to update. (`DEPLOY_PLIST_PATH`) + + * **`skip_podspec_update`**: Skips updating the version of the podspec. Defaults to false + + * **`podspec`**: The path of the podspec file to update. (`DEPLOY_PODSPEC`) + + * **`skip_changelog`**: Skip generating a changelog. Defaults to false. + + * **`changelog_path`**: The path to the changelog file. (`DEPLOY_CHANGELOG_PATH`) + + * **`changelog_insert_delimiter`**: The delimiter to insert the changelog after. (`DEPLOY_CHANGELOG_DELIMITER`) + + +### complete_framework_release +``` +fastlane complete_framework_release +``` +Completes the framework release + +This lane should be from a CI machine, after the tests have passed on the tag build. This lane does the following: + + * Verifies the git branch is clean + + * Ensures the lane is running on the master branch + + * Pulls the remote to verify the latest the branch is up to date + + * Generates a changelog for the Github Release + + * Creates a Github Release + + * Builds Carthage Frameworks + + * Uploads Carthage Framework to Github Release + + * Pushes podspec to pod trunk + + * Lints the pod spec to ensure it is valid + + * Closes the associated Github milestone + +####Example: + +``` +fastlane complete_framework_release --env deploy +``` + +####Options + +It is recommended to manage these options through a .env file. See `fastlane/.env.deploy` for an example. + + * **`version`** (required): The new version of the framework. Defaults to the last tag in the repo + + * **`allow_dirty_branch`**: Allows the git branch to be dirty before continuing. Defaults to false + + * **`remote`**: The name of the git remote. Defaults to `origin`. (`DEPLOY_REMOTE`) + + * **`allow_branch`**: The name of the branch to build from. Defaults to `master`. (`DEPLOY_BRANCH`) + + * **`skip_github_release`**: Skips creating a Github release. Defaults to false + + * **`skip_carthage_framework`**: Skips creating a carthage framework. If building a swift framework, this should be disabled. Defaults to false. + + * **`skip_pod_push`**: Skips pushing the podspec to trunk. + + * **`skip_podspec_update`**: Skips updating the version of the podspec. Defaults to false + + * **`skip_closing_github_milestone`**: Skips closing the associated Github milestone. Defaults to false + + + +---- + +This README.md is auto-generated and will be re-generated every time to run [fastlane](https://fastlane.tools). +More information about fastlane can be found on [https://fastlane.tools](https://fastlane.tools). +The documentation of fastlane can be found on [GitHub](https://github.com/fastlane/fastlane). \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_build_carthage_frameworks.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_build_carthage_frameworks.rb new file mode 100644 index 00000000..abe92c5a --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_build_carthage_frameworks.rb @@ -0,0 +1,64 @@ +module Fastlane + module Actions + module SharedValues + CARTHAGE_FRAMEWORK = :CARTHAGE_FRAMEWORK + end + + # To share this integration with the other fastlane users: + # - Fork https://github.com/KrauseFx/fastlane + # - Clone the forked repository + # - Move this integration into lib/fastlane/actions + # - Commit, push and submit the pull request + + class AfBuildCarthageFrameworksAction < Action + def self.run(params) + + Actions.sh("carthage build --no-skip-current") + Actions.sh("carthage archive #{params[:framework_name]}") + + path = "#{params[:framework_name]}.framework.zip" + + Actions.lane_context[SharedValues::CARTHAGE_FRAMEWORK] = path + + Helper.log.info "Carthage generated #{params[:framework_name]}.framework" + + return path + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Create a Carthage Framework for your project" + end + + def self.available_options + [ + FastlaneCore::ConfigItem.new(key: :framework_name, + env_name: "CARTHAGE_FRAMEWORK_NAME", # The name of the environment variable + description: "The name of the framework for Carthage to generate", # a short description of this parameter + is_string:true) + ] + end + + def self.output + [ + ['CARTHAGE_FRAMEWORK', 'The path to the generate Carthage framework'] + ] + end + + def self.return_value + "The path to the zipped framework" + end + + def self.authors + ["kcharwood"] + end + + def self.is_supported?(platform) + return true + end + end + end +end diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_create_github_release.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_create_github_release.rb new file mode 100644 index 00000000..14477dd4 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_create_github_release.rb @@ -0,0 +1,156 @@ +module Fastlane + module Actions + module SharedValues + GITHUB_RELEASE_ID = :GITHUB_RELEASE_ID + GITHUB_RELEASE_HTML_URL = :GITHUB_RELEASE_HTML_URL + GITHUB_RELEASE_UPLOAD_URL_TEMPLATE = :GITHUB_RELEASE_UPLOAD_URL_TEMPLATE + end + + # To share this integration with the other fastlane users: + # - Fork https://github.com/KrauseFx/fastlane + # - Clone the forked repository + # - Move this integration into lib/fastlane/actions + # - Commit, push and submit the pull request + + class AfCreateGithubReleaseAction < Action + def self.run(params) + require 'net/http' + require 'net/https' + require 'json' + require 'base64' + + begin + uri = URI("https://api.github.com/repos/#{params[:owner]}/#{params[:repository]}/releases") + + # Create client + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_PEER + + dict = Hash.new + dict["draft"] = params[:draft] + dict["prerelease"] = params[:prerelease] + dict["body"] = params[:body] if params[:body] + dict["tag_name"] = params[:tag_name] if params[:tag_name] + dict["name"] = params[:name] if params[:name] + body = JSON.dump(dict) + + # Create Request + req = Net::HTTP::Post.new(uri) + # Add headers + req.add_field "Content-Type", "application/json" + # Add headers + api_token = params[:api_token] + req.add_field "Authorization", "Basic #{Base64.strict_encode64(api_token)}" + # Add headers + req.add_field "Accept", "application/vnd.github.v3+json" + # Set header and body + req.add_field "Content-Type", "application/json" + req.body = body + + # Fetch Request + res = http.request(req) + rescue StandardError => e + Helper.log.info "HTTP Request failed (#{e.message})".red + end + + case res.code.to_i + when 201 + json = JSON.parse(res.body) + Helper.log.info "Github Release Created (#{json["id"]})".green + Helper.log.info "#{json["html_url"]}".green + + Actions.lane_context[SharedValues::GITHUB_RELEASE_ID] = json["id"] + Actions.lane_context[SharedValues::GITHUB_RELEASE_HTML_URL] = json["html_url"] + Actions.lane_context[SharedValues::GITHUB_RELEASE_UPLOAD_URL_TEMPLATE] = json["upload_url"] + return json + when 400..499 + json = JSON.parse(res.body) + raise "Error Creating Github Release (#{res.code}): #{json}".red + else + Helper.log.info "Status Code: #{res.code} Body: #{res.body}" + raise "Error Creating Github Release".red + end + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Create a Github Release" + end + + def self.available_options + [ + FastlaneCore::ConfigItem.new(key: :owner, + env_name: "GITHUB_OWNER", + description: "The Github Owner", + is_string:true, + optional:false), + FastlaneCore::ConfigItem.new(key: :repository, + env_name: "GITHUB_REPOSITORY", + description: "The Github Repository", + is_string:true, + optional:false), + FastlaneCore::ConfigItem.new(key: :api_token, + env_name: "GITHUB_API_TOKEN", + description: "Personal API Token for GitHub - generate one at https://github.com/settings/tokens", + is_string: true, + optional: false), + FastlaneCore::ConfigItem.new(key: :tag_name, + env_name: "GITHUB_RELEASE_TAG_NAME", + description: "Pass in the tag name", + is_string: true, + optional: false), + FastlaneCore::ConfigItem.new(key: :target_commitish, + env_name: "GITHUB_TARGET_COMMITISH", + description: "Specifies the commitish value that determines where the Git tag is created from. Can be any branch or commit SHA. Unused if the Git tag already exists", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :name, + env_name: "GITHUB_RELEASE_NAME", + description: "The name of the release", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :body, + env_name: "GITHUB_RELEASE_BODY", + description: "Text describing the contents of the tag", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :draft, + env_name: "GITHUB_RELEASE_DRAFT", + description: "true to create a draft (unpublished) release, false to create a published one", + is_string: false, + default_value: false), + FastlaneCore::ConfigItem.new(key: :prerelease, + env_name: "GITHUB_RELEASE_PRERELEASE", + description: "true to identify the release as a prerelease. false to identify the release as a full release", + is_string: false, + default_value: false), + + ] + end + + def self.output + [ + ['GITHUB_RELEASE_ID', 'The Github Release ID'], + ['GITHUB_RELEASE_HTML_URL', 'The Github Release URL'], + ['GITHUB_RELEASE_UPLOAD_URL_TEMPLATE', 'The Github Release Upload URL'] + ] + end + + def self.return_value + "The Hash representing the API response" + end + + def self.authors + ["kcharwood"] + end + + def self.is_supported?(platform) + return true + end + end + end +end diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_edit_github_release.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_edit_github_release.rb new file mode 100644 index 00000000..731b776d --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_edit_github_release.rb @@ -0,0 +1,161 @@ +module Fastlane + module Actions + module SharedValues + GITHUB_RELEASE_ID = :GITHUB_RELEASE_ID + GITHUB_RELEASE_HTML_URL = :GITHUB_RELEASE_HTML_URL + GITHUB_RELEASE_UPLOAD_URL_TEMPLATE = :GITHUB_RELEASE_UPLOAD_URL_TEMPLATE + end + + # To share this integration with the other fastlane users: + # - Fork https://github.com/KrauseFx/fastlane + # - Clone the forked repository + # - Move this integration into lib/fastlane/actions + # - Commit, push and submit the pull request + + class AfEditGithubReleaseAction < Action + def self.run(params) + + require 'net/http' + require 'net/https' + require 'json' + require 'base64' + + begin + uri = URI("https://api.github.com/repos/#{params[:owner]}/#{params[:repository]}/releases/#{params[:id]}") + + # Create client + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_PEER + + dict = Hash.new + dict["draft"] = params[:draft] if params[:draft] != nil + dict["prerelease"] = params[:prerelease] if params[:prerelease] != nil + dict["body"] = params[:body] if params[:body] + dict["tag_name"] = params[:tag_name] if params[:tag_name] + dict["name"] = params[:name] if params[:name] + body = JSON.dump(dict) + + # Create Request + req = Net::HTTP::Patch.new(uri) + # Add headers + req.add_field "Content-Type", "application/json" + # Add headers + api_token = params[:api_token] + req.add_field "Authorization", "Basic #{Base64.strict_encode64(api_token)}" + # Add headers + req.add_field "Accept", "application/vnd.github.v3+json" + # Set header and body + req.add_field "Content-Type", "application/json" + req.body = body + + # Fetch Request + res = http.request(req) + rescue StandardError => e + Helper.log.info "HTTP Request failed (#{e.message})".red + end + + case res.code.to_i + when 200 + json = JSON.parse(res.body) + Helper.log.info "Github Release updated".green + + Actions.lane_context[SharedValues::GITHUB_RELEASE_ID] = json["id"] + Actions.lane_context[SharedValues::GITHUB_RELEASE_HTML_URL] = json["html_url"] + Actions.lane_context[SharedValues::GITHUB_RELEASE_UPLOAD_URL_TEMPLATE] = json["upload_url"] + return json + when 400..499 + json = JSON.parse(res.body) + raise "Error Creating Github Release (#{res.code}): #{json["message"]}".red + else + Helper.log.info "Status Code: #{res.code} Body: #{res.body}" + raise "Error Creating Github Release".red + end + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Edit a Github Release" + end + + def self.available_options + [ + FastlaneCore::ConfigItem.new(key: :owner, + env_name: "GITHUB_OWNER", + description: "The Github Owner", + is_string:true, + optional:false), + FastlaneCore::ConfigItem.new(key: :repository, + env_name: "GITHUB_REPOSITORY", + description: "The Github Repository", + is_string:true, + optional:false), + FastlaneCore::ConfigItem.new(key: :id, + env_name: "GITHUB_RELEASE_ID", + description: "The Github Release ID", + is_string:true, + default_value:Actions.lane_context[SharedValues::GITHUB_RELEASE_ID]), + FastlaneCore::ConfigItem.new(key: :api_token, + env_name: "GITHUB_API_TOKEN", + description: "Personal API Token for GitHub - generate one at https://github.com/settings/tokens", + is_string: true, + optional: false), + FastlaneCore::ConfigItem.new(key: :tag_name, + env_name: "GITHUB_RELEASE_TAG_NAME", + description: "Pass in the tag name", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :target_commitish, + env_name: "GITHUB_TARGET_COMMITISH", + description: "Specifies the commitish value that determines where the Git tag is created from. Can be any branch or commit SHA. Unused if the Git tag already exists", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :name, + env_name: "GITHUB_RELEASE_NAME", + description: "The name of the release", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :body, + env_name: "GITHUB_RELEASE_BODY", + description: "Text describing the contents of the tag", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :draft, + env_name: "GITHUB_RELEASE_DRAFT", + description: "true to create a draft (unpublished) release, false to create a published one", + is_string: false, + optional: true), + FastlaneCore::ConfigItem.new(key: :prerelease, + env_name: "GITHUB_RELEASE_PRERELEASE", + description: "true to identify the release as a prerelease. false to identify the release as a full release", + is_string: false, + optional: true), + + ] + end + + def self.output + [ + ['GITHUB_RELEASE_ID', 'The Github Release ID'], + ['GITHUB_RELEASE_HTML_URL', 'The Github Release URL'], + ['GITHUB_RELEASE_UPLOAD_URL_TEMPLATE', 'The Github Release Upload URL'] + ] + end + + def self.return_value + "The Hash representing the API response" + end + + def self.authors + ["kcharwood"] + end + + def self.is_supported?(platform) + return true + end + end + end +end diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_generate_github_milestone_changelog.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_generate_github_milestone_changelog.rb new file mode 100644 index 00000000..ca503b60 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_generate_github_milestone_changelog.rb @@ -0,0 +1,225 @@ +module Fastlane + module Actions + module SharedValues + GITHUB_MILESTONE_CHANGELOG = :GITHUB_MILESTONE_CHANGELOG + end + + # To share this integration with the other fastlane users: + # - Fork https://github.com/KrauseFx/fastlane + # - Clone the forked repository + # - Move this integration into lib/fastlane/actions + # - Commit, push and submit the pull request + + class AfGenerateGithubMilestoneChangelogAction < Action + def self.english_join(array = nil) + return "" if array.nil? or array.length == 0 + return array[0] if array.length == 1 + array[0..-2].join(", ") + " and " + array[-1] + end + + def self.markdown_for_changelog_section (github_owner, github_repository, api_token, section, issues) + changelog = "\n#### #{section}\n" + issues.each do |issue| + authors = getAuthorsForIssue(github_owner,github_repository, api_token, issue) + + changelog << "* #{issue["title"]}\n" + changelog << " * Implemented by #{english_join(authors)} in [##{issue["number"]}](#{issue["html_url"]}).\n" + end + return changelog + end + + def self.getResponseForURL(url, api_token) + uri = URI(url) + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_PEER + + # Create Request + req = Net::HTTP::Get.new(uri) + req.add_field "Authorization", "Basic #{Base64.strict_encode64(api_token)}" if api_token != nil + req.add_field "Accept", "application/vnd.github.v3+json" + begin + httpResponse = http.request(req) + begin + case httpResponse.code.to_i + when 200..299 + response = JSON.parse(httpResponse.body) + when 400..499 + response = JSON.parse(httpResponse.body) + raise "Error (#{response.code}): #{response["message"]}".red + else + Helper.log.info "Status Code: #{httpResponse.code} Body: #{httpResponse.body}" + raise "Error with request".red + end + + rescue + + end + rescue => ex + raise "Error fetching remote file: #{ex}".red + end + return response + end + + def self.getIssuesForMilestone (github_owner, github_repository, api_token, milestone) + url = "https://api.github.com/search/issues?q=repo:#{github_owner}/#{github_repository}+milestone:#{milestone}+state:closed" + + response = getResponseForURL(url, api_token) + return response["items"] + end + + def self.getAuthorsForIssue(github_owner, github_repository, api_token, issue) + if issue.has_key?("pull_request") + url = "https://api.github.com/repos/#{github_owner}/#{github_repository}/pulls/#{issue["number"]}/commits" + + commits = getResponseForURL(url, api_token) + + authors = Array.new + commits.each do |commit| + author = commit["commit"]["author"] + if authors.include?(author["name"]) == false + authors << author["name"] + end + end + return authors + else + return [issue["user"]["login"]] + end + end + + + def self.run(params) + require 'net/http' + require 'fileutils' + + issues = getIssuesForMilestone(params[:github_owner], params[:github_repository], params[:api_token], params[:milestone]) + + if issues.count == 0 && params[:allow_empty_changelog] == false + raise "No closed issues found for #{params[:milestone]} in #{params[:github_owner]}/#{params[:github_repository]}".red + end + + labels = [params[:added_label_name], params[:updated_label_name], params[:changed_label_name], params[:fixed_label_name], params[:removed_label_name]] + sections = Array.new + labels.each do |label_name| + subissues = issues.select {|issue| issue["labels"].any? {|label| label["name"].downcase == label_name.downcase}} + if subissues.count > 0 + sections << {section: label_name, issues: subissues} + issues = issues - subissues + end + end + + if issues.count > 0 + prompt_text = "There are #{issues.count} issue(s) that have not been properly categorized in this milestone. Do you want to continue?" + if Fastlane::Actions::PromptAction.run(text: prompt_text, boolean: true, ci_input: "y") + if sections.count > 0 + section_label = "Additional Changes" + else + section_label = "Changes" + end + sections << {section: section_label, issues: issues} + else + raise "Aborting since issues have not been categorized." + end + + end + + + date = DateTime.now + result = Hash.new + result[:title] = "\n\n## [#{params[:milestone]}](https://github.com/#{params[:github_owner]}/#{params[:github_repository]}/releases/tag/#{params[:milestone]}) (#{date.strftime("%m/%d/%Y")})" + result[:header] = "\nReleased on #{date.strftime("%A, %B %d, %Y")}. All issues associated with this milestone can be found using this [filter](https://github.com/#{params[:github_owner]}/#{params[:github_repository]}/issues?q=milestone%3A#{params[:milestone]}+is%3Aclosed)." + + result[:changelog] = "\n" + sections.each do |section| + result[:changelog] << markdown_for_changelog_section(params[:github_owner], params[:github_repository], params[:api_token], section[:section], section[:issues]) + end + Actions.lane_context[SharedValues::GITHUB_MILESTONE_CHANGELOG] = result + + return result + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Generate a markdown formatted change log for a specific milestone in a Github repository" + end + + def self.details + + "You can use this action to do cool things..." + end + + def self.available_options + [ + FastlaneCore::ConfigItem.new(key: :github_owner, + env_name: "GITHUB_OWNER", + description: "Github Owner for the repository", + is_string: true), + FastlaneCore::ConfigItem.new(key: :github_repository, + env_name: "GITHUB_REPOSITORY", + description: "Github Repository containing the milestone", + is_string: true), + FastlaneCore::ConfigItem.new(key: :api_token, + env_name: "GITHUB_API_TOKEN", + description: "Personal API Token for GitHub - generate one at https://github.com/settings/tokens", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :milestone, + env_name: "FL_GENERATE_GITHUB_MILESTONE_CHANGELOG_MILESTONE", + description: "Milestone to generate changelog notes", + is_string: true), + FastlaneCore::ConfigItem.new(key: :added_label_name, + env_name: "FL_GENERATE_GITHUB_MILESTONE_CHANGELOG_ADDED_LABEL_NAME", + description: "Github label name for all issues added during this milestone", + is_string: true, + default_value: "Added"), + FastlaneCore::ConfigItem.new(key: :updated_label_name, + env_name: "FL_GENERATE_GITHUB_MILESTONE_CHANGELOG_UPDATED_LABEL_NAME", + description: "Github label name for all issues updated during this milestone", + is_string: true, + default_value: "Updated"), + FastlaneCore::ConfigItem.new(key: :changed_label_name, + env_name: "FL_GENERATE_GITHUB_MILESTONE_CHANGELOG_CHANGED_LABEL_NAME", + description: "Github label name for all issues changed during this milestone", + is_string: true, + default_value: "Changed"), + FastlaneCore::ConfigItem.new(key: :fixed_label_name, + env_name: "FL_GENERATE_GITHUB_MILESTONE_CHANGELOG_FIXED_LABEL_NAME", + description: "Github label name for all issues fixed during this milestone", + is_string: true, + default_value: "Fixed"), + FastlaneCore::ConfigItem.new(key: :removed_label_name, + env_name: "FL_GENERATE_GITHUB_MILESTONE_CHANGELOG_REMOVED_LABEL_NAME", + description: "Github label name for all removed added during this milestone", + is_string: true, + default_value: "Removed"), + FastlaneCore::ConfigItem.new(key: :allow_empty_changelog, + env_name: "FL_GENERATE_GITHUB_MILESTONE_CHANGELOG_ALLOW_EMPTY", + description: "Flag which allows an empty changelog. If false, exception is raised if no issues are found", + is_string: false, + default_value: true) + ] + end + + def self.output + [ + ['GITHUB_MILESTONE_CHANGELOG', 'A hash containing a well formatted :header, and the :changelog itself'] + ] + end + + def self.return_value + "Returns a hash containing a well formatted :title, :header, and the :changelog itself, both in markdown" + end + + def self.authors + ["kcharwood"] + end + + def self.is_supported?(platform) + return true + end + end + end +end diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_get_github_milestone.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_get_github_milestone.rb new file mode 100644 index 00000000..9ed273f4 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_get_github_milestone.rb @@ -0,0 +1,129 @@ +module Fastlane + module Actions + module SharedValues + GITHUB_MILESTONE_NUMBER = :GITHUB_MILESTONE_NUMBER + end + + # To share this integration with the other fastlane users: + # - Fork https://github.com/KrauseFx/fastlane + # - Clone the forked repository + # - Move this integration into lib/fastlane/actions + # - Commit, push and submit the pull request + + class AfGetGithubMilestoneAction < Action + def self.run(params) + require 'net/http' + require 'net/https' + require 'json' + require 'base64' + + begin + uri = URI("https://api.github.com/repos/#{params[:owner]}/#{params[:repository]}/milestones") + + # Create client + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_PEER + + # Create Request + req = Net::HTTP::Get.new(uri) + # Add headers + if params[:api_token] + api_token = params[:api_token] + req.add_field "Authorization", "Basic #{Base64.strict_encode64(api_token)}" + end + req.add_field "Accept", "application/vnd.github.v3+json" + + # Fetch Request + res = http.request(req) + rescue StandardError => e + Helper.log.info "HTTP Request failed (#{e.message})".red + end + + case res.code.to_i + when 200 + milestones = JSON.parse(res.body) + + milestone = milestones.select {|milestone| milestone["title"] == params[:title]}.first + + if milestone == nil + raise "No milestone found matching #{params[:title]}".red + end + + Helper.log.info "Milestone #{params[:title]}: #{milestone["url"]}".green + + if params[:verify_for_release] == true + raise "Milestone #{params[:title]} is already closed".red unless milestone["state"] == "open" + raise "Milestone #{params[:title]} still has open #{milestone["open_issues"]} issue(s)".red unless milestone["open_issues"] == 0 + raise "Milestone #{params[:title]} has no closed issues".red unless milestone["closed_issues"] > 0 + Helper.log.info "Milestone #{params[:title]} is ready for release!".green + end + + Actions.lane_context[SharedValues::GITHUB_MILESTONE_NUMBER] = milestone["number"] + return milestone + when 400..499 + json = JSON.parse(res.body) + raise "Error Retrieving Github Milestone (#{res.code}): #{json["message"]}".red + else + Helper.log.info "Status Code: #{res.code} Body: #{res.body}" + raise "Retrieving Github Milestone".red + end + + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Get a Github Milestone, and optional verify its ready for release" + end + + def self.available_options + [ + FastlaneCore::ConfigItem.new(key: :owner, + env_name: "GITHUB_OWNER", + description: "The Github Owner", + is_string:true, + optional:false), + FastlaneCore::ConfigItem.new(key: :repository, + env_name: "GITHUB_REPOSITORY", + description: "The Github Repository", + is_string:true, + optional:false), + FastlaneCore::ConfigItem.new(key: :api_token, + env_name: "GITHUB_API_TOKEN", + description: "Personal API Token for GitHub - generate one at https://github.com/settings/tokens", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :title, + description: "The milestone title, typically the same as the tag", + is_string: true, + optional: false), + FastlaneCore::ConfigItem.new(key: :verify_for_release, + description: "Verifies there are zero open issues, at least one closed issue, and is not closed", + is_string: false, + default_value:false) + ] + end + + def self.output + [ + ['GITHUB_MILESTONE_NUMBER', 'The milestone number'] + ] + end + + def self.return_value + "A Hash representing the API response" + end + + def self.authors + ["kcharwood"] + end + + def self.is_supported?(platform) + return true + end + end + end +end diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_insert_text_into_file.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_insert_text_into_file.rb new file mode 100644 index 00000000..a308ff0d --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_insert_text_into_file.rb @@ -0,0 +1,80 @@ +module Fastlane + module Actions + + # To share this integration with the other fastlane users: + # - Fork https://github.com/KrauseFx/fastlane + # - Clone the forked repository + # - Move this integration into lib/fastlane/actions + # - Commit, push and submit the pull request + class AfInsertTextIntoFileAction < Action + def self.replace(filepath, regexp, *args, &block) + content = File.read(filepath).gsub(regexp, *args, &block) + File.open(filepath, 'wb') { |file| file.write(content) } + end + + def self.run(params) + if params[:insert_delimiter] + replace(params[:file_path], /^#{params[:insert_delimiter]}/mi) do |match| + "#{match} #{params[:text]}" + end + elsif params[:insert_at_bottom] == true + open(params[:file_path], 'a') { |f| f.puts "#{params[:text]}" } + else + file = IO.read(params[:file_path]) + open(params[:file_path], 'w') { |f| f << params[:text] << file} + end + + Helper.log.info "#{params[:file_path]} has been updated".green + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Insert text into a file" + end + + def self.details + "Insert text at the top, bottom, or after a delimiter in a file" + end + + def self.available_options + [ + FastlaneCore::ConfigItem.new(key: :file_path, + description: "Path for the file", + is_string: true, + verify_block: proc do |value| + raise "Couldn't find file at path '#{value}'".red unless File.exist?(value) + end), + FastlaneCore::ConfigItem.new(key: :text, + description: "The text to insert", + is_string: true), + FastlaneCore::ConfigItem.new(key: :insert_delimiter, + description: "The delimiter indicating where to insert the text in the file", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :insert_at_bottom, + description: "If no 'insert_delimiter' is provided, the text will be appended to the bottom +of the file if this value is true, or to the top if this value is false", + is_string: false, + default_value: true), + ] + end + + def self.output + end + + def self.return_value + end + + def self.authors + ["kcharwood"] + end + + def self.is_supported?(platform) + return true + end + end + end +end diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_pod_spec_lint.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_pod_spec_lint.rb new file mode 100644 index 00000000..7beef8a0 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_pod_spec_lint.rb @@ -0,0 +1,90 @@ +module Fastlane + module Actions + + # To share this integration with the other fastlane users: + # - Fork https://github.com/KrauseFx/fastlane + # - Clone the forked repository + # - Move this integration into lib/fastlane/actions + # - Commit, push and submit the pull request + + class AfPodSpecLintAction < Action + def self.run(params) + commands = ["pod", "spec", "lint"] + if params[:path] + commands << params[:path] + end + + if params[:quick] + commands << "--quick" + end + + if params[:allow_warnings] + commands << "--allow-warnings" + end + + if params[:no_subspecs] + commands << "--no-subspecs" + end + + if params[:subspec] + commands << "--subspec=#{params[:subspec]}" + end + + result = Actions.sh("#{commands.join(" ")}") + Helper.log.info "Successfully linted podspec".green + return result + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Lint a pod spec" + end + + def self.available_options + [ + FastlaneCore::ConfigItem.new(key: :path, + description: "The Podspec you want to lint", + optional: true, + verify_block: proc do |value| + raise "Couldn't find file at path '#{value}'".red unless File.exist?(value) + raise "File must be a `.podspec`".red unless value.end_with?(".podspec") + end), + FastlaneCore::ConfigItem.new(key: :quick, + description: "Lint skips checks that would require to download and build the spec", + optional: true, + is_string:false), + FastlaneCore::ConfigItem.new(key: :allow_warnings, + description: "Lint validates even if warnings are present", + optional: true, + is_string:false), + FastlaneCore::ConfigItem.new(key: :no_subspecs, + description: "Lint skips validation of subspecs", + optional: true, + is_string:false), + FastlaneCore::ConfigItem.new(key: :subspec, + description: "Lint validates only the given subspec", + optional: true, + is_string: true), + ] + end + + def self.output + end + + def self.return_value + # If you method provides a return value, you can describe here what it does + end + + def self.authors + ["kcharwood"] + end + + def self.is_supported?(platform) + platform != :android + end + end + end +end diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_push_git_tags_to_remote.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_push_git_tags_to_remote.rb new file mode 100644 index 00000000..ed265dde --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_push_git_tags_to_remote.rb @@ -0,0 +1,47 @@ +module Fastlane + module Actions + class AfPushGitTagsToRemoteAction < Action + def self.run(params) + commands = ["git", "push"] + + if params[:remote] + commands << "#{params[:remote]}" + end + + commands << "--tags" + + result = Actions.sh("#{commands.join(" ")}") + Helper.log.info "Tags pushed to remote".green + return result + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Push local tags to the remote - this will only push tags" + end + + def self.available_options + [ + FastlaneCore::ConfigItem.new(key: :remote, + env_name: "FL_PUSH_GIT_TAGS_REMOTE", + description: "The remote to push tags too", + is_string:true, + optional:true) + ] + end + + def self.author + ['vittoriom'] + end + + def self.is_supported?(platform) + true + end + end + end + end + + \ No newline at end of file diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_update_github_milestone.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_update_github_milestone.rb new file mode 100644 index 00000000..8fa23c76 --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_update_github_milestone.rb @@ -0,0 +1,138 @@ +module Fastlane + module Actions + module SharedValues + end + + # To share this integration with the other fastlane users: + # - Fork https://github.com/KrauseFx/fastlane + # - Clone the forked repository + # - Move this integration into lib/fastlane/actions + # - Commit, push and submit the pull request + + class AfUpdateGithubMilestoneAction < Action + def self.run(params) + + require 'net/http' + require 'net/https' + require 'json' + require 'base64' + + begin + uri = URI("https://api.github.com/repos/#{params[:owner]}/#{params[:repository]}/milestones/#{params[:number]}") + + # Create client + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_PEER + + dict = Hash.new + dict["title"] = params[:title] if params[:title] + dict["state"] = params[:state] if params[:state] + dict["description"] = params[:description] if params[:description] + dict["due_on"] = params[:due_on] if params[:due_on] + body = JSON.dump(dict) + + # Create Request + req = Net::HTTP::Patch.new(uri) + req.add_field "Content-Type", "application/json" + api_token = params[:api_token] + req.add_field "Authorization", "Basic #{Base64.strict_encode64(api_token)}" + req.add_field "Accept", "application/vnd.github.v3+json" + req.add_field "Content-Type", "application/json" + req.body = body + + # Fetch Request + res = http.request(req) + rescue StandardError => e + Helper.log.info "HTTP Request failed (#{e.message})".red + end + + case res.code.to_i + when 200 + json = JSON.parse(res.body) + Helper.log.info "Github Release updated".green + + Actions.lane_context[SharedValues::GITHUB_RELEASE_ID] = json["id"] + Actions.lane_context[SharedValues::GITHUB_RELEASE_HTML_URL] = json["html_url"] + Actions.lane_context[SharedValues::GITHUB_RELEASE_UPLOAD_URL_TEMPLATE] = json["upload_url"] + return json + when 400..499 + json = JSON.parse(res.body) + raise "Error Creating Github Release (#{res.code}): #{json["message"]}".red + else + Helper.log.info "Status Code: #{res.code} Body: #{res.body}" + raise "Error Creating Github Release".red + end + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Edit a Github Milestone" + end + + def self.available_options + [ + FastlaneCore::ConfigItem.new(key: :owner, + env_name: "GITHUB_OWNER", + description: "The Github Owner", + is_string:true, + optional:false), + FastlaneCore::ConfigItem.new(key: :repository, + env_name: "GITHUB_REPOSITORY", + description: "The Github Repository", + is_string:true, + optional:false), + FastlaneCore::ConfigItem.new(key: :number, + env_name: "GITHUB_MILESTONE_NUMBER", + description: "The Github Release ID", + is_string:true, + default_value:Actions.lane_context[SharedValues::GITHUB_MILESTONE_NUMBER]), + FastlaneCore::ConfigItem.new(key: :api_token, + env_name: "GITHUB_API_TOKEN", + description: "Personal API Token for GitHub - generate one at https://github.com/settings/tokens", + is_string: true, + optional: false), + FastlaneCore::ConfigItem.new(key: :title, + env_name: "GITHUB_MILESTONE_TITLE", + description: "The title to update", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :state, + env_name: "GITHUB_MILESTONE_STATE", + description: "The state to update. Can be `open` or `closed`", + is_string: true, + optional: true, + verify_block: proc do |value| + raise "`state` can only be `open` or `closed".red unless value == "open" || value == "closed" + end), + FastlaneCore::ConfigItem.new(key: :description, + env_name: "GITHUB_MILESTONE_DESCRIPTION", + description: "The description of the milestone", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :due_on, + env_name: "GITHUB_MIELSTONE_DUE_DATE", + description: "The milestone due date. This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ", + is_string: true, + optional: true), + + ] + end + + def self.return_value + "The Hash representing the API response" + end + + def self.authors + ["kcharwood"] + end + + def self.is_supported?(platform) + return true + end + end + end +end diff --git a/its/plugin/projects/AFNetworking/fastlane/actions/af_upload_asset_for_github_release.rb b/its/plugin/projects/AFNetworking/fastlane/actions/af_upload_asset_for_github_release.rb new file mode 100644 index 00000000..900e3cfe --- /dev/null +++ b/its/plugin/projects/AFNetworking/fastlane/actions/af_upload_asset_for_github_release.rb @@ -0,0 +1,134 @@ +module Fastlane + module Actions + module SharedValues + GITHUB_UPLOAD_ASSET_URL = :GITHUB_UPLOAD_ASSET_URL + end + + # To share this integration with the other fastlane users: + # - Fork https://github.com/KrauseFx/fastlane + # - Clone the forked repository + # - Move this integration into lib/fastlane/actions + # - Commit, push and submit the pull request + + class AfUploadAssetForGithubReleaseAction < Action + def self.run(params) + require 'net/http' + require 'net/https' + require 'json' + require 'base64' + require 'addressable/template' + + begin + name = params[:name] ? params[:name] : File.basename(params[:file_path]) + expanded_url = Addressable::Template.new(params[:upload_url_template]).expand({name: name, label:params[:label]}).to_s + + uri = URI(expanded_url) + + # Create client + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_PEER + + + # Create Request + req = Net::HTTP::Post.new(uri) + # Add headers + req.add_field "Content-Type", params[:content_type] + # Add headers + api_token = params[:api_token] + req.add_field "Authorization", "Basic #{Base64.strict_encode64(api_token)}" + # Add headers + req.add_field "Accept", "application/vnd.github.v3+json" + # Set header and body + req.add_field "Content-Type", "application/json" + req.body = File.read(params[:file_path]) + + # Fetch Request + res = http.request(req) + rescue StandardError => e + Helper.log.info "HTTP Request failed (#{e.message})".red + end + + case res.code.to_i + when 201 + json = JSON.parse(res.body) + Helper.log.info "#{json["name"]} has been uploaded to the release".green + Actions.lane_context[SharedValues::GITHUB_UPLOAD_ASSET_URL] = json["browser_download_url"] + return json + when 400..499 + json = JSON.parse(res.body) + raise "Error Creating Github Release (#{res.code}): #{json}".red + else + Helper.log.info "Status Code: #{res.code} Body: #{res.body}" + raise "Error Creating Github Release".red + end + end + + ##################################################### + # @!group Documentation + ##################################################### + + def self.description + "Upload an asset to a Github Release" + end + + def self.available_options + # Define all options your action supports. + + # Below a few examples + [ + FastlaneCore::ConfigItem.new(key: :api_token, + env_name: "GITHUB_API_TOKEN", + description: "Personal API Token for GitHub - generate one at https://github.com/settings/tokens", + is_string: true, + optional: false), + FastlaneCore::ConfigItem.new(key: :upload_url_template, + env_name: "GITHUB_RELEASE_UPLOAD_URL_TEMPLATE", + description: "The Github Release Upload URL", + is_string:true, + default_value:Actions.lane_context[SharedValues::GITHUB_RELEASE_UPLOAD_URL_TEMPLATE]), + FastlaneCore::ConfigItem.new(key: :file_path, + env_name: "GITHUB_RELEASE_UPLOAD_FILE_PATH", + description: "Path for the file", + is_string: true, + verify_block: proc do |value| + raise "Couldn't find file at path '#{value}'".red unless File.exist?(value) + end), + FastlaneCore::ConfigItem.new(key: :name, + env_name: "GITHUB_RELEASE_UPLOAD_NAME", + description: "Name of the upload asset. Defaults to the base name of 'file_path'}", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :label, + env_name: "GITHUB_RELEASE_UPLOAD_LABEL", + description: "An alternate short description of the asset", + is_string: true, + optional: true), + FastlaneCore::ConfigItem.new(key: :content_type, + env_name: "GITHUB_RELEASE_UPLOAD_CONTENT_TYPE", + description: "The content type for the upload", + is_string: true, + default_value: "application/zip") + ] + end + + def self.output + [ + ['GITHUB_UPLOAD_ASSET_URL', 'A url for the newly created asset'] + ] + end + + def self.return_value + "The hash representing the API response" + end + + def self.authors + ["kcharwood"] + end + + def self.is_supported?(platform) + return true + end + end + end +end