diff --git a/.travis.yml b/.travis.yml index 20645cb5..f07c7649 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ language: objective-c -osx_image: xcode7 +osx_image: xcode7.1 before_install: - gem install xcpretty --no-rdoc --no-ri --no-document --quiet @@ -10,6 +10,7 @@ env: - RAKETASK="ios[iOS StaticLib,latest,test]" - RAKETASK="ios[iOS Framework,latest,test]" - RAKETASK="osx[Mac Framework,x86_64,test]" + - RAKETASK="tvos[tvOS Framework,latest,test]" script: - rake "$RAKETASK" diff --git a/OHHTTPStubs.podspec b/OHHTTPStubs.podspec index 239f8fcc..6f1eafda 100644 --- a/OHHTTPStubs.podspec +++ b/OHHTTPStubs.podspec @@ -31,6 +31,7 @@ Pod::Spec.new do |s| s.ios.deployment_target = '5.0' s.osx.deployment_target = '10.7' s.watchos.deployment_target = '2.0' + s.tvos.deployment_target = '9.0' s.default_subspec = 'Default' diff --git a/OHHTTPStubs/OHHTTPStubs.xcodeproj/project.pbxproj b/OHHTTPStubs/OHHTTPStubs.xcodeproj/project.pbxproj index 9e325dbc..c49f6250 100644 --- a/OHHTTPStubs/OHHTTPStubs.xcodeproj/project.pbxproj +++ b/OHHTTPStubs/OHHTTPStubs.xcodeproj/project.pbxproj @@ -82,6 +82,7 @@ 09D0D2991B67FED3004E7213 /* Compatibility.h in Headers */ = {isa = PBXBuildFile; fileRef = 09D0D2981B67FED3004E7213 /* Compatibility.h */; settings = {ATTRIBUTES = (Public, ); }; }; 09D0D29A1B67FED3004E7213 /* Compatibility.h in Headers */ = {isa = PBXBuildFile; fileRef = 09D0D2981B67FED3004E7213 /* Compatibility.h */; settings = {ATTRIBUTES = (Public, ); }; }; 09D0D29B1B67FF06004E7213 /* Compatibility.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 09D0D2981B67FED3004E7213 /* Compatibility.h */; }; + 0D4BF5A17B4778591F08161F /* libPods-OHHTTPStubs tvOS Fmk Tests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = BA8213D8FBCA73CF0607478B /* libPods-OHHTTPStubs tvOS Fmk Tests.a */; }; 0DB397E35DDB6808A5496D53 /* libPods-OHHTTPStubs Mac Tests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = F49690D948DE88BBB4A36B11 /* libPods-OHHTTPStubs Mac Tests.a */; }; 1D0F8E7E1B6E31850049A7D2 /* MocktailTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D0F8E7D1B6E31850049A7D2 /* MocktailTests.m */; }; 1D0F8E801B6E31A70049A7D2 /* login.tail in Resources */ = {isa = PBXBuildFile; fileRef = 1D0F8E7F1B6E31A70049A7D2 /* login.tail */; }; @@ -104,6 +105,38 @@ 725CD9BB1A9EB71A00F84C8B /* OHHTTPStubsResponse+JSON.h in Headers */ = {isa = PBXBuildFile; fileRef = 09110A721980606A00D175E4 /* OHHTTPStubsResponse+JSON.h */; settings = {ATTRIBUTES = (Public, ); }; }; 725CD9BC1A9EB71D00F84C8B /* OHHTTPStubsResponse+HTTPMessage.h in Headers */ = {isa = PBXBuildFile; fileRef = 09110A701980606A00D175E4 /* OHHTTPStubsResponse+HTTPMessage.h */; settings = {ATTRIBUTES = (Public, ); }; }; 7B812F8D5510F916B78E671A /* libPods-OHHTTPStubs iOS Lib Tests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = BFA846B11753DE97A1D563D0 /* libPods-OHHTTPStubs iOS Lib Tests.a */; }; + EA100ABC1BE15BE400129352 /* OHHTTPStubs.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EAA436A51BE1598D000E9E99 /* OHHTTPStubs.framework */; }; + EA9D27231BE15C740078CAA0 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA9D27221BE15C740078CAA0 /* Foundation.framework */; }; + EA9D27241BE15CA00078CAA0 /* empty.bundle in Resources */ = {isa = PBXBuildFile; fileRef = 221C34A61B0CCF9D00FCA8FF /* empty.bundle */; }; + EA9D27251BE15CA00078CAA0 /* emptyfile.json in Resources */ = {isa = PBXBuildFile; fileRef = 47AF337A1A37757B00158C9F /* emptyfile.json */; }; + EA9D27261BE15CA00078CAA0 /* login.tail in Resources */ = {isa = PBXBuildFile; fileRef = 1D0F8E7F1B6E31A70049A7D2 /* login.tail */; }; + EA9D27271BE15CA00078CAA0 /* MocktailFolder in Resources */ = {isa = PBXBuildFile; fileRef = 1D0F8E811B6E31B00049A7D2 /* MocktailFolder */; }; + EA9D27281BE15CB50078CAA0 /* AFNetworkingTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 095981481980668E00807DBE /* AFNetworkingTests.m */; }; + EA9D27291BE15CB50078CAA0 /* MocktailTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D0F8E7D1B6E31850049A7D2 /* MocktailTests.m */; }; + EA9D272A1BE15CB50078CAA0 /* NilValuesTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 095981491980668E00807DBE /* NilValuesTests.m */; }; + EA9D272B1BE15CB50078CAA0 /* NSURLConnectionDelegateTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 0959814A1980668E00807DBE /* NSURLConnectionDelegateTests.m */; }; + EA9D272C1BE15CB50078CAA0 /* NSURLConnectionTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 0959814B1980668E00807DBE /* NSURLConnectionTests.m */; }; + EA9D272D1BE15CB50078CAA0 /* NSURLSessionTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 0959814C1980668E00807DBE /* NSURLSessionTests.m */; }; + EA9D272E1BE15CB50078CAA0 /* OHPathHelpersTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 221C34A41B0CCF0600FCA8FF /* OHPathHelpersTests.m */; }; + EA9D272F1BE15CB50078CAA0 /* TimingTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 0959814D1980668E00807DBE /* TimingTests.m */; }; + EA9D27301BE15CB50078CAA0 /* WithContentsOfURLTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 0959814E1980668E00807DBE /* WithContentsOfURLTests.m */; }; + EA9D27311BE15CB50078CAA0 /* SwiftHelpersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 095925D51BAEC00200DD7F0B /* SwiftHelpersTests.swift */; }; + EAA4368F1BE1598D000E9E99 /* OHHTTPStubs.m in Sources */ = {isa = PBXBuildFile; fileRef = 09110A6B1980605A00D175E4 /* OHHTTPStubs.m */; }; + EAA436901BE1598D000E9E99 /* OHHTTPStubs+NSURLSessionConfiguration.m in Sources */ = {isa = PBXBuildFile; fileRef = 09110A781980608600D175E4 /* OHHTTPStubs+NSURLSessionConfiguration.m */; }; + EAA436911BE1598D000E9E99 /* OHHTTPStubs+Mocktail.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D6DB84F1B763B7A00FCF855 /* OHHTTPStubs+Mocktail.m */; }; + EAA436921BE1598D000E9E99 /* OHHTTPStubsResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 09110A6F1980606A00D175E4 /* OHHTTPStubsResponse.m */; }; + EAA436931BE1598D000E9E99 /* OHHTTPStubsResponse+JSON.m in Sources */ = {isa = PBXBuildFile; fileRef = 09110A731980606A00D175E4 /* OHHTTPStubsResponse+JSON.m */; }; + EAA436941BE1598D000E9E99 /* OHHTTPStubsResponse+HTTPMessage.m in Sources */ = {isa = PBXBuildFile; fileRef = 09110A711980606A00D175E4 /* OHHTTPStubsResponse+HTTPMessage.m */; }; + EAA436951BE1598D000E9E99 /* OHHTTPStubsSwift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0955699A1B90E4EA00503ADC /* OHHTTPStubsSwift.swift */; }; + EAA436961BE1598D000E9E99 /* OHPathHelpers.m in Sources */ = {isa = PBXBuildFile; fileRef = 095B1AD41AE30BA7009D1B56 /* OHPathHelpers.m */; }; + EAA436991BE1598D000E9E99 /* Compatibility.h in Headers */ = {isa = PBXBuildFile; fileRef = 09D0D2981B67FED3004E7213 /* Compatibility.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EAA4369A1BE1598D000E9E99 /* OHHTTPStubs.h in Headers */ = {isa = PBXBuildFile; fileRef = 09110A6A1980605A00D175E4 /* OHHTTPStubs.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EAA4369B1BE1598D000E9E99 /* OHHTTPStubsResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 09110A6E1980606A00D175E4 /* OHHTTPStubsResponse.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EAA4369C1BE1598D000E9E99 /* OHHTTPStubsResponse+JSON.h in Headers */ = {isa = PBXBuildFile; fileRef = 09110A721980606A00D175E4 /* OHHTTPStubsResponse+JSON.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EAA4369D1BE1598D000E9E99 /* OHHTTPStubsResponse+HTTPMessage.h in Headers */ = {isa = PBXBuildFile; fileRef = 09110A701980606A00D175E4 /* OHHTTPStubsResponse+HTTPMessage.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EAA4369E1BE1598D000E9E99 /* OHHTTPStubs+Mocktail.h in Headers */ = {isa = PBXBuildFile; fileRef = 1D6DB84E1B763B7A00FCF855 /* OHHTTPStubs+Mocktail.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EAA4369F1BE1598D000E9E99 /* OHPathHelpers.h in Headers */ = {isa = PBXBuildFile; fileRef = 095B1AD31AE30BA7009D1B56 /* OHPathHelpers.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EAA436A01BE1598D000E9E99 /* OHHTTPStubsUmbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 09199FCC1BD973800014376D /* OHHTTPStubsUmbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -128,6 +161,13 @@ remoteGlobalIDString = 095981C119806A7900807DBE; remoteInfo = "OHHTTPStubs Mac"; }; + EA100ABD1BE15BE400129352 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 09110A3919805F4800D175E4 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EAA4368D1BE1598D000E9E99; + remoteInfo = "OHHTTPStubs tvOS Framework"; + }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -199,11 +239,17 @@ 725CD99B1A9EB65100F84C8B /* OHHTTPStubs.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = OHHTTPStubs.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 78215AC3F712A93089D77E60 /* Pods-OHHTTPStubs iOS Fmk Tests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-OHHTTPStubs iOS Fmk Tests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-OHHTTPStubs iOS Fmk Tests/Pods-OHHTTPStubs iOS Fmk Tests.debug.xcconfig"; sourceTree = ""; }; 95E3CBB2346C0E2FBA46D63E /* Pods-OHHTTPStubs iOS Lib Tests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-OHHTTPStubs iOS Lib Tests.release.xcconfig"; path = "Pods/Target Support Files/Pods-OHHTTPStubs iOS Lib Tests/Pods-OHHTTPStubs iOS Lib Tests.release.xcconfig"; sourceTree = ""; }; + 9E2F558594F0FA64E4C87BBB /* Pods-OHHTTPStubs tvOS Fmk Tests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-OHHTTPStubs tvOS Fmk Tests.release.xcconfig"; path = "Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests.release.xcconfig"; sourceTree = ""; }; B11995FF7A5A81D0A322D6FA /* Pods-OHHTTPStubs Mac Tests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-OHHTTPStubs Mac Tests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-OHHTTPStubs Mac Tests/Pods-OHHTTPStubs Mac Tests.debug.xcconfig"; sourceTree = ""; }; + BA8213D8FBCA73CF0607478B /* libPods-OHHTTPStubs tvOS Fmk Tests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-OHHTTPStubs tvOS Fmk Tests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; + BEAE095678347F4BB47B8D3F /* Pods-OHHTTPStubs tvOS Fmk Tests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-OHHTTPStubs tvOS Fmk Tests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests.debug.xcconfig"; sourceTree = ""; }; BFA846B11753DE97A1D563D0 /* libPods-OHHTTPStubs iOS Lib Tests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-OHHTTPStubs iOS Lib Tests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; C0E954CB8F11618F9510F283 /* Pods-OHHTTPStubs iOS Lib Tests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-OHHTTPStubs iOS Lib Tests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-OHHTTPStubs iOS Lib Tests/Pods-OHHTTPStubs iOS Lib Tests.debug.xcconfig"; sourceTree = ""; }; DB9708EFC7D95D8EAE91EA78 /* Pods-OHHTTPStubs iOS Fmk Tests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-OHHTTPStubs iOS Fmk Tests.release.xcconfig"; path = "Pods/Target Support Files/Pods-OHHTTPStubs iOS Fmk Tests/Pods-OHHTTPStubs iOS Fmk Tests.release.xcconfig"; sourceTree = ""; }; E2483255B84CAC7897D6E98C /* Pods-OHHTTPStubs Mac Tests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-OHHTTPStubs Mac Tests.release.xcconfig"; path = "Pods/Target Support Files/Pods-OHHTTPStubs Mac Tests/Pods-OHHTTPStubs Mac Tests.release.xcconfig"; sourceTree = ""; }; + EA100AB71BE15BE400129352 /* OHHTTPStubs tvOS Fmk Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "OHHTTPStubs tvOS Fmk Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + EA9D27221BE15C740078CAA0 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/AppleTVOS.platform/Developer/SDKs/AppleTVOS9.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + EAA436A51BE1598D000E9E99 /* OHHTTPStubs.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = OHHTTPStubs.framework; sourceTree = BUILT_PRODUCTS_DIR; }; F49690D948DE88BBB4A36B11 /* libPods-OHHTTPStubs Mac Tests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-OHHTTPStubs Mac Tests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; FC7C82D3D508702D3B282621 /* libPods-OHHTTPStubs iOS Fmk Tests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-OHHTTPStubs iOS Fmk Tests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ @@ -263,6 +309,23 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + EA100AB41BE15BE400129352 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + EA9D27231BE15C740078CAA0 /* Foundation.framework in Frameworks */, + EA100ABC1BE15BE400129352 /* OHHTTPStubs.framework in Frameworks */, + 0D4BF5A17B4778591F08161F /* libPods-OHHTTPStubs tvOS Fmk Tests.a in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EAA436971BE1598D000E9E99 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ @@ -287,6 +350,8 @@ 095981D219806A7900807DBE /* OHHTTPStubs Mac Tests.xctest */, 725CD99B1A9EB65100F84C8B /* OHHTTPStubs.framework */, 093442F91B80EC4A00A91535 /* OHHTTPStubs iOS Fmk Tests.xctest */, + EAA436A51BE1598D000E9E99 /* OHHTTPStubs.framework */, + EA100AB71BE15BE400129352 /* OHHTTPStubs tvOS Fmk Tests.xctest */, ); name = Products; sourceTree = ""; @@ -294,6 +359,7 @@ 09110A4319805F4800D175E4 /* Frameworks */ = { isa = PBXGroup; children = ( + EA9D27221BE15C740078CAA0 /* Foundation.framework */, 09110A4419805F4800D175E4 /* Foundation.framework */, 09110A5219805F4800D175E4 /* XCTest.framework */, 0959819719806A4200807DBE /* Other Frameworks */, @@ -301,6 +367,7 @@ 446DA13BA37A8466FF4F9D35 /* libPods-OHHTTPStubs iOS Tests.a */, FC7C82D3D508702D3B282621 /* libPods-OHHTTPStubs iOS Fmk Tests.a */, BFA846B11753DE97A1D563D0 /* libPods-OHHTTPStubs iOS Lib Tests.a */, + BA8213D8FBCA73CF0607478B /* libPods-OHHTTPStubs tvOS Fmk Tests.a */, ); name = Frameworks; sourceTree = ""; @@ -470,6 +537,8 @@ DB9708EFC7D95D8EAE91EA78 /* Pods-OHHTTPStubs iOS Fmk Tests.release.xcconfig */, C0E954CB8F11618F9510F283 /* Pods-OHHTTPStubs iOS Lib Tests.debug.xcconfig */, 95E3CBB2346C0E2FBA46D63E /* Pods-OHHTTPStubs iOS Lib Tests.release.xcconfig */, + BEAE095678347F4BB47B8D3F /* Pods-OHHTTPStubs tvOS Fmk Tests.debug.xcconfig */, + 9E2F558594F0FA64E4C87BBB /* Pods-OHHTTPStubs tvOS Fmk Tests.release.xcconfig */, ); name = Pods; sourceTree = ""; @@ -507,6 +576,21 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + EAA436981BE1598D000E9E99 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + EAA436991BE1598D000E9E99 /* Compatibility.h in Headers */, + EAA4369A1BE1598D000E9E99 /* OHHTTPStubs.h in Headers */, + EAA4369B1BE1598D000E9E99 /* OHHTTPStubsResponse.h in Headers */, + EAA4369C1BE1598D000E9E99 /* OHHTTPStubsResponse+JSON.h in Headers */, + EAA4369D1BE1598D000E9E99 /* OHHTTPStubsResponse+HTTPMessage.h in Headers */, + EAA4369E1BE1598D000E9E99 /* OHHTTPStubs+Mocktail.h in Headers */, + EAA4369F1BE1598D000E9E99 /* OHPathHelpers.h in Headers */, + EAA436A01BE1598D000E9E99 /* OHHTTPStubsUmbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXHeadersBuildPhase section */ /* Begin PBXNativeTarget section */ @@ -626,13 +710,52 @@ productReference = 725CD99B1A9EB65100F84C8B /* OHHTTPStubs.framework */; productType = "com.apple.product-type.framework"; }; + EA100AB61BE15BE400129352 /* OHHTTPStubs tvOS Fmk Tests */ = { + isa = PBXNativeTarget; + buildConfigurationList = EA100ABF1BE15BE400129352 /* Build configuration list for PBXNativeTarget "OHHTTPStubs tvOS Fmk Tests" */; + buildPhases = ( + 12571D8F80AE616E05498AC3 /* Check Pods Manifest.lock */, + EA100AB31BE15BE400129352 /* Sources */, + EA100AB41BE15BE400129352 /* Frameworks */, + EA100AB51BE15BE400129352 /* Resources */, + B0A2A7148AAA43B25341BCB8 /* Embed Pods Frameworks */, + F7141306D92601BAC262BBE1 /* Copy Pods Resources */, + ); + buildRules = ( + ); + dependencies = ( + EA100ABE1BE15BE400129352 /* PBXTargetDependency */, + ); + name = "OHHTTPStubs tvOS Fmk Tests"; + productName = "OHHTTPStubs tvOS Fmk Tests"; + productReference = EA100AB71BE15BE400129352 /* OHHTTPStubs tvOS Fmk Tests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + EAA4368D1BE1598D000E9E99 /* OHHTTPStubs tvOS Framework */ = { + isa = PBXNativeTarget; + buildConfigurationList = EAA436A21BE1598D000E9E99 /* Build configuration list for PBXNativeTarget "OHHTTPStubs tvOS Framework" */; + buildPhases = ( + EAA4368E1BE1598D000E9E99 /* Sources */, + EAA436971BE1598D000E9E99 /* Frameworks */, + EAA436981BE1598D000E9E99 /* Headers */, + EAA436A11BE1598D000E9E99 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "OHHTTPStubs tvOS Framework"; + productName = "OHHTTPStubs iOS Framework"; + productReference = EAA436A51BE1598D000E9E99 /* OHHTTPStubs.framework */; + productType = "com.apple.product-type.framework"; + }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 09110A3919805F4800D175E4 /* Project object */ = { isa = PBXProject; attributes = { - LastSwiftUpdateCheck = 0700; + LastSwiftUpdateCheck = 0710; LastUpgradeCheck = 0700; ORGANIZATIONNAME = AliSoftware; TargetAttributes = { @@ -645,6 +768,9 @@ 725CD99A1A9EB65100F84C8B = { CreatedOnToolsVersion = 6.1.1; }; + EA100AB61BE15BE400129352 = { + CreatedOnToolsVersion = 7.1; + }; }; }; buildConfigurationList = 09110A3C19805F4800D175E4 /* Build configuration list for PBXProject "OHHTTPStubs" */; @@ -665,6 +791,8 @@ 093442DD1B80EC4A00A91535 /* OHHTTPStubs iOS Fmk Tests */, 095981C119806A7900807DBE /* OHHTTPStubs Mac Framework */, 095981D119806A7900807DBE /* OHHTTPStubs Mac Tests */, + EAA4368D1BE1598D000E9E99 /* OHHTTPStubs tvOS Framework */, + EA100AB61BE15BE400129352 /* OHHTTPStubs tvOS Fmk Tests */, ); }; /* End PBXProject section */ @@ -717,6 +845,24 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + EA100AB51BE15BE400129352 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + EA9D27241BE15CA00078CAA0 /* empty.bundle in Resources */, + EA9D27251BE15CA00078CAA0 /* emptyfile.json in Resources */, + EA9D27261BE15CA00078CAA0 /* login.tail in Resources */, + EA9D27271BE15CA00078CAA0 /* MocktailFolder in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EAA436A11BE1598D000E9E99 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ @@ -750,6 +896,21 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-OHHTTPStubs iOS Fmk Tests/Pods-OHHTTPStubs iOS Fmk Tests-resources.sh\"\n"; showEnvVarsInLog = 0; }; + 12571D8F80AE616E05498AC3 /* Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; 1E07E9B73004E60FD8FFF112 /* Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; @@ -810,6 +971,21 @@ shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; + B0A2A7148AAA43B25341BCB8 /* Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; BF1C89AB0FF2DD0E338DD44E /* Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; @@ -855,6 +1031,21 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-OHHTTPStubs iOS Lib Tests/Pods-OHHTTPStubs iOS Lib Tests-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; + F7141306D92601BAC262BBE1 /* Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -950,6 +1141,38 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + EA100AB31BE15BE400129352 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + EA9D272A1BE15CB50078CAA0 /* NilValuesTests.m in Sources */, + EA9D27301BE15CB50078CAA0 /* WithContentsOfURLTests.m in Sources */, + EA9D272D1BE15CB50078CAA0 /* NSURLSessionTests.m in Sources */, + EA9D27311BE15CB50078CAA0 /* SwiftHelpersTests.swift in Sources */, + EA9D272E1BE15CB50078CAA0 /* OHPathHelpersTests.m in Sources */, + EA9D272F1BE15CB50078CAA0 /* TimingTests.m in Sources */, + EA9D272C1BE15CB50078CAA0 /* NSURLConnectionTests.m in Sources */, + EA9D27281BE15CB50078CAA0 /* AFNetworkingTests.m in Sources */, + EA9D27291BE15CB50078CAA0 /* MocktailTests.m in Sources */, + EA9D272B1BE15CB50078CAA0 /* NSURLConnectionDelegateTests.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EAA4368E1BE1598D000E9E99 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + EAA4368F1BE1598D000E9E99 /* OHHTTPStubs.m in Sources */, + EAA436901BE1598D000E9E99 /* OHHTTPStubs+NSURLSessionConfiguration.m in Sources */, + EAA436911BE1598D000E9E99 /* OHHTTPStubs+Mocktail.m in Sources */, + EAA436921BE1598D000E9E99 /* OHHTTPStubsResponse.m in Sources */, + EAA436931BE1598D000E9E99 /* OHHTTPStubsResponse+JSON.m in Sources */, + EAA436941BE1598D000E9E99 /* OHHTTPStubsResponse+HTTPMessage.m in Sources */, + EAA436951BE1598D000E9E99 /* OHHTTPStubsSwift.swift in Sources */, + EAA436961BE1598D000E9E99 /* OHPathHelpers.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ @@ -968,6 +1191,11 @@ target = 095981C119806A7900807DBE /* OHHTTPStubs Mac Framework */; targetProxy = 095981D519806A7900807DBE /* PBXContainerItemProxy */; }; + EA100ABE1BE15BE400129352 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = EAA4368D1BE1598D000E9E99 /* OHHTTPStubs tvOS Framework */; + targetProxy = EA100ABD1BE15BE400129352 /* PBXContainerItemProxy */; + }; /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ @@ -1004,6 +1232,7 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 5.0; + MACOSX_DEPLOYMENT_TARGET = 10.7; MODULEMAP_FILE = "$(SRCROOT)/Supporting Files/module.modulemap"; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -1036,6 +1265,7 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 5.0; + MACOSX_DEPLOYMENT_TARGET = 10.7; MODULEMAP_FILE = "$(SRCROOT)/Supporting Files/module.modulemap"; SDKROOT = iphoneos; VALIDATE_PRODUCT = YES; @@ -1073,7 +1303,8 @@ "OHHTTPSTUBS_USE_STATIC_LIBRARY=1", ); INFOPLIST_FILE = "UnitTests/UnitTests-Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 6.0; + IPHONEOS_DEPLOYMENT_TARGET = 7.0; + MACOSX_DEPLOYMENT_TARGET = 10.9; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -1096,7 +1327,8 @@ "OHHTTPSTUBS_USE_STATIC_LIBRARY=1", ); INFOPLIST_FILE = "UnitTests/UnitTests-Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 6.0; + IPHONEOS_DEPLOYMENT_TARGET = 7.0; + MACOSX_DEPLOYMENT_TARGET = 10.9; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -1126,6 +1358,7 @@ INFOPLIST_FILE = "UnitTests/UnitTests-Info.plist"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.9; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -1152,6 +1385,7 @@ INFOPLIST_FILE = "UnitTests/UnitTests-Info.plist"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.9; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -1230,7 +1464,8 @@ "DEBUG=1", "$(inherited)", ); - MACOSX_DEPLOYMENT_TARGET = 10.8; + IPHONEOS_DEPLOYMENT_TARGET = 7.0; + MACOSX_DEPLOYMENT_TARGET = 10.9; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -1255,7 +1490,8 @@ GCC_ENABLE_OBJC_EXCEPTIONS = YES; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "UnitTests/UnitTests-Prefix.pch"; - MACOSX_DEPLOYMENT_TARGET = 10.8; + IPHONEOS_DEPLOYMENT_TARGET = 7.0; + MACOSX_DEPLOYMENT_TARGET = 10.9; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", @@ -1314,6 +1550,96 @@ }; name = Release; }; + EA100AC01BE15BE400129352 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = BEAE095678347F4BB47B8D3F /* Pods-OHHTTPStubs tvOS Fmk Tests.debug.xcconfig */; + buildSettings = { + CLANG_WARN_UNREACHABLE_CODE = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "UnitTests/UnitTests-Info.plist"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.9; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_BUNDLE_IDENTIFIER = "alisoftware.OHHTTPStubs-tvOS-Fmk-Tests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = appletvos; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TVOS_DEPLOYMENT_TARGET = 9.0; + }; + name = Debug; + }; + EA100AC11BE15BE400129352 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9E2F558594F0FA64E4C87BBB /* Pods-OHHTTPStubs tvOS Fmk Tests.release.xcconfig */; + buildSettings = { + CLANG_WARN_UNREACHABLE_CODE = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "UnitTests/UnitTests-Info.plist"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.9; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_BUNDLE_IDENTIFIER = "alisoftware.OHHTTPStubs-tvOS-Fmk-Tests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = appletvos; + TVOS_DEPLOYMENT_TARGET = 9.0; + }; + name = Release; + }; + EAA436A31BE1598D000E9E99 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_WARN_UNREACHABLE_CODE = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + INFOPLIST_FILE = "Supporting Files/OHHTTPStubs iOS-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_BUNDLE_IDENTIFIER = "com.alisoftware.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = OHHTTPStubs; + SDKROOT = appletvos; + SKIP_INSTALL = YES; + TVOS_DEPLOYMENT_TARGET = 9.0; + }; + name = Debug; + }; + EAA436A41BE1598D000E9E99 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_WARN_UNREACHABLE_CODE = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + INFOPLIST_FILE = "Supporting Files/OHHTTPStubs iOS-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_BUNDLE_IDENTIFIER = "com.alisoftware.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = OHHTTPStubs; + SDKROOT = appletvos; + SKIP_INSTALL = YES; + TVOS_DEPLOYMENT_TARGET = 9.0; + }; + name = Release; + }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ @@ -1380,6 +1706,24 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + EA100ABF1BE15BE400129352 /* Build configuration list for PBXNativeTarget "OHHTTPStubs tvOS Fmk Tests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + EA100AC01BE15BE400129352 /* Debug */, + EA100AC11BE15BE400129352 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + EAA436A21BE1598D000E9E99 /* Build configuration list for PBXNativeTarget "OHHTTPStubs tvOS Framework" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + EAA436A31BE1598D000E9E99 /* Debug */, + EAA436A41BE1598D000E9E99 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; /* End XCConfigurationList section */ }; rootObject = 09110A3919805F4800D175E4 /* Project object */; diff --git a/OHHTTPStubs/OHHTTPStubs.xcodeproj/xcshareddata/xcschemes/OHHTTPStubs tvOS Framework.xcscheme b/OHHTTPStubs/OHHTTPStubs.xcodeproj/xcshareddata/xcschemes/OHHTTPStubs tvOS Framework.xcscheme new file mode 100644 index 00000000..cde7ba1a --- /dev/null +++ b/OHHTTPStubs/OHHTTPStubs.xcodeproj/xcshareddata/xcschemes/OHHTTPStubs tvOS Framework.xcscheme @@ -0,0 +1,113 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OHHTTPStubs/OHHTTPStubs.xcworkspace/contents.xcworkspacedata b/OHHTTPStubs/OHHTTPStubs.xcworkspace/contents.xcworkspacedata index 06ceb62b..0458f8bf 100644 --- a/OHHTTPStubs/OHHTTPStubs.xcworkspace/contents.xcworkspacedata +++ b/OHHTTPStubs/OHHTTPStubs.xcworkspace/contents.xcworkspacedata @@ -1,6 +1,28 @@ + + + + + + + + + + + + + + diff --git a/OHHTTPStubs/Podfile b/OHHTTPStubs/Podfile index c20f4c54..9a0f333f 100644 --- a/OHHTTPStubs/Podfile +++ b/OHHTTPStubs/Podfile @@ -3,17 +3,26 @@ source 'https://github.com/CocoaPods/Specs.git' xcodeproj 'OHHTTPStubs.xcodeproj' inhibit_all_warnings! +def pod_afnetworking + pod 'AFNetworking', :git => 'https://github.com/AFNetworking/AFNetworking.git', :branch => '3_0_0_branch' +end + target 'OHHTTPStubs iOS Lib Tests' do - platform :ios, '6.0' - pod 'AFNetworking', '2.5.0' + platform :ios, '7.0' + pod_afnetworking end target 'OHHTTPStubs iOS Fmk Tests' do platform :ios, '8.0' - pod 'AFNetworking', '2.5.0' + pod_afnetworking end target 'OHHTTPStubs Mac Tests' do - platform :osx, '10.8' - pod 'AFNetworking', '2.5.0' + platform :osx, '10.9' + pod_afnetworking +end + +target 'OHHTTPStubs tvOS Fmk Tests' do + platform :tvos, '9.0' + pod_afnetworking end diff --git a/OHHTTPStubs/Podfile.lock b/OHHTTPStubs/Podfile.lock index fa01a7cb..f6c8deca 100644 --- a/OHHTTPStubs/Podfile.lock +++ b/OHHTTPStubs/Podfile.lock @@ -1,30 +1,35 @@ PODS: - - AFNetworking (2.5.0): - - AFNetworking/NSURLConnection (= 2.5.0) - - AFNetworking/NSURLSession (= 2.5.0) - - AFNetworking/Reachability (= 2.5.0) - - AFNetworking/Security (= 2.5.0) - - AFNetworking/Serialization (= 2.5.0) - - AFNetworking/UIKit (= 2.5.0) - - AFNetworking/NSURLConnection (2.5.0): + - AFNetworking (3.0.0-beta.1): + - AFNetworking/NSURLSession (= 3.0.0-beta.1) + - AFNetworking/Reachability (= 3.0.0-beta.1) + - AFNetworking/Security (= 3.0.0-beta.1) + - AFNetworking/Serialization (= 3.0.0-beta.1) + - AFNetworking/UIKit (= 3.0.0-beta.1) + - AFNetworking/NSURLSession (3.0.0-beta.1): - AFNetworking/Reachability - AFNetworking/Security - AFNetworking/Serialization - - AFNetworking/NSURLSession (2.5.0): - - AFNetworking/Reachability - - AFNetworking/Security - - AFNetworking/Serialization - - AFNetworking/Reachability (2.5.0) - - AFNetworking/Security (2.5.0) - - AFNetworking/Serialization (2.5.0) - - AFNetworking/UIKit (2.5.0): - - AFNetworking/NSURLConnection + - AFNetworking/Reachability (3.0.0-beta.1) + - AFNetworking/Security (3.0.0-beta.1) + - AFNetworking/Serialization (3.0.0-beta.1) + - AFNetworking/UIKit (3.0.0-beta.1): - AFNetworking/NSURLSession DEPENDENCIES: - - AFNetworking (= 2.5.0) + - AFNetworking (from `https://github.com/AFNetworking/AFNetworking.git`, branch + `3_0_0_branch`) + +EXTERNAL SOURCES: + AFNetworking: + :branch: 3_0_0_branch + :git: https://github.com/AFNetworking/AFNetworking.git + +CHECKOUT OPTIONS: + AFNetworking: + :commit: ef7d55b9556707d80af9edd83e504a91f9df2490 + :git: https://github.com/AFNetworking/AFNetworking.git SPEC CHECKSUMS: - AFNetworking: 96ac9bf3eda33582701cb1fcc5b896aa1e20311e + AFNetworking: 1100906802d9479aa0949e8e2cbc1d4e6beba327 COCOAPODS: 0.39.0 diff --git a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.h b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.h deleted file mode 100644 index dfa82f66..00000000 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.h +++ /dev/null @@ -1,67 +0,0 @@ -// AFHTTPRequestOperation.h -// -// Copyright (c) 2013-2014 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 "AFURLConnectionOperation.h" - -/** - `AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request. - */ -@interface AFHTTPRequestOperation : AFURLConnectionOperation - -///------------------------------------------------ -/// @name Getting HTTP URL Connection Information -///------------------------------------------------ - -/** - The last HTTP response received by the operation's connection. - */ -@property (readonly, nonatomic, strong) NSHTTPURLResponse *response; - -/** - Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an AFHTTPResponse serializer, which uses the raw data as its response object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed. - - @warning `responseSerializer` must not be `nil`. Setting a response serializer will clear out any cached value - */ -@property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; - -/** - An object constructed by the `responseSerializer` from the response and response data. Returns `nil` unless the operation `isFinished`, has a `response`, and has `responseData` with non-zero content length. If an error occurs during serialization, `nil` will be returned, and the `error` property will be populated with the serialization error. - */ -@property (readonly, nonatomic, strong) id responseObject; - -///----------------------------------------------------------- -/// @name Setting Completion Block Success / Failure Callbacks -///----------------------------------------------------------- - -/** - Sets the `completionBlock` property with a block that executes either the specified success or failure block, depending on the state of the request on completion. If `error` returns a value, which can be caused by an unacceptable status code or content type, then `failure` is executed. Otherwise, `success` is executed. - - This method should be overridden in subclasses in order to specify the response object passed into the success block. - - @param success The block to be executed on the completion of a successful request. This block has no return value and takes two arguments: the receiver operation and the object constructed from the response data of the request. - @param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that occurred during the request. - */ -- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -@end diff --git a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m deleted file mode 100644 index 1de5812c..00000000 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m +++ /dev/null @@ -1,206 +0,0 @@ -// AFHTTPRequestOperation.m -// -// Copyright (c) 2013-2014 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 "AFHTTPRequestOperation.h" - -static dispatch_queue_t http_request_operation_processing_queue() { - static dispatch_queue_t af_http_request_operation_processing_queue; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_http_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.http-request.processing", DISPATCH_QUEUE_CONCURRENT); - }); - - return af_http_request_operation_processing_queue; -} - -static dispatch_group_t http_request_operation_completion_group() { - static dispatch_group_t af_http_request_operation_completion_group; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_http_request_operation_completion_group = dispatch_group_create(); - }); - - return af_http_request_operation_completion_group; -} - -#pragma mark - - -@interface AFURLConnectionOperation () -@property (readwrite, nonatomic, strong) NSURLRequest *request; -@property (readwrite, nonatomic, strong) NSURLResponse *response; -@end - -@interface AFHTTPRequestOperation () -@property (readwrite, nonatomic, strong) NSHTTPURLResponse *response; -@property (readwrite, nonatomic, strong) id responseObject; -@property (readwrite, nonatomic, strong) NSError *responseSerializationError; -@property (readwrite, nonatomic, strong) NSRecursiveLock *lock; -@end - -@implementation AFHTTPRequestOperation -@dynamic lock; - -- (instancetype)initWithRequest:(NSURLRequest *)urlRequest { - self = [super initWithRequest:urlRequest]; - if (!self) { - return nil; - } - - self.responseSerializer = [AFHTTPResponseSerializer serializer]; - - return self; -} - -- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { - NSParameterAssert(responseSerializer); - - [self.lock lock]; - _responseSerializer = responseSerializer; - self.responseObject = nil; - self.responseSerializationError = nil; - [self.lock unlock]; -} - -- (id)responseObject { - [self.lock lock]; - if (!_responseObject && [self isFinished] && !self.error) { - NSError *error = nil; - self.responseObject = [self.responseSerializer responseObjectForResponse:self.response data:self.responseData error:&error]; - if (error) { - self.responseSerializationError = error; - } - } - [self.lock unlock]; - - return _responseObject; -} - -- (NSError *)error { - if (_responseSerializationError) { - return _responseSerializationError; - } else { - return [super error]; - } -} - -#pragma mark - AFHTTPRequestOperation - -- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - // completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle. -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Warc-retain-cycles" -#pragma clang diagnostic ignored "-Wgnu" - self.completionBlock = ^{ - if (self.completionGroup) { - dispatch_group_enter(self.completionGroup); - } - - dispatch_async(http_request_operation_processing_queue(), ^{ - if (self.error) { - if (failure) { - dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{ - failure(self, self.error); - }); - } - } else { - id responseObject = self.responseObject; - if (self.error) { - if (failure) { - dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{ - failure(self, self.error); - }); - } - } else { - if (success) { - dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{ - success(self, responseObject); - }); - } - } - } - - if (self.completionGroup) { - dispatch_group_leave(self.completionGroup); - } - }); - }; -#pragma clang diagnostic pop -} - -#pragma mark - AFURLRequestOperation - -- (void)pause { - [super pause]; - - u_int64_t offset = 0; - if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) { - offset = [(NSNumber *)[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue]; - } else { - offset = [(NSData *)[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length]; - } - - NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy]; - if ([self.response respondsToSelector:@selector(allHeaderFields)] && [[self.response allHeaderFields] valueForKey:@"ETag"]) { - [mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"]; - } - [mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"]; - self.request = mutableURLRequest; -} - -#pragma mark - NSSecureCoding - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (id)initWithCoder:(NSCoder *)decoder { - self = [super initWithCoder:decoder]; - if (!self) { - return nil; - } - - self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - - [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFHTTPRequestOperation *operation = [super copyWithZone:zone]; - - operation.responseSerializer = [self.responseSerializer copyWithZone:zone]; - operation.completionQueue = self.completionQueue; - operation.completionGroup = self.completionGroup; - - return operation; -} - -@end diff --git a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.h b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.h deleted file mode 100644 index 9f390294..00000000 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.h +++ /dev/null @@ -1,308 +0,0 @@ -// AFHTTPRequestOperationManager.h -// -// Copyright (c) 2013-2014 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 - -#if __IPHONE_OS_VERSION_MIN_REQUIRED -#import -#else -#import -#endif - -#import "AFHTTPRequestOperation.h" -#import "AFURLResponseSerialization.h" -#import "AFURLRequestSerialization.h" -#import "AFSecurityPolicy.h" -#import "AFNetworkReachabilityManager.h" - -/** - `AFHTTPRequestOperationManager` encapsulates the common patterns of communicating with a web application over HTTP, including request creation, response serialization, network reachability monitoring, and security, as well as request operation management. - - ## Subclassing Notes - - Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application. - - For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect. - - ## Methods to Override - - To change the behavior of all request operation construction for an `AFHTTPRequestOperationManager` subclass, override `HTTPRequestOperationWithRequest:success:failure`. - - ## Serialization - - Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to ``. - - 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. - - ## 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. - - ## NSSecureCoding & NSCopying Caveats - - `AFHTTPRequestOperationManager` conforms to the `NSSecureCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however: - - - Archives and copies of HTTP clients will be initialized with an empty operation queue. - - NSSecureCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set. - */ -@interface AFHTTPRequestOperationManager : NSObject - -/** - The URL used to monitor reachability, and construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods. - */ -@property (readonly, nonatomic, strong) NSURL *baseURL; - -/** - Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `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 a JSON serializer, which serializes data from responses with a `application/json` MIME type, and falls back to the raw data object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed. - - @warning `responseSerializer` must not be `nil`. - */ -@property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; - -/** - The operation queue on which request operations are scheduled and run. - */ -@property (nonatomic, strong) NSOperationQueue *operationQueue; - -///------------------------------- -/// @name Managing URL Credentials -///------------------------------- - -/** - Whether request operations should consult the credential storage for authenticating the connection. `YES` by default. - - @see AFURLConnectionOperation -shouldUseCredentialStorage - */ -@property (nonatomic, assign) BOOL shouldUseCredentialStorage; - -/** - The credential used by request operations for authentication challenges. - - @see AFURLConnectionOperation -credential - */ -@property (nonatomic, strong) NSURLCredential *credential; - -///------------------------------- -/// @name Managing Security Policy -///------------------------------- - -/** - The security policy used by created request operations to evaluate server trust for secure connections. `AFHTTPRequestOperationManager` uses the `defaultPolicy` unless otherwise specified. - */ -@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; - -///------------------------------------ -/// @name Managing Network Reachability -///------------------------------------ - -/** - The network reachability manager. `AFHTTPRequestOperationManager` uses the `sharedManager` by default. - */ -@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; - -///------------------------------- -/// @name Managing Callback Queues -///------------------------------- - -/** - The dispatch queue for the `completionBlock` of request operations. If `NULL` (default), the main queue is used. - */ -@property (nonatomic, strong) dispatch_queue_t completionQueue; - -/** - The dispatch group for the `completionBlock` of request operations. If `NULL` (default), a private dispatch group is used. - */ -@property (nonatomic, strong) dispatch_group_t completionGroup; - -///--------------------------------------------- -/// @name Creating and Initializing HTTP Clients -///--------------------------------------------- - -/** - Creates and returns an `AFHTTPRequestOperationManager` object. - */ -+ (instancetype)manager; - -/** - Initializes an `AFHTTPRequestOperationManager` object with the specified base URL. - - This is the designated initializer. - - @param url The base URL for the HTTP client. - - @return The newly-initialized HTTP client - */ -- (instancetype)initWithBaseURL:(NSURL *)url; - -///--------------------------------------- -/// @name Managing HTTP Request Operations -///--------------------------------------- - -/** - Creates an `AFHTTPRequestOperation`, and sets the response serializers to that of the HTTP client. - - @param request The request object to be loaded asynchronously during execution of the operation. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request. - @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred. - */ -- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -///--------------------------- -/// @name Making HTTP Requests -///--------------------------- - -/** - Creates and runs an `AFHTTPRequestOperation` with a `GET` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. - @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)GET:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates and runs an `AFHTTPRequestOperation` with a `HEAD` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes a single arguments: the request operation. - @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)HEAD:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates and runs an `AFHTTPRequestOperation` with a `POST` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. - @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)POST:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates and runs an `AFHTTPRequestOperation` with a multipart `POST` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. - @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)POST:(NSString *)URLString - parameters:(id)parameters - constructingBodyWithBlock:(void (^)(id formData))block - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates and runs an `AFHTTPRequestOperation` with a `PUT` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. - @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)PUT:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates and runs an `AFHTTPRequestOperation` with a `PATCH` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. - @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)PATCH:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates and runs an `AFHTTPRequestOperation` with a `DELETE` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. - @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)DELETE:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -@end - diff --git a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.m b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.m deleted file mode 100644 index 4ae72754..00000000 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperationManager.m +++ /dev/null @@ -1,253 +0,0 @@ -// AFHTTPRequestOperationManager.m -// -// Copyright (c) 2013-2014 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 "AFHTTPRequestOperationManager.h" -#import "AFHTTPRequestOperation.h" - -#import -#import - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#import -#endif - -@interface AFHTTPRequestOperationManager () -@property (readwrite, nonatomic, strong) NSURL *baseURL; -@end - -@implementation AFHTTPRequestOperationManager - -+ (instancetype)manager { - return [[self alloc] initWithBaseURL:nil]; -} - -- (instancetype)init { - return [self initWithBaseURL:nil]; -} - -- (instancetype)initWithBaseURL:(NSURL *)url { - self = [super init]; - if (!self) { - return nil; - } - - // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected - if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) { - url = [url URLByAppendingPathComponent:@""]; - } - - self.baseURL = url; - - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - self.responseSerializer = [AFJSONResponseSerializer serializer]; - - self.securityPolicy = [AFSecurityPolicy defaultPolicy]; - - self.reachabilityManager = [AFNetworkReachabilityManager sharedManager]; - - self.operationQueue = [[NSOperationQueue alloc] init]; - - self.shouldUseCredentialStorage = YES; - - return self; -} - -#pragma mark - - -#ifdef _SYSTEMCONFIGURATION_H -#endif - -- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { - NSParameterAssert(requestSerializer); - - _requestSerializer = requestSerializer; -} - -- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { - NSParameterAssert(responseSerializer); - - _responseSerializer = responseSerializer; -} - -#pragma mark - - -- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; - operation.responseSerializer = self.responseSerializer; - operation.shouldUseCredentialStorage = self.shouldUseCredentialStorage; - operation.credential = self.credential; - operation.securityPolicy = self.securityPolicy; - - [operation setCompletionBlockWithSuccess:success failure:failure]; - operation.completionQueue = self.completionQueue; - operation.completionGroup = self.completionGroup; - - return operation; -} - -#pragma mark - - -- (AFHTTPRequestOperation *)GET:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"GET" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -- (AFHTTPRequestOperation *)HEAD:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"HEAD" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *requestOperation, __unused id responseObject) { - if (success) { - success(requestOperation); - } - } failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -- (AFHTTPRequestOperation *)POST:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -- (AFHTTPRequestOperation *)POST:(NSString *)URLString - parameters:(id)parameters - constructingBodyWithBlock:(void (^)(id formData))block - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -- (AFHTTPRequestOperation *)PUT:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"PUT" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -- (AFHTTPRequestOperation *)PATCH:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"PATCH" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -- (AFHTTPRequestOperation *)DELETE:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"DELETE" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -#pragma mark - NSObject - -- (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.operationQueue]; -} - -#pragma mark - NSSecureCoding - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (id)initWithCoder:(NSCoder *)decoder { - NSURL *baseURL = [decoder decodeObjectForKey:NSStringFromSelector(@selector(baseURL))]; - - self = [self initWithBaseURL:baseURL]; - if (!self) { - return nil; - } - - self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))]; - self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))]; - [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))]; - [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFHTTPRequestOperationManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL]; - - HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone]; - HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone]; - - return HTTPClient; -} - -@end diff --git a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h index 8fed5a68..3e0b9af4 100644 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h +++ b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h @@ -1,6 +1,5 @@ // AFHTTPSessionManager.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2015 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 @@ -21,10 +20,12 @@ // THE SOFTWARE. #import +#if !TARGET_OS_WATCH #import -#import +#endif +#import -#if __IPHONE_OS_VERSION_MIN_REQUIRED +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV #import #else #import @@ -32,6 +33,14 @@ #import "AFURLSessionManager.h" +#ifndef NS_DESIGNATED_INITIALIZER +#if __has_attribute(objc_designated_initializer) +#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) +#else +#define NS_DESIGNATED_INITIALIZER +#endif +#endif + /** `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. @@ -70,14 +79,14 @@ @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. */ -#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) +NS_ASSUME_NONNULL_BEGIN @interface AFHTTPSessionManager : AFURLSessionManager /** - The URL used to monitor reachability, and construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods. + 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) NSURL *baseURL; +@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. @@ -109,7 +118,7 @@ @return The newly-initialized HTTP client */ -- (instancetype)initWithBaseURL:(NSURL *)url; +- (instancetype)initWithBaseURL:(nullable NSURL *)url; /** Initializes an `AFHTTPSessionManager` object with the specified base URL. @@ -121,8 +130,8 @@ @return The newly-initialized HTTP client */ -- (instancetype)initWithBaseURL:(NSURL *)url - sessionConfiguration:(NSURLSessionConfiguration *)configuration; +- (instancetype)initWithBaseURL:(nullable NSURL *)url + sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; ///--------------------------- /// @name Making HTTP Requests @@ -138,10 +147,10 @@ @see -dataTaskWithRequest:completionHandler: */ -- (NSURLSessionDataTask *)GET:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; +- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * __nullable task, NSError *error))failure; /** Creates and runs an `NSURLSessionDataTask` with a `HEAD` request. @@ -153,10 +162,10 @@ @see -dataTaskWithRequest:completionHandler: */ -- (NSURLSessionDataTask *)HEAD:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; +- (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. @@ -168,10 +177,10 @@ @see -dataTaskWithRequest:completionHandler: */ -- (NSURLSessionDataTask *)POST:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * __nullable task, NSError *error))failure; /** Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. @@ -184,11 +193,11 @@ @see -dataTaskWithRequest:completionHandler: */ -- (NSURLSessionDataTask *)POST:(NSString *)URLString - parameters:(id)parameters - constructingBodyWithBlock:(void (^)(id formData))block - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + constructingBodyWithBlock:(nullable void (^)(id formData))block + success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * __nullable task, NSError *error))failure; /** Creates and runs an `NSURLSessionDataTask` with a `PUT` request. @@ -200,10 +209,10 @@ @see -dataTaskWithRequest:completionHandler: */ -- (NSURLSessionDataTask *)PUT:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; +- (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * __nullable task, NSError *error))failure; /** Creates and runs an `NSURLSessionDataTask` with a `PATCH` request. @@ -215,10 +224,10 @@ @see -dataTaskWithRequest:completionHandler: */ -- (NSURLSessionDataTask *)PATCH:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; +- (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * __nullable task, NSError *error))failure; /** Creates and runs an `NSURLSessionDataTask` with a `DELETE` request. @@ -230,11 +239,11 @@ @see -dataTaskWithRequest:completionHandler: */ -- (NSURLSessionDataTask *)DELETE:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; +- (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * __nullable task, NSError *error))failure; @end -#endif +NS_ASSUME_NONNULL_END diff --git a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m index 6413297d..700929bb 100644 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m +++ b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m @@ -1,6 +1,5 @@ // AFHTTPSessionManager.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2015 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 @@ -22,12 +21,11 @@ #import "AFHTTPSessionManager.h" -#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) - #import "AFURLRequestSerialization.h" #import "AFURLResponseSerialization.h" #import +#import #import #ifdef _SYSTEMCONFIGURATION_H @@ -38,8 +36,10 @@ #import #endif -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_TV #import +#elif TARGET_OS_WATCH +#import #endif @interface AFHTTPSessionManager () @@ -47,6 +47,7 @@ @interface AFHTTPSessionManager () @end @implementation AFHTTPSessionManager +@dynamic responseSerializer; + (instancetype)manager { return [[[self class] alloc] initWithBaseURL:nil]; @@ -267,7 +268,7 @@ + (BOOL)supportsSecureCoding { return YES; } -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))]; NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; if (!configuration) { @@ -288,6 +289,10 @@ - (id)initWithCoder:(NSCoder *)decoder { 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; } @@ -303,19 +308,18 @@ - (void)encodeWithCoder:(NSCoder *)coder { } [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 -- (id)copyWithZone:(NSZone *)zone { +- (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 - -#endif diff --git a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h index 5e610d88..e2eb945d 100644 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h +++ b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h @@ -1,6 +1,5 @@ // AFNetworkReachabilityManager.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2015 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 @@ -8,10 +7,10 @@ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,8 +20,18 @@ // THE SOFTWARE. #import + +#if !TARGET_OS_WATCH #import +#ifndef NS_DESIGNATED_INITIALIZER +#if __has_attribute(objc_designated_initializer) +#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) +#else +#define NS_DESIGNATED_INITIALIZER +#endif +#endif + typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { AFNetworkReachabilityStatusUnknown = -1, AFNetworkReachabilityStatusNotReachable = 0, @@ -30,13 +39,15 @@ typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { 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 @@ -72,9 +83,9 @@ typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { /** 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; @@ -90,12 +101,12 @@ typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { /** 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; +- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER; ///-------------------------------------------------- /// @name Starting & Stopping Reachability Monitoring @@ -129,7 +140,7 @@ typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`. */ -- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block; +- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block; @end @@ -180,8 +191,8 @@ typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { @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`). */ -extern NSString * const AFNetworkingReachabilityDidChangeNotification; -extern NSString * const AFNetworkingReachabilityNotificationStatusItem; +FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification; +FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem; ///-------------------- /// @name Functions @@ -190,4 +201,7 @@ extern NSString * const AFNetworkingReachabilityNotificationStatusItem; /** Returns a localized string representation of an `AFNetworkReachabilityStatus` value. */ -extern NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); +FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); + +NS_ASSUME_NONNULL_END +#endif diff --git a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m index 1da14828..2e5e2edb 100644 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m +++ b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m @@ -1,6 +1,5 @@ // AFNetworkReachabilityManager.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2015 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 @@ -8,10 +7,10 @@ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +20,7 @@ // THE SOFTWARE. #import "AFNetworkReachabilityManager.h" +#if !TARGET_OS_WATCH #import #import @@ -86,9 +86,10 @@ static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused targ dispatch_async(dispatch_get_main_queue(), ^{ NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:@{ AFNetworkingReachabilityNotificationStatusItem: @(status) }]; + NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) }; + [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo]; }); - + } static const void * AFNetworkReachabilityRetainCallback(const void *info) { @@ -102,7 +103,7 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) { } @interface AFNetworkReachabilityManager () -@property (readwrite, nonatomic, assign) SCNetworkReachabilityRef networkReachability; +@property (readwrite, nonatomic, strong) id networkReachability; @property (readwrite, nonatomic, assign) AFNetworkReachabilityAssociation networkReachabilityAssociation; @property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; @property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock; @@ -149,19 +150,19 @@ - (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability { return nil; } - self.networkReachability = reachability; + self.networkReachability = CFBridgingRelease(reachability); self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; return self; } +- (instancetype)init NS_UNAVAILABLE +{ + return nil; +} + - (void)dealloc { [self stopMonitoring]; - - if (_networkReachability) { - CFRelease(_networkReachability); - _networkReachability = NULL; - } } #pragma mark - @@ -198,9 +199,10 @@ - (void)startMonitoring { }; + id networkReachability = self.networkReachability; SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; - SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context); - SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); + SCNetworkReachabilitySetCallback((__bridge SCNetworkReachabilityRef)networkReachability, AFNetworkReachabilityCallback, &context); + SCNetworkReachabilityScheduleWithRunLoop((__bridge SCNetworkReachabilityRef)networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); switch (self.networkReachabilityAssociation) { case AFNetworkReachabilityForName: @@ -210,15 +212,15 @@ - (void)startMonitoring { default: { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ SCNetworkReachabilityFlags flags; - SCNetworkReachabilityGetFlags(self.networkReachability, &flags); + SCNetworkReachabilityGetFlags((__bridge SCNetworkReachabilityRef)networkReachability, &flags); AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); dispatch_async(dispatch_get_main_queue(), ^{ callback(status); - + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:@{ AFNetworkingReachabilityNotificationStatusItem: @(status) }]; - + }); }); } @@ -231,7 +233,7 @@ - (void)stopMonitoring { return; } - SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); + SCNetworkReachabilityUnscheduleFromRunLoop((__bridge SCNetworkReachabilityRef)self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); } #pragma mark - @@ -257,3 +259,4 @@ + (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key { } @end +#endif diff --git a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFNetworking.h b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFNetworking.h index 68273da5..e2fb2f44 100644 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFNetworking.h +++ b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFNetworking.h @@ -22,6 +22,7 @@ #import #import +#import #ifndef _AFNETWORKING_ #define _AFNETWORKING_ @@ -29,16 +30,12 @@ #import "AFURLRequestSerialization.h" #import "AFURLResponseSerialization.h" #import "AFSecurityPolicy.h" - #import "AFNetworkReachabilityManager.h" - #import "AFURLConnectionOperation.h" - #import "AFHTTPRequestOperation.h" - #import "AFHTTPRequestOperationManager.h" +#if !TARGET_OS_WATCH + #import "AFNetworkReachabilityManager.h" +#endif -#if ( ( defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || \ - ( defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 ) ) #import "AFURLSessionManager.h" #import "AFHTTPSessionManager.h" -#endif #endif /* _AFNETWORKING_ */ diff --git a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h index a880d751..80df91d5 100644 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h +++ b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h @@ -1,6 +1,5 @@ -// AFSecurity.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// AFSecurityPolicy.h +// Copyright (c) 2011–2015 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 @@ -31,10 +30,13 @@ typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { /** `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. */ -@interface AFSecurityPolicy : NSObject + +NS_ASSUME_NONNULL_BEGIN + +@interface AFSecurityPolicy : NSObject /** The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`. @@ -42,14 +44,13 @@ typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { @property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode; /** - Whether to evaluate an entire SSL certificate chain, or just the leaf certificate. Defaults to `YES`. - */ -@property (nonatomic, assign) BOOL validatesCertificateChain; + The certificates used to evaluate server trust according to the SSL pinning mode. -/** - The certificates used to evaluate server trust according to the SSL pinning mode. By default, this property is set to any (`.cer`) certificates included in the app bundle. + 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 you create an array with duplicate certificates, the duplicate certificates will be removed. Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches. */ -@property (nonatomic, strong) NSArray *pinnedCertificates; +@property (nonatomic, strong, nullable) NSArray *pinnedCertificates; /** Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. @@ -57,17 +58,28 @@ typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { @property (nonatomic, assign) BOOL allowInvalidCertificates; /** - Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES` for `AFSSLPinningModePublicKey` or `AFSSLPinningModeCertificate`, otherwise `NO`. + 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 default security policy. + */ ++ (NSArray *)certificatesInBundle:(NSBundle *)bundle; + ///----------------------------------------- /// @name Getting Specific Security Policies ///----------------------------------------- /** - Returns the shared default security policy, which does not allow invalid certificates, does not validate domain name, and does not validate against pinned certificates or public keys. - + 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; @@ -80,11 +92,21 @@ typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { 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:(NSArray *)pinnedCertificates; + ///------------------------------ /// @name Evaluating Server Trust ///------------------------------ @@ -97,26 +119,28 @@ typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { @param serverTrust The X.509 certificate trust of the server. @return Whether or not to trust the server. - + @warning This method has been deprecated in favor of `-evaluateServerTrust:forDomain:`. */ - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust DEPRECATED_ATTRIBUTE; /** - Whether or not the specified server trust should be accepted, based on the security policy. - + 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:(NSString *)domain; + forDomain:(nullable NSString *)domain; @end +NS_ASSUME_NONNULL_END + ///---------------- /// @name Constants ///---------------- diff --git a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m index 1f97f914..b014d75b 100644 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m +++ b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m @@ -1,6 +1,5 @@ -// AFSecurity.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// AFSecurityPolicy.m +// Copyright (c) 2011–2015 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 @@ -22,31 +21,13 @@ #import "AFSecurityPolicy.h" -// Equivalent of macro in , without causing compiler warning: -// "'DebugAssert' is deprecated: first deprecated in OS X 10.8" -#ifndef AF_Require - #define AF_Require(assertion, exceptionLabel) \ - do { \ - if (__builtin_expect(!(assertion), 0)) { \ - goto exceptionLabel; \ - } \ - } while (0) -#endif - -#ifndef AF_Require_noErr - #define AF_Require_noErr(errorCode, exceptionLabel) \ - do { \ - if (__builtin_expect(0 != (errorCode), 0)) { \ - goto exceptionLabel; \ - } \ - } while (0) -#endif +#import -#if !defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV static NSData * AFSecKeyGetData(SecKeyRef key) { CFDataRef data = NULL; - AF_Require_noErr(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out); + __Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out); return (__bridge_transfer NSData *)data; @@ -60,7 +41,7 @@ #endif static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) { -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#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)]; @@ -77,14 +58,14 @@ static id AFPublicKeyForCertificate(NSData *certificate) { SecTrustResultType result; allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate); - AF_Require(allowedCertificate != NULL, _out); + __Require_Quiet(allowedCertificate != NULL, _out); allowedCertificates[0] = allowedCertificate; tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL); policy = SecPolicyCreateBasicX509(); - AF_Require_noErr(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out); - AF_Require_noErr(SecTrustEvaluate(allowedTrust, &result), _out); + __Require_noErr_Quiet(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out); + __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out); allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust); @@ -111,7 +92,7 @@ static id AFPublicKeyForCertificate(NSData *certificate) { static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) { BOOL isValid = NO; SecTrustResultType result; - AF_Require_noErr(SecTrustEvaluate(serverTrust, &result), _out); + __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out); isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed); @@ -142,10 +123,10 @@ static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) { CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL); SecTrustRef trust; - AF_Require_noErr(SecTrustCreateWithCertificates(certificates, policy, &trust), _out); - + __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out); + SecTrustResultType result; - AF_Require_noErr(SecTrustEvaluate(trust, &result), _out); + __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out); [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)]; @@ -174,20 +155,24 @@ @interface AFSecurityPolicy() @implementation AFSecurityPolicy ++ (NSArray *)certificatesInBundle:(NSBundle *)bundle { + NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; + + NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]]; + for (NSString *path in paths) { + NSData *certificateData = [NSData dataWithContentsOfFile:path]; + [certificates addObject:certificateData]; + } + + return [[NSArray alloc] initWithArray:certificates]; +} + + (NSArray *)defaultPinnedCertificates { static NSArray *_defaultPinnedCertificates = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSBundle *bundle = [NSBundle bundleForClass:[self class]]; - NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; - - NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]]; - for (NSString *path in paths) { - NSData *certificateData = [NSData dataWithContentsOfFile:path]; - [certificates addObject:certificateData]; - } - - _defaultPinnedCertificates = [[NSArray alloc] initWithArray:certificates]; + _defaultPinnedCertificates = [self certificatesInBundle:bundle]; }); return _defaultPinnedCertificates; @@ -201,43 +186,31 @@ + (instancetype)defaultPolicy { } + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode { + return [self policyWithPinningMode:pinningMode withPinnedCertificates:[self defaultPinnedCertificates]]; +} + ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSArray *)pinnedCertificates { AFSecurityPolicy *securityPolicy = [[self alloc] init]; securityPolicy.SSLPinningMode = pinningMode; - [securityPolicy setPinnedCertificates:[self defaultPinnedCertificates]]; + [securityPolicy setPinnedCertificates:pinnedCertificates]; return securityPolicy; } -- (id)init { +- (instancetype)init { self = [super init]; if (!self) { return nil; } - self.validatesCertificateChain = YES; + self.validatesDomainName = YES; return self; } -#pragma mark - - -- (void)setSSLPinningMode:(AFSSLPinningMode)SSLPinningMode { - _SSLPinningMode = SSLPinningMode; - - switch (self.SSLPinningMode) { - case AFSSLPinningModePublicKey: - case AFSSLPinningModeCertificate: - self.validatesDomainName = YES; - break; - default: - self.validatesDomainName = NO; - break; - } -} - - (void)setPinnedCertificates:(NSArray *)pinnedCertificates { - _pinnedCertificates = pinnedCertificates; + _pinnedCertificates = [[NSOrderedSet orderedSetWithArray:pinnedCertificates] array]; if (self.pinnedCertificates) { NSMutableArray *mutablePinnedPublicKeys = [NSMutableArray arrayWithCapacity:[self.pinnedCertificates count]]; @@ -263,6 +236,19 @@ - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust { - (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)]; @@ -272,14 +258,17 @@ - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies); - if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) { + if (self.SSLPinningMode == AFSSLPinningModeNone) { + return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust); + } else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) { return NO; } NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); switch (self.SSLPinningMode) { case AFSSLPinningModeNone: - return YES; + default: + return NO; case AFSSLPinningModeCertificate: { NSMutableArray *pinnedCertificates = [NSMutableArray array]; for (NSData *certificateData in self.pinnedCertificates) { @@ -291,25 +280,17 @@ - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust return NO; } - if (!self.validatesCertificateChain) { - return YES; - } - NSUInteger trustedCertificateCount = 0; for (NSData *trustChainCertificate in serverCertificates) { if ([self.pinnedCertificates containsObject:trustChainCertificate]) { trustedCertificateCount++; } } - - return trustedCertificateCount == [serverCertificates count]; + return trustedCertificateCount > 0; } case AFSSLPinningModePublicKey: { NSUInteger trustedPublicKeyCount = 0; NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust); - if (!self.validatesCertificateChain && [publicKeys count] > 0) { - publicKeys = @[[publicKeys firstObject]]; - } for (id trustChainPublicKey in publicKeys) { for (id pinnedPublicKey in self.pinnedPublicKeys) { @@ -318,8 +299,7 @@ - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust } } } - - return trustedPublicKeyCount > 0 && ((self.validatesCertificateChain && trustedPublicKeyCount == [serverCertificates count]) || (!self.validatesCertificateChain && trustedPublicKeyCount >= 1)); + return trustedPublicKeyCount > 0; } } @@ -332,4 +312,44 @@ + (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/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.h b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.h deleted file mode 100644 index 85435564..00000000 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.h +++ /dev/null @@ -1,328 +0,0 @@ -// AFURLConnectionOperation.h -// -// Copyright (c) 2013-2014 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 "AFURLRequestSerialization.h" -#import "AFURLResponseSerialization.h" -#import "AFSecurityPolicy.h" - -/** - `AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods. - - ## Subclassing Notes - - This is the base class of all network request operations. You may wish to create your own subclass in order to implement additional `NSURLConnection` delegate methods (see "`NSURLConnection` Delegate Methods" below), or to provide additional properties and/or class constructors. - - If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `AFHTTPRequestOperation` instead, as it supports specifying acceptable content types or status codes. - - ## NSURLConnection Delegate Methods - - `AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods: - - - `connection:didReceiveResponse:` - - `connection:didReceiveData:` - - `connectionDidFinishLoading:` - - `connection:didFailWithError:` - - `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:` - - `connection:willCacheResponse:` - - `connectionShouldUseCredentialStorage:` - - `connection:needNewBodyStream:` - - `connection:willSendRequestForAuthenticationChallenge:` - - If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. - - ## Callbacks and Completion Blocks - - The built-in `completionBlock` provided by `NSOperation` allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its `completionBlock`. Make sure to handle cancelled operations appropriately when setting a `completionBlock` (i.e. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this. - - Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `AFURLConnectionOperation`'s implementation includes a workaround to mitigate retain cycles, and what Apple rather ominously refers to as ["The Deallocation Problem"](http://developer.apple.com/library/ios/#technotes/tn2109/). - - ## SSL Pinning - - Relying on the CA trust model to validate SSL certificates exposes your app to security vulnerabilities, such as man-in-the-middle attacks. For applications that connect to known servers, SSL certificate pinning provides an increased level of security, by checking server certificate validity against those specified in the app bundle. - - SSL with certificate pinning is strongly recommended for any application that transmits sensitive information to an external webservice. - - Connections will be validated on all matching certificates with a `.cer` extension in the bundle root. - - ## App Extensions - - When using AFNetworking in an App Extension, `#define AF_APP_EXTENSIONS` to avoid using unavailable APIs. - - ## NSCoding & NSCopying Conformance - - `AFURLConnectionOperation` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. However, because of the intrinsic limitations of capturing the exact state of an operation at a particular moment, there are some important caveats to keep in mind: - - ### NSCoding Caveats - - - Encoded operations do not include any block or stream properties. Be sure to set `completionBlock`, `outputStream`, and any callback blocks as necessary when using `-initWithCoder:` or `NSKeyedUnarchiver`. - - Operations are paused on `encodeWithCoder:`. If the operation was encoded while paused or still executing, its archived state will return `YES` for `isReady`. Otherwise, the state of an operation when encoding will remain unchanged. - - ### NSCopying Caveats - - - `-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations. - - A copy of an operation will not include the `outputStream` of the original. - - Operation copies do not include `completionBlock`, as it often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied. - */ - -@interface AFURLConnectionOperation : NSOperation - -///------------------------------- -/// @name Accessing Run Loop Modes -///------------------------------- - -/** - The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing `NSRunLoopCommonModes`. - */ -@property (nonatomic, strong) NSSet *runLoopModes; - -///----------------------------------------- -/// @name Getting URL Connection Information -///----------------------------------------- - -/** - The request used by the operation's connection. - */ -@property (readonly, nonatomic, strong) NSURLRequest *request; - -/** - The last response received by the operation's connection. - */ -@property (readonly, nonatomic, strong) NSURLResponse *response; - -/** - The error, if any, that occurred in the lifecycle of the request. - */ -@property (readonly, nonatomic, strong) NSError *error; - -///---------------------------- -/// @name Getting Response Data -///---------------------------- - -/** - The data received during the request. - */ -@property (readonly, nonatomic, strong) NSData *responseData; - -/** - The string representation of the response data. - */ -@property (readonly, nonatomic, copy) NSString *responseString; - -/** - The string encoding of the response. - - If the response does not specify a valid string encoding, `responseStringEncoding` will return `NSUTF8StringEncoding`. - */ -@property (readonly, nonatomic, assign) NSStringEncoding responseStringEncoding; - -///------------------------------- -/// @name Managing URL Credentials -///------------------------------- - -/** - Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default. - - This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`. - */ -@property (nonatomic, assign) BOOL shouldUseCredentialStorage; - -/** - The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. - - This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. - */ -@property (nonatomic, strong) NSURLCredential *credential; - -///------------------------------- -/// @name Managing Security Policy -///------------------------------- - -/** - The security policy used to evaluate server trust for secure connections. - */ -@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; - -///------------------------ -/// @name Accessing Streams -///------------------------ - -/** - The input stream used to read data to be sent during the request. - - This property acts as a proxy to the `HTTPBodyStream` property of `request`. - */ -@property (nonatomic, strong) NSInputStream *inputStream; - -/** - The output stream that is used to write data received until the request is finished. - - By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request, with the intermediary `outputStream` property set to `nil`. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`. The output stream will be scheduled in the network thread runloop upon being set. - */ -@property (nonatomic, strong) NSOutputStream *outputStream; - -///--------------------------------- -/// @name Managing Callback Queues -///--------------------------------- - -/** - The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. - */ -@property (nonatomic, strong) dispatch_queue_t completionQueue; - -/** - The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. - */ -@property (nonatomic, strong) dispatch_group_t completionGroup; - -///--------------------------------------------- -/// @name Managing Request Operation Information -///--------------------------------------------- - -/** - The user info dictionary for the receiver. - */ -@property (nonatomic, strong) NSDictionary *userInfo; - -///------------------------------------------------------ -/// @name Initializing an AFURLConnectionOperation Object -///------------------------------------------------------ - -/** - Initializes and returns a newly allocated operation object with a url connection configured with the specified url request. - - This is the designated initializer. - - @param urlRequest The request object to be used by the operation connection. - */ -- (instancetype)initWithRequest:(NSURLRequest *)urlRequest; - -///---------------------------------- -/// @name Pausing / Resuming Requests -///---------------------------------- - -/** - Pauses the execution of the request operation. - - A paused operation returns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, it will remain in an `NSOperationQueue` until it is either cancelled or resumed. Pausing a finished, cancelled, or paused operation has no effect. - */ -- (void)pause; - -/** - Whether the request operation is currently paused. - - @return `YES` if the operation is currently paused, otherwise `NO`. - */ -- (BOOL)isPaused; - -/** - Resumes the execution of the paused request operation. - - Pause/Resume behavior varies depending on the underlying implementation for the operation class. In its base implementation, resuming a paused requests restarts the original request. However, since HTTP defines a specification for how to request a specific content range, `AFHTTPRequestOperation` will resume downloading the request from where it left off, instead of restarting the original request. - */ -- (void)resume; - -///---------------------------------------------- -/// @name Configuring Backgrounding Task Behavior -///---------------------------------------------- - -/** - Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task. - - @param handler A handler to be called shortly before the application’s remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the `handler` parameter in `UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the application’s suspension momentarily while the application is notified. - */ -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS) -- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler; -#endif - -///--------------------------------- -/// @name Setting Progress Callbacks -///--------------------------------- - -/** - Sets a callback to be called when an undetermined number of bytes have been uploaded to the server. - - @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 three arguments: 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)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block; - -/** - Sets a callback to be called when an undetermined number of bytes have been downloaded from the server. - - @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 number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread. - */ -- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block; - -///------------------------------------------------- -/// @name Setting NSURLConnection Delegate Callbacks -///------------------------------------------------- - -/** - Sets a block to be executed when the connection will authenticate a challenge in order to download its request, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequestForAuthenticationChallenge:`. - - @param block A block object to be executed when the connection will authenticate a challenge in order to download its request. The block has no return type and takes two arguments: the URL connection object, and the challenge that must be authenticated. This block must invoke one of the challenge-responder methods (NSURLAuthenticationChallengeSender protocol). - - If `allowsInvalidSSLCertificate` is set to YES, `connection:willSendRequestForAuthenticationChallenge:` will attempt to have the challenge sender use credentials with invalid SSL certificates. - */ -- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block; - -/** - Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the `NSURLProtocol` subclass handling the request in order to standardize its format, as handled by the `NSURLConnectionDataDelegate` method `connection:willSendRequest:redirectResponse:`. - - @param block A block object to be executed when the request URL was changed. The block returns an `NSURLRequest` object, the URL request to redirect, and takes three arguments: the URL connection object, the the proposed redirected request, and the URL response that caused the redirect. - */ -- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block; - - -/** - Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`. - - @param block A block object to be executed to determine what response a connection will cache, if any. The block returns an `NSCachedURLResponse` object, the cached response to store in memory or `nil` to prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request. - */ -- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block; - -/// - -/** - - */ -+ (NSArray *)batchOfRequestOperations:(NSArray *)operations - progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock - completionBlock:(void (^)(NSArray *operations))completionBlock; - -@end - -///-------------------- -/// @name Notifications -///-------------------- - -/** - Posted when an operation begins executing. - */ -extern NSString * const AFNetworkingOperationDidStartNotification; - -/** - Posted when an operation finishes. - */ -extern NSString * const AFNetworkingOperationDidFinishNotification; diff --git a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.m b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.m deleted file mode 100644 index cfe609a2..00000000 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.m +++ /dev/null @@ -1,789 +0,0 @@ -// AFURLConnectionOperation.m -// -// Copyright (c) 2013-2014 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 "AFURLConnectionOperation.h" - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#import -#endif - -#if !__has_feature(objc_arc) -#error AFNetworking must be built with ARC. -// You can turn on ARC for only AFNetworking files by adding -fobjc-arc to the build phase for each of its files. -#endif - -typedef NS_ENUM(NSInteger, AFOperationState) { - AFOperationPausedState = -1, - AFOperationReadyState = 1, - AFOperationExecutingState = 2, - AFOperationFinishedState = 3, -}; - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS) -typedef UIBackgroundTaskIdentifier AFBackgroundTaskIdentifier; -#else -typedef id AFBackgroundTaskIdentifier; -#endif - -static dispatch_group_t url_request_operation_completion_group() { - static dispatch_group_t af_url_request_operation_completion_group; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_url_request_operation_completion_group = dispatch_group_create(); - }); - - return af_url_request_operation_completion_group; -} - -static dispatch_queue_t url_request_operation_completion_queue() { - static dispatch_queue_t af_url_request_operation_completion_queue; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_url_request_operation_completion_queue = dispatch_queue_create("com.alamofire.networking.operation.queue", DISPATCH_QUEUE_CONCURRENT ); - }); - - return af_url_request_operation_completion_queue; -} - -static NSString * const kAFNetworkingLockName = @"com.alamofire.networking.operation.lock"; - -NSString * const AFNetworkingOperationDidStartNotification = @"com.alamofire.networking.operation.start"; -NSString * const AFNetworkingOperationDidFinishNotification = @"com.alamofire.networking.operation.finish"; - -typedef void (^AFURLConnectionOperationProgressBlock)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected); -typedef void (^AFURLConnectionOperationAuthenticationChallengeBlock)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge); -typedef NSCachedURLResponse * (^AFURLConnectionOperationCacheResponseBlock)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse); -typedef NSURLRequest * (^AFURLConnectionOperationRedirectResponseBlock)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse); - -static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { - switch (state) { - case AFOperationReadyState: - return @"isReady"; - case AFOperationExecutingState: - return @"isExecuting"; - case AFOperationFinishedState: - return @"isFinished"; - case AFOperationPausedState: - return @"isPaused"; - default: { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunreachable-code" - return @"state"; -#pragma clang diagnostic pop - } - } -} - -static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperationState toState, BOOL isCancelled) { - switch (fromState) { - case AFOperationReadyState: - switch (toState) { - case AFOperationPausedState: - case AFOperationExecutingState: - return YES; - case AFOperationFinishedState: - return isCancelled; - default: - return NO; - } - case AFOperationExecutingState: - switch (toState) { - case AFOperationPausedState: - case AFOperationFinishedState: - return YES; - default: - return NO; - } - case AFOperationFinishedState: - return NO; - case AFOperationPausedState: - return toState == AFOperationReadyState; - default: { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunreachable-code" - switch (toState) { - case AFOperationPausedState: - case AFOperationReadyState: - case AFOperationExecutingState: - case AFOperationFinishedState: - return YES; - default: - return NO; - } - } -#pragma clang diagnostic pop - } -} - -@interface AFURLConnectionOperation () -@property (readwrite, nonatomic, assign) AFOperationState state; -@property (readwrite, nonatomic, strong) NSRecursiveLock *lock; -@property (readwrite, nonatomic, strong) NSURLConnection *connection; -@property (readwrite, nonatomic, strong) NSURLRequest *request; -@property (readwrite, nonatomic, strong) NSURLResponse *response; -@property (readwrite, nonatomic, strong) NSError *error; -@property (readwrite, nonatomic, strong) NSData *responseData; -@property (readwrite, nonatomic, copy) NSString *responseString; -@property (readwrite, nonatomic, assign) NSStringEncoding responseStringEncoding; -@property (readwrite, nonatomic, assign) long long totalBytesRead; -@property (readwrite, nonatomic, assign) AFBackgroundTaskIdentifier backgroundTaskIdentifier; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock uploadProgress; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock downloadProgress; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationAuthenticationChallengeBlock authenticationChallenge; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationCacheResponseBlock cacheResponse; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationRedirectResponseBlock redirectResponse; - -- (void)operationDidStart; -- (void)finish; -- (void)cancelConnection; -@end - -@implementation AFURLConnectionOperation -@synthesize outputStream = _outputStream; - -+ (void)networkRequestThreadEntryPoint:(id)__unused object { - @autoreleasepool { - [[NSThread currentThread] setName:@"AFNetworking"]; - - NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; - [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]; - [runLoop run]; - } -} - -+ (NSThread *)networkRequestThread { - static NSThread *_networkRequestThread = nil; - static dispatch_once_t oncePredicate; - dispatch_once(&oncePredicate, ^{ - _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil]; - [_networkRequestThread start]; - }); - - return _networkRequestThread; -} - -- (instancetype)initWithRequest:(NSURLRequest *)urlRequest { - NSParameterAssert(urlRequest); - - self = [super init]; - if (!self) { - return nil; - } - - _state = AFOperationReadyState; - - self.lock = [[NSRecursiveLock alloc] init]; - self.lock.name = kAFNetworkingLockName; - - self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes]; - - self.request = urlRequest; - - self.shouldUseCredentialStorage = YES; - - self.securityPolicy = [AFSecurityPolicy defaultPolicy]; - - return self; -} - -- (void)dealloc { - if (_outputStream) { - [_outputStream close]; - _outputStream = nil; - } - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS) - if (_backgroundTaskIdentifier) { - [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier]; - _backgroundTaskIdentifier = UIBackgroundTaskInvalid; - } -#endif -} - -#pragma mark - - -- (void)setResponseData:(NSData *)responseData { - [self.lock lock]; - if (!responseData) { - _responseData = nil; - } else { - _responseData = [NSData dataWithBytes:responseData.bytes length:responseData.length]; - } - [self.lock unlock]; -} - -- (NSString *)responseString { - [self.lock lock]; - if (!_responseString && self.response && self.responseData) { - self.responseString = [[NSString alloc] initWithData:self.responseData encoding:self.responseStringEncoding]; - } - [self.lock unlock]; - - return _responseString; -} - -- (NSStringEncoding)responseStringEncoding { - [self.lock lock]; - if (!_responseStringEncoding && self.response) { - NSStringEncoding stringEncoding = NSUTF8StringEncoding; - if (self.response.textEncodingName) { - CFStringEncoding IANAEncoding = CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)self.response.textEncodingName); - if (IANAEncoding != kCFStringEncodingInvalidId) { - stringEncoding = CFStringConvertEncodingToNSStringEncoding(IANAEncoding); - } - } - - self.responseStringEncoding = stringEncoding; - } - [self.lock unlock]; - - return _responseStringEncoding; -} - -- (NSInputStream *)inputStream { - return self.request.HTTPBodyStream; -} - -- (void)setInputStream:(NSInputStream *)inputStream { - NSMutableURLRequest *mutableRequest = [self.request mutableCopy]; - mutableRequest.HTTPBodyStream = inputStream; - self.request = mutableRequest; -} - -- (NSOutputStream *)outputStream { - if (!_outputStream) { - self.outputStream = [NSOutputStream outputStreamToMemory]; - } - - return _outputStream; -} - -- (void)setOutputStream:(NSOutputStream *)outputStream { - [self.lock lock]; - if (outputStream != _outputStream) { - if (_outputStream) { - [_outputStream close]; - } - - _outputStream = outputStream; - } - [self.lock unlock]; -} - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS) -- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler { - [self.lock lock]; - if (!self.backgroundTaskIdentifier) { - UIApplication *application = [UIApplication sharedApplication]; - __weak __typeof(self)weakSelf = self; - self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{ - __strong __typeof(weakSelf)strongSelf = weakSelf; - - if (handler) { - handler(); - } - - if (strongSelf) { - [strongSelf cancel]; - - [application endBackgroundTask:strongSelf.backgroundTaskIdentifier]; - strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid; - } - }]; - } - [self.lock unlock]; -} -#endif - -#pragma mark - - -- (void)setState:(AFOperationState)state { - if (!AFStateTransitionIsValid(self.state, state, [self isCancelled])) { - return; - } - - [self.lock lock]; - NSString *oldStateKey = AFKeyPathFromOperationState(self.state); - NSString *newStateKey = AFKeyPathFromOperationState(state); - - [self willChangeValueForKey:newStateKey]; - [self willChangeValueForKey:oldStateKey]; - _state = state; - [self didChangeValueForKey:oldStateKey]; - [self didChangeValueForKey:newStateKey]; - [self.lock unlock]; -} - -- (void)pause { - if ([self isPaused] || [self isFinished] || [self isCancelled]) { - return; - } - - [self.lock lock]; - if ([self isExecuting]) { - [self performSelector:@selector(operationDidPause) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; - - dispatch_async(dispatch_get_main_queue(), ^{ - NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - [notificationCenter postNotificationName:AFNetworkingOperationDidFinishNotification object:self]; - }); - } - - self.state = AFOperationPausedState; - [self.lock unlock]; -} - -- (void)operationDidPause { - [self.lock lock]; - [self.connection cancel]; - [self.lock unlock]; -} - -- (BOOL)isPaused { - return self.state == AFOperationPausedState; -} - -- (void)resume { - if (![self isPaused]) { - return; - } - - [self.lock lock]; - self.state = AFOperationReadyState; - - [self start]; - [self.lock unlock]; -} - -#pragma mark - - -- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block { - self.uploadProgress = block; -} - -- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block { - self.downloadProgress = block; -} - -- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block { - self.authenticationChallenge = block; -} - -- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block { - self.cacheResponse = block; -} - -- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block { - self.redirectResponse = block; -} - -#pragma mark - NSOperation - -- (void)setCompletionBlock:(void (^)(void))block { - [self.lock lock]; - if (!block) { - [super setCompletionBlock:nil]; - } else { - __weak __typeof(self)weakSelf = self; - [super setCompletionBlock:^ { - __strong __typeof(weakSelf)strongSelf = weakSelf; - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - dispatch_group_t group = strongSelf.completionGroup ?: url_request_operation_completion_group(); - dispatch_queue_t queue = strongSelf.completionQueue ?: dispatch_get_main_queue(); -#pragma clang diagnostic pop - - dispatch_group_async(group, queue, ^{ - block(); - }); - - dispatch_group_notify(group, url_request_operation_completion_queue(), ^{ - [strongSelf setCompletionBlock:nil]; - }); - }]; - } - [self.lock unlock]; -} - -- (BOOL)isReady { - return self.state == AFOperationReadyState && [super isReady]; -} - -- (BOOL)isExecuting { - return self.state == AFOperationExecutingState; -} - -- (BOOL)isFinished { - return self.state == AFOperationFinishedState; -} - -- (BOOL)isConcurrent { - return YES; -} - -- (void)start { - [self.lock lock]; - if ([self isCancelled]) { - [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; - } else if ([self isReady]) { - self.state = AFOperationExecutingState; - - [self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; - } - [self.lock unlock]; -} - -- (void)operationDidStart { - [self.lock lock]; - if (![self isCancelled]) { - self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO]; - - NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; - for (NSString *runLoopMode in self.runLoopModes) { - [self.connection scheduleInRunLoop:runLoop forMode:runLoopMode]; - [self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode]; - } - - [self.outputStream open]; - [self.connection start]; - } - [self.lock unlock]; - - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidStartNotification object:self]; - }); -} - -- (void)finish { - [self.lock lock]; - self.state = AFOperationFinishedState; - [self.lock unlock]; - - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self]; - }); -} - -- (void)cancel { - [self.lock lock]; - if (![self isFinished] && ![self isCancelled]) { - [super cancel]; - - if ([self isExecuting]) { - [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; - } - } - [self.lock unlock]; -} - -- (void)cancelConnection { - NSDictionary *userInfo = nil; - if ([self.request URL]) { - userInfo = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; - } - NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]; - - if (![self isFinished]) { - if (self.connection) { - [self.connection cancel]; - [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:error]; - } else { - // Accomodate race condition where `self.connection` has not yet been set before cancellation - self.error = error; - [self finish]; - } - } -} - -#pragma mark - - -+ (NSArray *)batchOfRequestOperations:(NSArray *)operations - progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock - completionBlock:(void (^)(NSArray *operations))completionBlock -{ - if (!operations || [operations count] == 0) { - return @[[NSBlockOperation blockOperationWithBlock:^{ - dispatch_async(dispatch_get_main_queue(), ^{ - if (completionBlock) { - completionBlock(@[]); - } - }); - }]]; - } - - __block dispatch_group_t group = dispatch_group_create(); - NSBlockOperation *batchedOperation = [NSBlockOperation blockOperationWithBlock:^{ - dispatch_group_notify(group, dispatch_get_main_queue(), ^{ - if (completionBlock) { - completionBlock(operations); - } - }); - }]; - - for (AFURLConnectionOperation *operation in operations) { - operation.completionGroup = group; - void (^originalCompletionBlock)(void) = [operation.completionBlock copy]; - __weak __typeof(operation)weakOperation = operation; - operation.completionBlock = ^{ - __strong __typeof(weakOperation)strongOperation = weakOperation; -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - dispatch_queue_t queue = strongOperation.completionQueue ?: dispatch_get_main_queue(); -#pragma clang diagnostic pop - dispatch_group_async(group, queue, ^{ - if (originalCompletionBlock) { - originalCompletionBlock(); - } - - NSUInteger numberOfFinishedOperations = [[operations indexesOfObjectsPassingTest:^BOOL(id op, NSUInteger __unused idx, BOOL __unused *stop) { - return [op isFinished]; - }] count]; - - if (progressBlock) { - progressBlock(numberOfFinishedOperations, [operations count]); - } - - dispatch_group_leave(group); - }); - }; - - dispatch_group_enter(group); - [batchedOperation addDependency:operation]; - } - - return [operations arrayByAddingObject:batchedOperation]; -} - -#pragma mark - NSObject - -- (NSString *)description { - [self.lock lock]; - NSString *description = [NSString stringWithFormat:@"<%@: %p, state: %@, cancelled: %@ request: %@, response: %@>", NSStringFromClass([self class]), self, AFKeyPathFromOperationState(self.state), ([self isCancelled] ? @"YES" : @"NO"), self.request, self.response]; - [self.lock unlock]; - return description; -} - -#pragma mark - NSURLConnectionDelegate - -- (void)connection:(NSURLConnection *)connection -willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge -{ - if (self.authenticationChallenge) { - self.authenticationChallenge(connection, challenge); - return; - } - - if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { - if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { - NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; - [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; - } else { - [[challenge sender] cancelAuthenticationChallenge:challenge]; - } - } else { - if ([challenge previousFailureCount] == 0) { - if (self.credential) { - [[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge]; - } else { - [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; - } - } else { - [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; - } - } -} - -- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection { - return self.shouldUseCredentialStorage; -} - -- (NSURLRequest *)connection:(NSURLConnection *)connection - willSendRequest:(NSURLRequest *)request - redirectResponse:(NSURLResponse *)redirectResponse -{ - if (self.redirectResponse) { - return self.redirectResponse(connection, request, redirectResponse); - } else { - return request; - } -} - -- (void)connection:(NSURLConnection __unused *)connection - didSendBodyData:(NSInteger)bytesWritten - totalBytesWritten:(NSInteger)totalBytesWritten -totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite -{ - dispatch_async(dispatch_get_main_queue(), ^{ - if (self.uploadProgress) { - self.uploadProgress((NSUInteger)bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); - } - }); -} - -- (void)connection:(NSURLConnection __unused *)connection -didReceiveResponse:(NSURLResponse *)response -{ - self.response = response; -} - -- (void)connection:(NSURLConnection __unused *)connection - didReceiveData:(NSData *)data -{ - NSUInteger length = [data length]; - while (YES) { - NSInteger totalNumberOfBytesWritten = 0; - if ([self.outputStream hasSpaceAvailable]) { - const uint8_t *dataBuffer = (uint8_t *)[data bytes]; - - NSInteger numberOfBytesWritten = 0; - while (totalNumberOfBytesWritten < (NSInteger)length) { - numberOfBytesWritten = [self.outputStream write:&dataBuffer[(NSUInteger)totalNumberOfBytesWritten] maxLength:(length - (NSUInteger)totalNumberOfBytesWritten)]; - if (numberOfBytesWritten == -1) { - break; - } - - totalNumberOfBytesWritten += numberOfBytesWritten; - } - - break; - } - - if (self.outputStream.streamError) { - [self.connection cancel]; - [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:self.outputStream.streamError]; - return; - } - } - - dispatch_async(dispatch_get_main_queue(), ^{ - self.totalBytesRead += (long long)length; - - if (self.downloadProgress) { - self.downloadProgress(length, self.totalBytesRead, self.response.expectedContentLength); - } - }); -} - -- (void)connectionDidFinishLoading:(NSURLConnection __unused *)connection { - self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; - - [self.outputStream close]; - if (self.responseData) { - self.outputStream = nil; - } - - self.connection = nil; - - [self finish]; -} - -- (void)connection:(NSURLConnection __unused *)connection - didFailWithError:(NSError *)error -{ - self.error = error; - - [self.outputStream close]; - if (self.responseData) { - self.outputStream = nil; - } - - self.connection = nil; - - [self finish]; -} - -- (NSCachedURLResponse *)connection:(NSURLConnection *)connection - willCacheResponse:(NSCachedURLResponse *)cachedResponse -{ - if (self.cacheResponse) { - return self.cacheResponse(connection, cachedResponse); - } else { - if ([self isCancelled]) { - return nil; - } - - return cachedResponse; - } -} - -#pragma mark - NSSecureCoding - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (id)initWithCoder:(NSCoder *)decoder { - NSURLRequest *request = [decoder decodeObjectOfClass:[NSURLRequest class] forKey:NSStringFromSelector(@selector(request))]; - - self = [self initWithRequest:request]; - if (!self) { - return nil; - } - - self.state = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(state))] integerValue]; - self.response = [decoder decodeObjectOfClass:[NSHTTPURLResponse class] forKey:NSStringFromSelector(@selector(response))]; - self.error = [decoder decodeObjectOfClass:[NSError class] forKey:NSStringFromSelector(@selector(error))]; - self.responseData = [decoder decodeObjectOfClass:[NSData class] forKey:NSStringFromSelector(@selector(responseData))]; - self.totalBytesRead = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(totalBytesRead))] longLongValue]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [self pause]; - - [coder encodeObject:self.request forKey:NSStringFromSelector(@selector(request))]; - - switch (self.state) { - case AFOperationExecutingState: - case AFOperationPausedState: - [coder encodeInteger:AFOperationReadyState forKey:NSStringFromSelector(@selector(state))]; - break; - default: - [coder encodeInteger:self.state forKey:NSStringFromSelector(@selector(state))]; - break; - } - - [coder encodeObject:self.response forKey:NSStringFromSelector(@selector(response))]; - [coder encodeObject:self.error forKey:NSStringFromSelector(@selector(error))]; - [coder encodeObject:self.responseData forKey:NSStringFromSelector(@selector(responseData))]; - [coder encodeInt64:self.totalBytesRead forKey:NSStringFromSelector(@selector(totalBytesRead))]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFURLConnectionOperation *operation = [(AFURLConnectionOperation *)[[self class] allocWithZone:zone] initWithRequest:self.request]; - - operation.uploadProgress = self.uploadProgress; - operation.downloadProgress = self.downloadProgress; - operation.authenticationChallenge = self.authenticationChallenge; - operation.cacheResponse = self.cacheResponse; - operation.redirectResponse = self.redirectResponse; - operation.completionQueue = self.completionQueue; - operation.completionGroup = self.completionGroup; - - return operation; -} - -@end diff --git a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h index aed45498..c31c5231 100644 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h +++ b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h @@ -1,6 +1,5 @@ -// AFSerialization.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// AFURLRequestSerialization.h +// Copyright (c) 2011–2015 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 @@ -8,10 +7,10 @@ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,10 +20,16 @@ // THE SOFTWARE. #import -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#import + +#if TARGET_OS_IOS || TARGET_OS_TV #import +#elif TARGET_OS_WATCH +#import #endif +NS_ASSUME_NONNULL_BEGIN + /** 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. @@ -41,9 +46,9 @@ @return A serialized request. */ -- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request - withParameters:(id)parameters - error:(NSError * __autoreleasing *)error; +- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(nullable id)parameters + error:(NSError * _Nullable __autoreleasing *)error; @end @@ -72,42 +77,42 @@ typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) { /** 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; @@ -117,7 +122,12 @@ typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) { ///--------------------------------------- /** - Default HTTP header field values to be applied to serialized requests. + 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; @@ -132,17 +142,17 @@ typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) { @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:(NSString *)value +- (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` */ -- (NSString *)valueForHTTPHeaderField:(NSString *)field; +- (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. @@ -187,7 +197,7 @@ forHTTPHeaderField:(NSString *)field; @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:(NSString * (^)(NSURLRequest *request, NSDictionary *parameters, NSError * __autoreleasing *error))block; +- (void)setQueryStringSerializationWithBlock:(nullable NSString * (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block; ///------------------------------- /// @name Creating Request Objects @@ -208,14 +218,14 @@ forHTTPHeaderField:(NSString *)field; @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 occured while constructing the request. + @param error The error that occurred while constructing the request. @return An `NSMutableURLRequest` object. */ - (NSMutableURLRequest *)requestWithMethod:(NSString *)method URLString:(NSString *)URLString - parameters:(id)parameters - error:(NSError * __autoreleasing *)error; + parameters:(nullable id)parameters + error:(NSError * _Nullable __autoreleasing *)error; /** @deprecated This method has been deprecated. Use -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error: instead. @@ -234,30 +244,30 @@ forHTTPHeaderField:(NSString *)field; @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 occured while constructing the request. + @param error The error that occurred while constructing the request. @return An `NSMutableURLRequest` object */ - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method URLString:(NSString *)URLString - parameters:(NSDictionary *)parameters - constructingBodyWithBlock:(void (^)(id formData))block - error:(NSError * __autoreleasing *)error; + 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. + + @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:(void (^)(NSError *error))handler; + completionHandler:(nullable void (^)(NSError * _Nullable error))handler; @end @@ -281,7 +291,7 @@ forHTTPHeaderField:(NSString *)field; */ - (BOOL)appendPartWithFileURL:(NSURL *)fileURL name:(NSString *)name - error:(NSError * __autoreleasing *)error; + 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. @@ -298,7 +308,7 @@ forHTTPHeaderField:(NSString *)field; name:(NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mimeType - error:(NSError * __autoreleasing *)error; + 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. @@ -309,7 +319,7 @@ forHTTPHeaderField:(NSString *)field; @param length The length of the specified input stream in bytes. @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. */ -- (void)appendPartWithInputStream:(NSInputStream *)inputStream +- (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream name:(NSString *)name fileName:(NSString *)fileName length:(int64_t)length @@ -345,7 +355,7 @@ forHTTPHeaderField:(NSString *)field; @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:(NSDictionary *)headers +- (void)appendPartWithHeaders:(nullable NSDictionary *)headers body:(NSData *)body; /** @@ -404,7 +414,7 @@ forHTTPHeaderField:(NSString *)field; @param format The property list format. @param writeOptions The property list write options. - + @warning The `writeOptions` property is currently unused. */ + (instancetype)serializerWithFormat:(NSPropertyListFormat)format @@ -430,7 +440,7 @@ forHTTPHeaderField:(NSString *)field; `AFURLRequestSerializationErrorDomain` AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. */ -extern NSString * const AFURLRequestSerializationErrorDomain; +FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain; /** ## User info dictionary keys @@ -444,7 +454,7 @@ extern NSString * const AFURLRequestSerializationErrorDomain; `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`. */ -extern NSString * const AFNetworkingOperationFailingURLRequestErrorKey; +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey; /** ## Throttling Bandwidth for HTTP Request Input Streams @@ -459,5 +469,7 @@ extern NSString * const AFNetworkingOperationFailingURLRequestErrorKey; `kAFUploadStream3GSuggestedDelay` Duration of delay each time a packet is read. Equal to 0.2 seconds. */ -extern NSUInteger const kAFUploadStream3GSuggestedPacketSize; -extern NSTimeInterval const kAFUploadStream3GSuggestedDelay; +FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize; +FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay; + +NS_ASSUME_NONNULL_END diff --git a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m index a56e8542..26dbc693 100644 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m +++ b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m @@ -1,6 +1,5 @@ -// AFSerialization.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// AFURLRequestSerialization.m +// Copyright (c) 2011–2015 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 @@ -8,10 +7,10 @@ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -22,7 +21,7 @@ #import "AFURLRequestSerialization.h" -#if __IPHONE_OS_VERSION_MIN_REQUIRED +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV #import #else #import @@ -31,7 +30,7 @@ NSString * const AFURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request"; NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response"; -typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error); +typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id parameters, NSError *__autoreleasing *error); static NSString * AFBase64EncodedStringFromString(NSString *string) { NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]]; @@ -62,16 +61,51 @@ return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding]; } -static NSString * const kAFCharactersToBeEscapedInQueryString = @":/?&=;+!@#$()',*"; +/** + 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: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" -static NSString * AFPercentEscapedQueryStringKeyFromStringWithEncoding(NSString *string, NSStringEncoding encoding) { - static NSString * const kAFCharactersToLeaveUnescapedInQueryStringPairKey = @"[]."; + 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. + */ +static NSString * AFPercentEscapedStringFromString(NSString *string) { + static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4 + static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;="; - return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, (__bridge CFStringRef)kAFCharactersToLeaveUnescapedInQueryStringPairKey, (__bridge CFStringRef)kAFCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding)); -} + 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; -static NSString * AFPercentEscapedQueryStringValueFromStringWithEncoding(NSString *string, NSStringEncoding encoding) { - return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)kAFCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding)); + 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 - @@ -80,14 +114,14 @@ @interface AFQueryStringPair : NSObject @property (readwrite, nonatomic, strong) id field; @property (readwrite, nonatomic, strong) id value; -- (id)initWithField:(id)field value:(id)value; +- (instancetype)initWithField:(id)field value:(id)value; -- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding; +- (NSString *)URLEncodedStringValue; @end @implementation AFQueryStringPair -- (id)initWithField:(id)field value:(id)value { +- (instancetype)initWithField:(id)field value:(id)value { self = [super init]; if (!self) { return nil; @@ -99,11 +133,11 @@ - (id)initWithField:(id)field value:(id)value { return self; } -- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding { +- (NSString *)URLEncodedStringValue { if (!self.value || [self.value isEqual:[NSNull null]]) { - return AFPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding); + return AFPercentEscapedStringFromString([self.field description]); } else { - return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding), AFPercentEscapedQueryStringValueFromStringWithEncoding([self.value description], stringEncoding)]; + return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedStringFromString([self.field description]), AFPercentEscapedStringFromString([self.value description])]; } } @@ -111,13 +145,13 @@ - (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding #pragma mark - -extern NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary); -extern NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value); +FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary); +FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value); -static NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding stringEncoding) { +static NSString * AFQueryStringFromParameters(NSDictionary *parameters) { NSMutableArray *mutablePairs = [NSMutableArray array]; for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { - [mutablePairs addObject:[pair URLEncodedStringValueWithEncoding:stringEncoding]]; + [mutablePairs addObject:[pair URLEncodedStringValue]]; } return [mutablePairs componentsJoinedByString:@"&"]; @@ -136,7 +170,7 @@ - (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding 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 objectForKey:nestedKey]; + id nestedValue = dictionary[nestedKey]; if (nestedValue) { [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)]; } @@ -154,7 +188,7 @@ - (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding } else { [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]]; } - + return mutableQueryStringComponents; } @@ -216,11 +250,14 @@ - (instancetype)init { NSString *userAgent = nil; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#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] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; + 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] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]]; + 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) { @@ -256,6 +293,47 @@ - (void)dealloc { #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]; } @@ -292,7 +370,7 @@ - (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializat self.queryStringSerialization = nil; } -- (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, NSDictionary *, NSError *__autoreleasing *))block { +- (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, id, NSError *__autoreleasing *))block { self.queryStringSerialization = block; } @@ -380,10 +458,7 @@ - (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request writingStreamContentsToFile:(NSURL *)fileURL completionHandler:(void (^)(NSError *error))handler { - if (!request.HTTPBodyStream) { - return [request mutableCopy]; - } - + NSParameterAssert(request.HTTPBodyStream); NSParameterAssert([fileURL isFileURL]); NSInputStream *inputStream = request.HTTPBodyStream; @@ -449,8 +524,8 @@ - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request } }]; + NSString *query = nil; if (parameters) { - NSString *query = nil; if (self.queryStringSerialization) { NSError *serializationError; query = self.queryStringSerialization(request, parameters, &serializationError); @@ -465,19 +540,25 @@ - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request } else { switch (self.queryStringSerializationStyle) { case AFHTTPRequestQueryStringDefaultStyle: - query = AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding); + query = AFQueryStringFromParameters(parameters); break; } } + } - if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + if (query) { mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]]; - } else { - if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { - [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; - } - [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]]; } + } 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; @@ -485,6 +566,14 @@ - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request #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 @@ -505,14 +594,14 @@ + (BOOL)supportsSecureCoding { return YES; } -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { self = [self init]; if (!self) { return nil; } self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy]; - self.queryStringSerializationStyle = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue]; + self.queryStringSerializationStyle = (AFHTTPRequestQueryStringSerializationStyle)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue]; return self; } @@ -524,12 +613,12 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (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; } @@ -598,7 +687,7 @@ @interface AFMultipartBodyStream : NSInputStream @property (readonly, nonatomic, assign) unsigned long long contentLength; @property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty; -- (id)initWithStringEncoding:(NSStringEncoding)encoding; +- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding; - (void)setInitialAndFinalBoundaries; - (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart; @end @@ -614,8 +703,8 @@ @interface AFStreamingMultipartFormData () @implementation AFStreamingMultipartFormData -- (id)initWithURLRequest:(NSMutableURLRequest *)urlRequest - stringEncoding:(NSStringEncoding)encoding +- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest + stringEncoding:(NSStringEncoding)encoding { self = [super init]; if (!self) { @@ -674,17 +763,17 @@ - (BOOL)appendPartWithFileURL:(NSURL *)fileURL 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 objectForKey:NSFileSize] unsignedLongLongValue]; + bodyPart.bodyContentLength = [fileAttributes[NSFileSize] unsignedLongLongValue]; [self.bodyStream appendHTTPBodyPart:bodyPart]; return YES; @@ -807,7 +896,7 @@ @implementation AFMultipartBodyStream @synthesize streamError; #pragma clang diagnostic pop -- (id)initWithStringEncoding:(NSStringEncoding)encoding { +- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding { self = [super init]; if (!self) { return nil; @@ -827,7 +916,7 @@ - (void)setInitialAndFinalBoundaries { bodyPart.hasFinalBoundary = NO; } - [[self.HTTPBodyParts objectAtIndex:0] setHasInitialBoundary:YES]; + [[self.HTTPBodyParts firstObject] setHasInitialBoundary:YES]; [[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES]; } } @@ -950,7 +1039,7 @@ - (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags #pragma mark - NSCopying --(id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding]; for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { @@ -987,7 +1076,7 @@ - (NSInteger)readData:(NSData *)data @implementation AFHTTPBodyPart -- (id)init { +- (instancetype)init { self = [super init]; if (!self) { return nil; @@ -1165,15 +1254,15 @@ - (BOOL)transitionToNextPhase { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (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; } @@ -1214,7 +1303,7 @@ - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request [mutableRequest setValue:value forHTTPHeaderField:field]; } }]; - + if (parameters) { if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; @@ -1228,7 +1317,7 @@ - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request #pragma mark - NSSecureCoding -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; @@ -1247,7 +1336,7 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFJSONRequestSerializer *serializer = [super copyWithZone:zone]; serializer.writingOptions = self.writingOptions; @@ -1307,13 +1396,13 @@ - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request #pragma mark - NSSecureCoding -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; } - self.format = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; + 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; @@ -1328,7 +1417,7 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone]; serializer.format = self.format; serializer.writeOptions = self.writeOptions; diff --git a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h index 030e8fae..f6933bec 100644 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h +++ b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h @@ -1,6 +1,5 @@ -// AFSerialization.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// AFURLResponseSerialization.h +// Copyright (c) 2011–2015 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 @@ -8,10 +7,10 @@ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,6 +22,8 @@ #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. @@ -39,9 +40,9 @@ @return The object decoded from the specified response data. */ -- (id)responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error; +- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response + data:(nullable NSData *)data + error:(NSError * _Nullable __autoreleasing *)error; @end @@ -54,10 +55,10 @@ */ @interface AFHTTPResponseSerializer : NSObject -- (instancetype) init; +- (instancetype)init; /** - The string encoding used to serialize parameters. + 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; @@ -75,12 +76,12 @@ See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html */ -@property (nonatomic, copy) NSIndexSet *acceptableStatusCodes; +@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) NSSet *acceptableContentTypes; +@property (nonatomic, copy, nullable) NSSet *acceptableContentTypes; /** Validates the specified response and data. @@ -93,9 +94,9 @@ @return `YES` if the response is valid, otherwise `NO`. */ -- (BOOL)validateResponse:(NSHTTPURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error; +- (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response + data:(nullable NSData *)data + error:(NSError * _Nullable __autoreleasing *)error; @end @@ -113,7 +114,7 @@ */ @interface AFJSONResponseSerializer : AFHTTPResponseSerializer -- (instancetype) init; +- (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. @@ -162,7 +163,7 @@ */ @interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer -- (instancetype) init; +- (instancetype)init; /** Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. @@ -191,7 +192,7 @@ */ @interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer -- (instancetype) init; +- (instancetype)init; /** The property list format. Possible values are described in "NSPropertyListFormat". @@ -234,7 +235,7 @@ */ @interface AFImageResponseSerializer : AFHTTPResponseSerializer -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#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. */ @@ -285,7 +286,7 @@ `AFURLResponseSerializationErrorDomain` AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. */ -extern NSString * const AFURLResponseSerializationErrorDomain; +FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain; /** ## User info dictionary keys @@ -299,12 +300,12 @@ extern NSString * const AFURLResponseSerializationErrorDomain; `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`. */ -extern NSString * const AFNetworkingOperationFailingURLResponseErrorKey; - -extern NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey; +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey; +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey; +NS_ASSUME_NONNULL_END diff --git a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m index 083d30c2..cde847d9 100644 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m +++ b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m @@ -1,6 +1,5 @@ -// AFSerialization.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// AFURLResponseSerialization.m +// Copyright (c) 2011–2015 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 @@ -8,10 +7,10 @@ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -22,8 +21,12 @@ #import "AFURLResponseSerialization.h" -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#import + +#if TARGET_OS_IOS #import +#elif TARGET_OS_WATCH +#import #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) #import #endif @@ -68,11 +71,11 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO } else if ([JSONObject isKindOfClass:[NSDictionary class]]) { NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject]; for (id key in [(NSDictionary *)JSONObject allKeys]) { - id value = [(NSDictionary *)JSONObject objectForKey:key]; + 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 setObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions) forKey:key]; + mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions); } } @@ -170,7 +173,7 @@ + (BOOL)supportsSecureCoding { return YES; } -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { self = [self init]; if (!self) { return nil; @@ -189,7 +192,7 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone]; serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone]; @@ -276,17 +279,17 @@ - (id)responseObjectForResponse:(NSURLResponse *)response if (self.removesKeysWithNullValues && responseObject) { responseObject = AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions); } - + if (error) { *error = AFErrorWithUnderlyingError(serializationError, *error); } - + return responseObject; } #pragma mark - NSSecureCoding -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; @@ -307,7 +310,7 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; serializer.readingOptions = self.readingOptions; serializer.removesKeysWithNullValues = self.removesKeysWithNullValues; @@ -407,7 +410,7 @@ - (id)responseObjectForResponse:(NSURLResponse *)response #pragma mark - NSSecureCoding -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; @@ -426,7 +429,7 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFXMLDocumentResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; serializer.options = self.options; @@ -494,13 +497,13 @@ - (id)responseObjectForResponse:(NSURLResponse *)response #pragma mark - NSSecureCoding -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; } - self.format = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; + 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; @@ -515,7 +518,7 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; serializer.format = self.format; serializer.readOptions = self.readOptions; @@ -527,12 +530,39 @@ - (id)copyWithZone:(NSZone *)zone { #pragma mark - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_TV #import +#import -static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) { - UIImage *image = [[UIImage alloc] initWithData:data]; +@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]; } @@ -549,10 +579,11 @@ - (id)copyWithZone:(NSZone *)zone { } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) { imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); - // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so if so, fall back to AFImageWithDataAtScale 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; @@ -584,7 +615,8 @@ - (id)copyWithZone:(NSZone *)zone { return image; } - size_t bytesPerRow = 0; // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate + // 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); @@ -622,7 +654,7 @@ - (id)copyWithZone:(NSZone *)zone { CGImageRelease(inflatedImageRef); CGImageRelease(imageRef); - + return inflatedImage; } #endif @@ -638,9 +670,12 @@ - (instancetype)init { self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil]; -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS self.imageScale = [[UIScreen mainScreen] scale]; self.automaticallyInflatesResponseImage = YES; +#elif TARGET_OS_WATCH + self.imageScale = [[WKInterfaceDevice currentDevice] screenScale]; + self.automaticallyInflatesResponseImage = YES; #endif return self; @@ -658,13 +693,13 @@ - (id)responseObjectForResponse:(NSURLResponse *)response } } -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_TV if (self.automaticallyInflatesResponseImage) { return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale); } else { return AFImageWithDataAtScale(data, self.imageScale); } -#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) +#elif !TARGET_OS_WATCH // 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])]; @@ -678,13 +713,13 @@ - (id)responseObjectForResponse:(NSURLResponse *)response #pragma mark - NSSecureCoding -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; } -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_TV NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))]; #if CGFLOAT_IS_DOUBLE self.imageScale = [imageScale doubleValue]; @@ -701,7 +736,7 @@ - (id)initWithCoder:(NSCoder *)decoder { - (void)encodeWithCoder:(NSCoder *)coder { [super encodeWithCoder:coder]; -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_TV [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))]; [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; #endif @@ -709,10 +744,10 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_TV serializer.imageScale = self.imageScale; serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage; #endif @@ -758,13 +793,13 @@ - (id)responseObjectForResponse:(NSURLResponse *)response return responseObject; } } - + return [super responseObjectForResponse:response data:data error:error]; } #pragma mark - NSSecureCoding -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; @@ -783,7 +818,7 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; serializer.responseSerializers = self.responseSerializers; diff --git a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLSessionManager.h b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLSessionManager.h index f475773d..b99f9d09 100644 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLSessionManager.h +++ b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLSessionManager.h @@ -1,6 +1,5 @@ // AFURLSessionManager.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2015 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 @@ -20,12 +19,23 @@ // 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 + +#ifndef NS_DESIGNATED_INITIALIZER +#if __has_attribute(objc_designated_initializer) +#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) +#else +#define NS_DESIGNATED_INITIALIZER +#endif +#endif /** `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. @@ -82,7 +92,7 @@ @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. */ -#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) +NS_ASSUME_NONNULL_BEGIN @interface AFURLSessionManager : NSObject @@ -108,10 +118,11 @@ ///------------------------------- /** - The security policy used by created request operations to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. + 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 ///-------------------------------------- @@ -120,6 +131,7 @@ The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default. */ @property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; +#endif ///---------------------------- /// @name Getting Session Tasks @@ -152,12 +164,20 @@ /** The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. */ -@property (nonatomic, strong) dispatch_queue_t completionQueue; +#if OS_OBJECT_HAVE_OBJC_SUPPORT +@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; +#else +@property (nonatomic, assign, nullable) dispatch_queue_t completionQueue; +#endif /** The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. */ -@property (nonatomic, strong) dispatch_group_t completionGroup; +#if OS_OBJECT_HAVE_OBJC_SUPPORT +@property (nonatomic, strong, nullable) dispatch_group_t completionGroup; +#else +@property (nonatomic, assign, nullable) dispatch_group_t completionGroup; +#endif ///--------------------------------- /// @name Working Around System Bugs @@ -183,7 +203,7 @@ @return A manager for a newly-created session. */ -- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration; +- (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; /** Invalidates the managed session, optionally canceling pending tasks. @@ -203,7 +223,7 @@ @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:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler; + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; ///--------------------------- /// @name Running Upload Tasks @@ -221,8 +241,8 @@ */ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL - progress:(NSProgress * __autoreleasing *)progress - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler; + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; /** Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body. @@ -233,9 +253,9 @@ @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:(NSData *)bodyData - progress:(NSProgress * __autoreleasing *)progress - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler; + fromData:(nullable NSData *)bodyData + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; /** Creates an `NSURLSessionUploadTask` with the specified streaming request. @@ -245,8 +265,8 @@ @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:(NSProgress * __autoreleasing *)progress - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler; + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; ///----------------------------- /// @name Running Download Tasks @@ -263,9 +283,9 @@ @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:(NSProgress * __autoreleasing *)progress - destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination - completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler; + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + 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. @@ -276,14 +296,23 @@ @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. */ - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData - progress:(NSProgress * __autoreleasing *)progress - destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination - completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler; + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + 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 response download progress of the specified task. + + @param dataTask The session data task. Must not be `nil`. + + @return An `NSProgress` object reporting the response download progress of a task, or `nil` if the progress is unavailable. + */ +- (nullable NSProgress *)progressForDataTask:(NSURLSessionDataTask *)dataTask; + /** Returns the upload progress of the specified task. @@ -291,7 +320,7 @@ @return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable. */ -- (NSProgress *)uploadProgressForTask:(NSURLSessionUploadTask *)uploadTask; +- (nullable NSProgress *)uploadProgressForTask:(NSURLSessionUploadTask *)uploadTask; /** Returns the download progress of the specified task. @@ -300,7 +329,7 @@ @return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable. */ -- (NSProgress *)downloadProgressForTask:(NSURLSessionDownloadTask *)downloadTask; +- (nullable NSProgress *)downloadProgressForTask:(NSURLSessionDownloadTask *)downloadTask; ///----------------------------------------- /// @name Setting Session Delegate Callbacks @@ -311,14 +340,14 @@ @param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation. */ -- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block; +- (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:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block; +- (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; ///-------------------------------------- /// @name Setting Task Delegate Callbacks @@ -329,35 +358,35 @@ @param block A block object to be executed when a task requires a new request body stream. */ -- (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block; +- (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:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block; +- (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:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block; +- (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:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block; +- (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:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block; +- (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError * _Nullable error))block; ///------------------------------------------- /// @name Setting Data Task Delegate Callbacks @@ -368,35 +397,35 @@ @param block A block object to be executed when a data task has received a response. The block returns the disposition of the session response, and takes three arguments: the session, the data task, and the received response. */ -- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block; +- (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:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block; +- (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:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block; +- (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:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block; +- (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:(void (^)(NSURLSession *session))block; +- (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block; ///----------------------------------------------- /// @name Setting Download Task Delegate Callbacks @@ -407,26 +436,24 @@ @param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error. */ -- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block; +- (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block; /** Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`. @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes five arguments: the session, the download task, the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the session manager operation queue. */ -- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block; +- (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:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block; +- (void)setDownloadTaskDidResumeBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block; @end -#endif - ///-------------------- /// @name Notifications ///-------------------- @@ -436,96 +463,98 @@ @deprecated Use `AFNetworkingTaskDidResumeNotification` instead. */ -extern NSString * const AFNetworkingTaskDidStartNotification DEPRECATED_ATTRIBUTE; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidStartNotification DEPRECATED_ATTRIBUTE; /** Posted when a task resumes. */ -extern NSString * const AFNetworkingTaskDidResumeNotification; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification; /** Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. @deprecated Use `AFNetworkingTaskDidCompleteNotification` instead. */ -extern NSString * const AFNetworkingTaskDidFinishNotification DEPRECATED_ATTRIBUTE; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidFinishNotification DEPRECATED_ATTRIBUTE; /** Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. */ -extern NSString * const AFNetworkingTaskDidCompleteNotification; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification; /** Posted when a task suspends its execution. */ -extern NSString * const AFNetworkingTaskDidSuspendNotification; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidSuspendNotification; /** Posted when a session is invalidated. */ -extern NSString * const AFURLSessionDidInvalidateNotification; +FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification; /** Posted when a session download task encountered an error when moving the temporary download file to a specified destination. */ -extern NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification; +FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification; /** The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if response data exists for the task. @deprecated Use `AFNetworkingTaskDidCompleteResponseDataKey` instead. */ -extern NSString * const AFNetworkingTaskDidFinishResponseDataKey DEPRECATED_ATTRIBUTE; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidFinishResponseDataKey DEPRECATED_ATTRIBUTE; /** The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if response data exists for the task. */ -extern NSString * const AFNetworkingTaskDidCompleteResponseDataKey; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey; /** The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the response was serialized. @deprecated Use `AFNetworkingTaskDidCompleteSerializedResponseKey` instead. */ -extern NSString * const AFNetworkingTaskDidFinishSerializedResponseKey DEPRECATED_ATTRIBUTE; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidFinishSerializedResponseKey DEPRECATED_ATTRIBUTE; /** The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the response was serialized. */ -extern NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey; /** The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the task has an associated response serializer. @deprecated Use `AFNetworkingTaskDidCompleteResponseSerializerKey` instead. */ -extern NSString * const AFNetworkingTaskDidFinishResponseSerializerKey DEPRECATED_ATTRIBUTE; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidFinishResponseSerializerKey DEPRECATED_ATTRIBUTE; /** The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the task has an associated response serializer. */ -extern NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey; /** The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an the response data has been stored directly to disk. @deprecated Use `AFNetworkingTaskDidCompleteAssetPathKey` instead. */ -extern NSString * const AFNetworkingTaskDidFinishAssetPathKey DEPRECATED_ATTRIBUTE; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidFinishAssetPathKey DEPRECATED_ATTRIBUTE; /** The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an the response data has been stored directly to disk. */ -extern NSString * const AFNetworkingTaskDidCompleteAssetPathKey; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey; /** Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an error exists. @deprecated Use `AFNetworkingTaskDidCompleteErrorKey` instead. */ -extern NSString * const AFNetworkingTaskDidFinishErrorKey DEPRECATED_ATTRIBUTE; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidFinishErrorKey DEPRECATED_ATTRIBUTE; /** Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an error exists. */ -extern NSString * const AFNetworkingTaskDidCompleteErrorKey; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey; + +NS_ASSUME_NONNULL_END diff --git a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m index d53e6ec2..b91d00f7 100644 --- a/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m +++ b/OHHTTPStubs/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m @@ -1,6 +1,5 @@ // AFURLSessionManager.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2015 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 @@ -8,10 +7,10 @@ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,8 +22,6 @@ #import "AFURLSessionManager.h" #import -#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) - static dispatch_queue_t url_session_manager_creation_queue() { static dispatch_queue_t af_url_session_manager_creation_queue; static dispatch_once_t onceToken; @@ -155,10 +152,18 @@ - (void)URLSession:(__unused NSURLSession *)session __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 (self.mutableData) { - userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = [NSData dataWithData:self.mutableData]; + } else if (data) { + userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data; } if (error) { @@ -176,7 +181,7 @@ - (void)URLSession:(__unused NSURLSession *)session } else { dispatch_async(url_session_manager_processing_queue(), ^{ NSError *serializationError = nil; - responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:[NSData dataWithData:self.mutableData] error:&serializationError]; + responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError]; if (self.downloadFileURL) { responseObject = self.downloadFileURL; @@ -194,7 +199,7 @@ - (void)URLSession:(__unused NSURLSession *)session if (self.completionHandler) { self.completionHandler(task.response, responseObject, serializationError); } - + dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo]; }); @@ -210,6 +215,12 @@ - (void)URLSession:(__unused NSURLSession *)session dataTask:(__unused NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { + NSUInteger length = data.length; + long long expectedLength = dataTask.response.expectedContentLength; + if(expectedLength != -1) { + self.progress.totalUnitCount = expectedLength; + self.progress.completedUnitCount += length; + } [self.mutableData appendData:data]; } @@ -256,58 +267,129 @@ - (void)URLSession:(__unused NSURLSession *)session #pragma mark - -/* - A workaround for issues related to key-value observing the `state` of an `NSURLSessionTask`. - - See https://github.com/AFNetworking/AFNetworking/issues/1477 +/** + * 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 class, SEL originalSelector, SEL swizzledSelector) { - Method originalMethod = class_getInstanceMethod(class, originalSelector); - Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector); - if (class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))) { - class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); - } else { - method_exchangeImplementations(originalMethod, swizzledMethod); - } +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 NSURLSessionTask (_AFStateObserving) +@interface _AFURLSessionTaskSwizzling : NSObject + @end -@implementation NSURLSessionTask (_AFStateObserving) +@implementation _AFURLSessionTaskSwizzling + (void)load { - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_swizzleSelector([self class], @selector(resume), @selector(af_resume)); - af_swizzleSelector([self class], @selector(suspend), @selector(af_suspend)); - }); + /** + 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]; + } } -#pragma mark - ++ (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 { - NSURLSessionTaskState state = self.state; + 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 { - NSURLSessionTaskState state = self.state; + 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 - @@ -317,6 +399,7 @@ @interface AFURLSessionManager () @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; @@ -362,22 +445,24 @@ - (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)config 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 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]; } @@ -393,11 +478,16 @@ - (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 isKindOfClass:[NSURLSessionTask class]]) { - AFURLSessionManager *manager = [self delegateForTask:task].manager; - if ([manager isEqual:self]) { + if ([task respondsToSelector:@selector(taskDescription)]) { + if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) { dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidResumeNotification object:task]; }); @@ -407,9 +497,8 @@ - (void)taskDidResume:(NSNotification *)notification { - (void)taskDidSuspend:(NSNotification *)notification { NSURLSessionTask *task = notification.object; - if ([task isKindOfClass:[NSURLSessionTask class]]) { - AFURLSessionManager *manager = [self delegateForTask:task].manager; - if ([manager isEqual:self]) { + if ([task respondsToSelector:@selector(taskDescription)]) { + if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) { dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidSuspendNotification object:task]; }); @@ -448,6 +537,7 @@ - (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask delegate.manager = self; delegate.completionHandler = completionHandler; + dataTask.taskDescription = self.taskDescriptionForSessionTasks; [self setDelegate:delegate forTask:dataTask]; } @@ -463,11 +553,16 @@ - (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask if(totalUnitCount == NSURLSessionTransferSizeUnknown) { NSString *contentLength = [uploadTask.originalRequest valueForHTTPHeaderField:@"Content-Length"]; if(contentLength) { - totalUnitCount = (int64_t) [contentLength longLongValue]; + totalUnitCount = (int64_t)[contentLength longLongValue]; } } - delegate.progress = [NSProgress progressWithTotalUnitCount:totalUnitCount]; + if (delegate.progress) { + delegate.progress.totalUnitCount = totalUnitCount; + } else { + delegate.progress = [NSProgress progressWithTotalUnitCount:totalUnitCount]; + } + delegate.progress.pausingHandler = ^{ [uploadTask suspend]; }; @@ -479,6 +574,8 @@ - (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask *progress = delegate.progress; } + uploadTask.taskDescription = self.taskDescriptionForSessionTasks; + [self setDelegate:delegate forTask:uploadTask]; } @@ -501,6 +598,8 @@ - (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask *progress = delegate.progress; } + downloadTask.taskDescription = self.taskDescriptionForSessionTasks; + [self setDelegate:delegate forTask:downloadTask]; } @@ -678,6 +777,9 @@ - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData } #pragma mark - +- (NSProgress *)progressForDataTask:(NSURLSessionDataTask *)dataTask { + return [[self delegateForTask:dataTask] progress]; +} - (NSProgress *)uploadProgressForTask:(NSURLSessionUploadTask *)uploadTask { return [[self delegateForTask:uploadTask] progress]; @@ -871,7 +973,7 @@ - (void)URLSession:(NSURLSession *)session 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)]) { @@ -889,7 +991,7 @@ - (void)URLSession:(NSURLSession *)session totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { - + int64_t totalUnitCount = totalBytesExpectedToSend; if(totalUnitCount == NSURLSessionTransferSizeUnknown) { NSString *contentLength = [task.originalRequest valueForHTTPHeaderField:@"Content-Length"]; @@ -897,7 +999,7 @@ - (void)URLSession:(NSURLSession *)session totalUnitCount = (int64_t) [contentLength longLongValue]; } } - + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; [delegate URLSession:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalUnitCount]; @@ -962,6 +1064,8 @@ - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { + + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; [delegate URLSession:session dataTask:dataTask didReceiveData:data]; @@ -1014,7 +1118,7 @@ - (void)URLSession:(NSURLSession *)session return; } } - + if (delegate) { [delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location]; } @@ -1053,7 +1157,7 @@ + (BOOL)supportsSecureCoding { return YES; } -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; self = [self initWithSessionConfiguration:configuration]; @@ -1070,10 +1174,8 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration]; } @end - -#endif diff --git a/OHHTTPStubs/Pods/AFNetworking/LICENSE b/OHHTTPStubs/Pods/AFNetworking/LICENSE index 0616192d..91f125b0 100644 --- a/OHHTTPStubs/Pods/AFNetworking/LICENSE +++ b/OHHTTPStubs/Pods/AFNetworking/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com/) +Copyright (c) 2011–2015 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 diff --git a/OHHTTPStubs/Pods/AFNetworking/README.md b/OHHTTPStubs/Pods/AFNetworking/README.md index 13e080c0..e44875ff 100644 --- a/OHHTTPStubs/Pods/AFNetworking/README.md +++ b/OHHTTPStubs/Pods/AFNetworking/README.md @@ -3,6 +3,10 @@

[![Build Status](https://travis-ci.org/AFNetworking/AFNetworking.svg)](https://travis-ci.org/AFNetworking/AFNetworking) +[![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. @@ -15,7 +19,7 @@ Choose AFNetworking for your next project, or migrate over your existing project - [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 2.0 Migration Guide](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-2.0-Migration-Guide) for an overview of the architectural changes from 1.0. +- 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 @@ -25,36 +29,71 @@ Choose AFNetworking for your next project, or migrate over your existing project - If you **have a feature request**, open an issue. - If you **want to contribute**, submit a pull request. -### Installation with CocoaPods +## Installation +AFNetworking supports multiple methods for installing the library in a project. -[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). +## 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 -platform :ios, '7.0' -pod "AFNetworking", "~> 2.0" +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 | Notes | -|:--------------------:|:---------------------------:|:----------------------------:|:-------------------------------------------------------------------------:| -| 2.x | iOS 6 | OS X 10.8 | Xcode 5 is required. `AFHTTPSessionManager` requires iOS 7 or OS X 10.9. | -| [1.x](https://github.com/AFNetworking/AFNetworking/tree/1.x) | iOS 5 | Mac OS X 10.7 | | -| [0.10.x](https://github.com/AFNetworking/AFNetworking/tree/0.10.x) | iOS 4 | Mac OS X 10.6 | | +| AFNetworking Version | Minimum iOS Target | Minimum OS X Target | Minimum watchOS Target | Minimum tvOS Target | Notes | +|:--------------------:|:---------------------------:|:----------------------------:|:----------------------------:|:----------------------------:|:-------------------------------------------------------------------------:| +| 3.x | iOS 7 | OS X 10.9 | 2.0 | 9.0 | Xcode 7 is required. `NSURLConnectionOperation` support has been removed. | +| [2.x](https://github.com/AFNetworking/AFNetworking/tree/2.x) | iOS 7 | OS X 10.8 | 2.0 | n/a | Xcode 5 is required. `NSURLSession` subspec requires iOS 7 or OS X 10.9. | +| [1.x](https://github.com/AFNetworking/AFNetworking/tree/1.x) | iOS 5 | Mac OS X 10.7 | n/a | n/a | +| [0.10.x](https://github.com/AFNetworking/AFNetworking/tree/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)). -## Architecture - -### NSURLConnection +> Programming in Swift? Try [Alamofire](https://github.com/Alamofire/Alamofire) for a more conventional set of APIs. -- `AFURLConnectionOperation` -- `AFHTTPRequestOperation` -- `AFHTTPRequestOperationManager` +## Architecture -### NSURLSession _(iOS 7 / Mac OS X 10.9)_ +### NSURLSession - `AFURLSessionManager` - `AFHTTPSessionManager` @@ -81,50 +120,6 @@ pod "AFNetworking", "~> 2.0" ## Usage -### HTTP Request Operation Manager - -`AFHTTPRequestOperationManager` encapsulates the common patterns of communicating with a web application over HTTP, including request creation, response serialization, network reachability monitoring, and security, as well as request operation management. - -#### `GET` Request - -```objective-c -AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; -[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { - NSLog(@"JSON: %@", responseObject); -} failure:^(AFHTTPRequestOperation *operation, NSError *error) { - NSLog(@"Error: %@", error); -}]; -``` - -#### `POST` URL-Form-Encoded Request - -```objective-c -AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; -NSDictionary *parameters = @{@"foo": @"bar"}; -[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { - NSLog(@"JSON: %@", responseObject); -} failure:^(AFHTTPRequestOperation *operation, NSError *error) { - NSLog(@"Error: %@", error); -}]; -``` - -#### `POST` Multi-Part Request - -```objective-c -AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; -NSDictionary *parameters = @{@"foo": @"bar"}; -NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"]; -[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id formData) { - [formData appendPartWithFileURL:filePath name:@"image" error:nil]; -} success:^(AFHTTPRequestOperation *operation, id responseObject) { - NSLog(@"Success: %@", responseObject); -} failure:^(AFHTTPRequestOperation *operation, NSError *error) { - NSLog(@"Error: %@", error); -}]; -``` - ---- - ### AFURLSessionManager `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. @@ -254,35 +249,23 @@ NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]}; `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)); }]; -``` - -#### HTTP Manager Reachability -```objective-c -NSURL *baseURL = [NSURL URLWithString:@"http://example.com/"]; -AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL]; - -NSOperationQueue *operationQueue = manager.operationQueue; -[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { - switch (status) { - case AFNetworkReachabilityStatusReachableViaWWAN: - case AFNetworkReachabilityStatusReachableViaWiFi: - [operationQueue setSuspended:NO]; - break; - case AFNetworkReachabilityStatusNotReachable: - default: - [operationQueue setSuspended:YES]; - break; - } -}]; - -[manager.reachabilityManager startMonitoring]; +[[AFNetworkReachabilityManager sharedManager] startMonitoring]; ``` --- @@ -296,88 +279,30 @@ Adding pinned SSL certificates to your app helps prevent man-in-the-middle attac #### Allowing Invalid SSL Certificates ```objective-c -AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; +AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production ``` --- -### AFHTTPRequestOperation - -`AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request. - -Although `AFHTTPRequestOperationManager` is usually the best way to go about making requests, `AFHTTPRequestOperation` can be used by itself. - -#### `GET` with `AFHTTPRequestOperation` - -```objective-c -NSURL *URL = [NSURL URLWithString:@"http://example.com/resources/123.json"]; -NSURLRequest *request = [NSURLRequest requestWithURL:URL]; -AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request]; -op.responseSerializer = [AFJSONResponseSerializer serializer]; -[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { - NSLog(@"JSON: %@", responseObject); -} failure:^(AFHTTPRequestOperation *operation, NSError *error) { - NSLog(@"Error: %@", error); -}]; -[[NSOperationQueue mainQueue] addOperation:op]; -``` - -#### Batch of Operations - -```objective-c -NSMutableArray *mutableOperations = [NSMutableArray array]; -for (NSURL *fileURL in filesToUpload) { - NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) { - [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil]; - }]; - - AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; - - [mutableOperations addObject:operation]; -} - -NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) { - NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations); -} completionBlock:^(NSArray *operations) { - NSLog(@"All operations in batch complete"); -}]; -[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO]; -``` - ## Unit Tests -AFNetworking includes a suite of unit tests within the Tests subdirectory. In order to run the unit tests, you must install the testing dependencies via [CocoaPods](http://cocoapods.org/): - - $ cd Tests - $ pod install - -Once testing dependencies are installed, you can execute the test suite via the 'iOS Tests' and 'OS X Tests' schemes within Xcode. - -### Running Tests from the Command Line - -Tests can also be run from the command line or within a continuous integration environment. The [`xcpretty`](https://github.com/mneorr/xcpretty) utility needs to be installed before running the tests from the command line: - - $ gem install xcpretty - -Once `xcpretty` is installed, you can execute the suite via `rake test`. +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). -## Contact - -Follow AFNetworking on Twitter ([@AFNetworking](https://twitter.com/AFNetworking)) - -### Maintainers +### Security Disclosure -- [Mattt Thompson](http://github.com/mattt) ([@mattt](https://twitter.com/mattt)) +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 available under the MIT license. See the LICENSE file for more info. +AFNetworking is released under the MIT license. See LICENSE for details. diff --git a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h new file mode 100644 index 00000000..e89b951e --- /dev/null +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h @@ -0,0 +1,149 @@ +// AFAutoPurgingImageCache.h +// Copyright (c) 2011–2015 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/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m new file mode 100644 index 00000000..4bf1d7e0 --- /dev/null +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m @@ -0,0 +1,205 @@ +// AFAutoPurgingImageCache.m +// Copyright (c) 2011–2015 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; +#if OS_OBJECT_HAVE_OBJC_SUPPORT +@property (nonatomic, strong) dispatch_queue_t synchronizationQueue; +#else +@property (nonatomic, assign) dispatch_queue_t synchronizationQueue; +#endif +@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/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h new file mode 100644 index 00000000..9c044a53 --- /dev/null +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h @@ -0,0 +1,137 @@ +// AFImageDownloader.h +// Copyright (c) 2011–2015 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 image + 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; + +/** + 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/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m new file mode 100644 index 00000000..1503056e --- /dev/null +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m @@ -0,0 +1,367 @@ +// AFImageDownloader.m +// Copyright (c) 2011–2015 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 *identifier; +@property (nonatomic, strong) NSURLSessionDataTask *task; +@property (nonatomic, strong) NSMutableArray *responseHandlers; + +@end + +@implementation AFImageDownloaderMergedTask + +- (instancetype)initWithIdentifier:(NSString *)identifier task:(NSURLSessionDataTask *)task { + if (self = [self init]) { + self.identifier = identifier; + self.task = task; + 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 () + +#if OS_OBJECT_HAVE_OBJC_SUPPORT +@property (nonatomic, strong) dispatch_queue_t synchronizationQueue; +@property (nonatomic, strong) dispatch_queue_t responseQueue; +#else +@property (nonatomic, assign) dispatch_queue_t synchronizationQueue; +@property (nonatomic, assign) dispatch_queue_t responseQueue; +#endif + +@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:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure { + NSUUID *callerUUID = [NSUUID UUID]; + __block NSURLSessionDataTask *task = nil; + dispatch_sync(self.synchronizationQueue, ^{ + NSString *identifier = request.URL.absoluteString; + + // 1) Append the success and failure blocks to a pre-existing request if it already exists + AFImageDownloaderMergedTask *existingMergedTask = self.mergedTasks[identifier]; + if (existingMergedTask != nil) { + AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:callerUUID 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 + 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 = [strongSelf safelyRemoveMergedTaskWithIdentifier:identifier]; + 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:callerUUID + success:success + failure:failure]; + AFImageDownloaderMergedTask *mergedTask = [[AFImageDownloaderMergedTask alloc] + initWithIdentifier:identifier + task:createdTask]; + [mergedTask addResponseHandler:handler]; + self.mergedTasks[identifier] = 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:callerUUID task:task]; + } else { + return nil; + } +} + +- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt { + dispatch_sync(self.synchronizationQueue, ^{ + NSString *identifier = imageDownloadReceipt.task.originalRequest.URL.absoluteString; + AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[identifier]; + 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]; + } + }); +} + +- (AFImageDownloaderMergedTask*)safelyRemoveMergedTaskWithIdentifier:(NSString *)identifier { + __block AFImageDownloaderMergedTask *mergedTask = nil; + dispatch_sync(self.synchronizationQueue, ^{ + mergedTask = self.mergedTasks[identifier]; + [self.mergedTasks removeObjectForKey:identifier]; + + }); + 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/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h index 312d680e..a627a6d6 100644 --- a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h @@ -1,6 +1,5 @@ // AFNetworkActivityIndicatorManager.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2015 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 @@ -22,24 +21,27 @@ #import -#import +#import -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#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 network request operation has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero. + `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 `isNetworkActivityIndicatorVisible` 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. + 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 /** @@ -50,9 +52,25 @@ @property (nonatomic, assign, getter = isEnabled) BOOL enabled; /** - A Boolean value indicating whether the network activity indicator is currently displayed in the status bar. + 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 (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible; +@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. @@ -71,6 +89,15 @@ */ - (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/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m index c2d855a5..0615fa9f 100644 --- a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m @@ -1,6 +1,5 @@ // AFNetworkActivityIndicatorManager.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2015 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 @@ -22,41 +21,42 @@ #import "AFNetworkActivityIndicatorManager.h" -#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) - -#import "AFHTTPRequestOperation.h" - -#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 +#if TARGET_OS_IOS #import "AFURLSessionManager.h" -#endif -static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17; +typedef NS_ENUM(NSInteger, AFNetworkActivityManagerState) { + AFNetworkActivityManagerStateNotActive, + AFNetworkActivityManagerStateDelayingStart, + AFNetworkActivityManagerStateActive, + AFNetworkActivityManagerStateDelayingEnd +}; -static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) { - if ([[notification object] isKindOfClass:[AFURLConnectionOperation class]]) { - return [(AFURLConnectionOperation *)[notification object] request]; - } +static NSTimeInterval const kDefaultAFNetworkActivityManagerActivationDelay = 1.0; +static NSTimeInterval const kDefaultAFNetworkActivityManagerCompletionDelay = 0.17; -#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 +static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) { if ([[notification object] respondsToSelector:@selector(originalRequest)]) { return [(NSURLSessionTask *)[notification object] originalRequest]; + } else { + return nil; } -#endif - - return nil; } +typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisible); + @interface AFNetworkActivityIndicatorManager () @property (readwrite, nonatomic, assign) NSInteger activityCount; -@property (readwrite, nonatomic, strong) NSTimer *activityIndicatorVisibilityTimer; -@property (readonly, nonatomic, getter = isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; +@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)updateNetworkActivityIndicatorVisibility; -- (void)updateNetworkActivityIndicatorVisibilityDelayed; +- (void)updateCurrentStateForNetworkActivityChange; @end @implementation AFNetworkActivityIndicatorManager -@dynamic networkActivityIndicatorVisible; + (instancetype)sharedManager { static AFNetworkActivityIndicatorManager *_sharedManager = nil; @@ -68,24 +68,17 @@ + (instancetype)sharedManager { return _sharedManager; } -+ (NSSet *)keyPathsForValuesAffectingIsNetworkActivityIndicatorVisible { - return [NSSet setWithObject:@"activityCount"]; -} - -- (id)init { +- (instancetype)init { self = [super init]; if (!self) { return nil; } - - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingOperationDidStartNotification object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingOperationDidFinishNotification object:nil]; - -#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 + 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]; -#endif + self.activationDelay = kDefaultAFNetworkActivityManagerActivationDelay; + self.completionDelay = kDefaultAFNetworkActivityManagerCompletionDelay; return self; } @@ -93,37 +86,49 @@ - (id)init { - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; - [_activityIndicatorVisibilityTimer invalidate]; + [_activationDelayTimer invalidate]; + [_completionDelayTimer invalidate]; } -- (void)updateNetworkActivityIndicatorVisibilityDelayed { - if (self.enabled) { - // Delay hiding of activity indicator for a short interval, to avoid flickering - if (![self isNetworkActivityIndicatorVisible]) { - [self.activityIndicatorVisibilityTimer invalidate]; - self.activityIndicatorVisibilityTimer = [NSTimer timerWithTimeInterval:kAFNetworkActivityIndicatorInvisibilityDelay target:self selector:@selector(updateNetworkActivityIndicatorVisibility) userInfo:nil repeats:NO]; - [[NSRunLoop mainRunLoop] addTimer:self.activityIndicatorVisibilityTimer forMode:NSRunLoopCommonModes]; - } else { - [self performSelectorOnMainThread:@selector(updateNetworkActivityIndicatorVisibility) withObject:nil waitUntilDone:NO modes:@[NSRunLoopCommonModes]]; - } +- (void)setEnabled:(BOOL)enabled { + _enabled = enabled; + if (enabled == NO) { + [self setCurrentState:AFNetworkActivityManagerStateNotActive]; } } -- (BOOL)isNetworkActivityIndicatorVisible { - return self.activityCount > 0; +- (void)setNetworkingActivityActionWithBlock:(void (^)(BOOL networkActivityIndicatorVisible))block { + self.networkActivityActionBlock = block; } -- (void)updateNetworkActivityIndicatorVisibility { - [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:[self isNetworkActivityIndicatorVisible]]; +- (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 updateNetworkActivityIndicatorVisibilityDelayed]; + [self updateCurrentStateForNetworkActivityChange]; }); } @@ -133,9 +138,9 @@ - (void)incrementActivityCount { _activityCount++; } [self didChangeValueForKey:@"activityCount"]; - + dispatch_async(dispatch_get_main_queue(), ^{ - [self updateNetworkActivityIndicatorVisibilityDelayed]; + [self updateCurrentStateForNetworkActivityChange]; }); } @@ -148,9 +153,9 @@ - (void)decrementActivityCount { #pragma clang diagnostic pop } [self didChangeValueForKey:@"activityCount"]; - + dispatch_async(dispatch_get_main_queue(), ^{ - [self updateNetworkActivityIndicatorVisibilityDelayed]; + [self updateCurrentStateForNetworkActivityChange]; }); } @@ -166,6 +171,91 @@ - (void)networkRequestDidFinish:(NSNotification *)notification { } } +#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/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h index 1c1f8dd6..b6ef044d 100644 --- a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h @@ -1,6 +1,5 @@ // UIActivityIndicatorView+AFNetworking.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2015 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 @@ -22,16 +21,14 @@ #import -#import +#import -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_TV #import -@class AFURLConnectionOperation; - /** - This category adds methods to the UIKit framework's `UIActivityIndicatorView` class. The methods in this category provide support for automatically starting and stopping animation depending on the loading state of a request operation or session task. + 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) @@ -44,20 +41,7 @@ @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. */ -#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 -- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task; -#endif - -///--------------------------------------- -/// @name Animating for Request Operations -///--------------------------------------- - -/** - Binds the animating state to the execution state of the specified operation. - - @param operation The operation. If `nil`, automatic updating from any previously specified operation will be disabled. - */ -- (void)setAnimatingWithStateOfOperation:(AFURLConnectionOperation *)operation; +- (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task; @end diff --git a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m index 6627dbb1..fcf1c0c9 100644 --- a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m @@ -1,6 +1,5 @@ // UIActivityIndicatorView+AFNetworking.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2015 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 @@ -21,32 +20,67 @@ // THE SOFTWARE. #import "UIActivityIndicatorView+AFNetworking.h" +#import -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - -#import "AFHTTPRequestOperation.h" +#if TARGET_OS_IOS || TARGET_OS_TV -#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 #import "AFURLSessionManager.h" -#endif + +@interface AFActivityIndicatorViewNotificationObserver : NSObject +@property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView; +- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView; + +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task; + +@end @implementation UIActivityIndicatorView (AFNetworking) -#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 +- (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 startAnimating]; + [self.activityIndicatorView startAnimating]; } else { - [self stopAnimating]; + [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]; @@ -54,44 +88,37 @@ - (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { } } } -#endif - -#pragma mark - - -- (void)setAnimatingWithStateOfOperation:(AFURLConnectionOperation *)operation { - NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - - [notificationCenter removeObserver:self name:AFNetworkingOperationDidStartNotification object:nil]; - [notificationCenter removeObserver:self name:AFNetworkingOperationDidFinishNotification object:nil]; - - if (operation) { - if (![operation isFinished]) { - if ([operation isExecuting]) { - [self startAnimating]; - } else { - [self stopAnimating]; - } - - [notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingOperationDidStartNotification object:operation]; - [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingOperationDidFinishNotification object:operation]; - } - } -} #pragma mark - - (void)af_startAnimating { dispatch_async(dispatch_get_main_queue(), ^{ - [self startAnimating]; +#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(), ^{ - [self stopAnimating]; +#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/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.h b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.h deleted file mode 100644 index b94f1cb8..00000000 --- a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.h +++ /dev/null @@ -1,96 +0,0 @@ -// UIAlertView+AFNetworking.h -// -// Copyright (c) 2013-2014 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 - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - -#import - -@class AFURLConnectionOperation; - -/** - This category adds methods to the UIKit framework's `UIAlertView` class. The methods in this category provide support for automatically showing an alert if a session task or request operation finishes with an error. Alert title and message are filled from the corresponding `localizedDescription` & `localizedRecoverySuggestion` or `localizedFailureReason` of the error. - */ -@interface UIAlertView (AFNetworking) - -///------------------------------------- -/// @name Showing Alert for Session Task -///------------------------------------- - -/** - Shows an alert view with the error of the specified session task, if any. - - @param task The session task. - @param delegate The alert view delegate. - */ -#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 -+ (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task - delegate:(id)delegate; -#endif - -/** - Shows an alert view with the error of the specified session task, if any, with a custom cancel button title and other button titles. - - @param task The session task. - @param delegate The alert view delegate. - @param cancelButtonTitle The title of the cancel button or nil if there is no cancel button. Using this argument is equivalent to setting the cancel button index to the value returned by invoking addButtonWithTitle: specifying this title. - @param otherButtonTitles The title of another button. Using this argument is equivalent to invoking addButtonWithTitle: with this title to add more buttons. Too many buttons can cause the alert view to scroll. For guidelines on the best ways to use an alert in an app, see "Temporary Views". Titles of additional buttons to add to the receiver, terminated with `nil`. - */ -#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 -+ (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task - delegate:(id)delegate - cancelButtonTitle:(NSString *)cancelButtonTitle - otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION; -#endif - -///------------------------------------------ -/// @name Showing Alert for Request Operation -///------------------------------------------ - -/** - Shows an alert view with the error of the specified request operation, if any. - - @param operation The request operation. - @param delegate The alert view delegate. - */ -+ (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation - delegate:(id)delegate; - -/** - Shows an alert view with the error of the specified request operation, if any, with a custom cancel button title and other button titles. - - @param operation The request operation. - @param delegate The alert view delegate. - @param cancelButtonTitle The title of the cancel button or nil if there is no cancel button. Using this argument is equivalent to setting the cancel button index to the value returned by invoking addButtonWithTitle: specifying this title. - @param otherButtonTitles The title of another button. Using this argument is equivalent to invoking addButtonWithTitle: with this title to add more buttons. Too many buttons can cause the alert view to scroll. For guidelines on the best ways to use an alert in an app, see "Temporary Views". Titles of additional buttons to add to the receiver, terminated with `nil`. - */ -+ (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation - delegate:(id)delegate - cancelButtonTitle:(NSString *)cancelButtonTitle - otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION; - -@end - -#endif diff --git a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.m b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.m deleted file mode 100644 index b7e2a26c..00000000 --- a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIAlertView+AFNetworking.m +++ /dev/null @@ -1,111 +0,0 @@ -// UIAlertView+AFNetworking.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "UIAlertView+AFNetworking.h" - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - -#import "AFURLConnectionOperation.h" - -#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 -#import "AFURLSessionManager.h" -#endif - -static void AFGetAlertViewTitleAndMessageFromError(NSError *error, NSString * __autoreleasing *title, NSString * __autoreleasing *message) { - if (error.localizedDescription && (error.localizedRecoverySuggestion || error.localizedFailureReason)) { - *title = error.localizedDescription; - - if (error.localizedRecoverySuggestion) { - *message = error.localizedRecoverySuggestion; - } else { - *message = error.localizedFailureReason; - } - } else if (error.localizedDescription) { - *title = NSLocalizedStringFromTable(@"Error", @"AFNetworking", @"Fallback Error Description"); - *message = error.localizedDescription; - } else { - *title = NSLocalizedStringFromTable(@"Error", @"AFNetworking", @"Fallback Error Description"); - *message = [NSString stringWithFormat:NSLocalizedStringFromTable(@"%@ Error: %ld", @"AFNetworking", @"Fallback Error Failure Reason Format"), error.domain, (long)error.code]; - } -} - -@implementation UIAlertView (AFNetworking) - -#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 -+ (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task - delegate:(id)delegate -{ - [self showAlertViewForTaskWithErrorOnCompletion:task delegate:delegate cancelButtonTitle:NSLocalizedStringFromTable(@"Dismiss", @"AFNetworking", @"UIAlertView Cancel Button Title") otherButtonTitles:nil, nil]; -} - -+ (void)showAlertViewForTaskWithErrorOnCompletion:(NSURLSessionTask *)task - delegate:(id)delegate - cancelButtonTitle:(NSString *)cancelButtonTitle - otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION -{ - __block id observer = [[NSNotificationCenter defaultCenter] addObserverForName:AFNetworkingTaskDidCompleteNotification object:task queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) { - - NSError *error = notification.userInfo[AFNetworkingTaskDidCompleteErrorKey]; - if (error) { - NSString *title, *message; - AFGetAlertViewTitleAndMessageFromError(error, &title, &message); - - [[[UIAlertView alloc] initWithTitle:title message:message delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil] show]; - } - - [[NSNotificationCenter defaultCenter] removeObserver:observer name:AFNetworkingTaskDidCompleteNotification object:notification.object]; - }]; -} -#endif - -#pragma mark - - -+ (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation - delegate:(id)delegate -{ - [self showAlertViewForRequestOperationWithErrorOnCompletion:operation delegate:delegate cancelButtonTitle:NSLocalizedStringFromTable(@"Dismiss", @"AFNetworking", @"UIAlert View Cancel Button Title") otherButtonTitles:nil, nil]; -} - -+ (void)showAlertViewForRequestOperationWithErrorOnCompletion:(AFURLConnectionOperation *)operation - delegate:(id)delegate - cancelButtonTitle:(NSString *)cancelButtonTitle - otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION -{ - __block id observer = [[NSNotificationCenter defaultCenter] addObserverForName:AFNetworkingOperationDidFinishNotification object:operation queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) { - - if (notification.object && [notification.object isKindOfClass:[AFURLConnectionOperation class]]) { - NSError *error = [(AFURLConnectionOperation *)notification.object error]; - if (error) { - NSString *title, *message; - AFGetAlertViewTitleAndMessageFromError(error, &title, &message); - - [[[UIAlertView alloc] initWithTitle:title message:message delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil] show]; - } - } - - [[NSNotificationCenter defaultCenter] removeObserver:observer name:AFNetworkingOperationDidFinishNotification object:notification.object]; - }]; -} - -@end - -#endif diff --git a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h index e6ed6de0..98b911e1 100644 --- a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h @@ -1,6 +1,5 @@ // UIButton+AFNetworking.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2015 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 @@ -22,47 +21,38 @@ #import -#import +#import -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_TV #import -@protocol AFURLResponseSerialization, AFImageCache; +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 Image Cache -///---------------------------- - -/** - The image cache used to improve image loadiing performance on scroll views. By default, `UIButton` will use the `sharedImageCache` of `UIImageView`. - */ -+ (id )sharedImageCache; - -/** - Set the cache used for image loading. - - @param imageCache The image cache. - */ -+ (void)setSharedImageCache:(id )imageCache; - ///------------------------------------ -/// @name Accessing Response Serializer +/// @name Accessing the Image Downloader ///------------------------------------ /** - The response serializer used to create an image representation from the server response and response data. By default, this is an instance of `AFImageResponseSerializer`. + Set the shared image downloader used to download images. - @discussion Subclasses of `AFImageResponseSerializer` could be used to perform post-processing, such as color correction, face detection, or other effects. See https://github.com/AFNetworking/AFCoreImageSerializer + @param imageDownloader The shared image downloader used to download images. +*/ ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; + +/** + The shared image downloader used to download images. */ -@property (nonatomic, strong) id imageResponseSerializer; ++ (AFImageDownloader *)sharedImageDownloader; ///-------------------- /// @name Setting Image @@ -70,9 +60,9 @@ /** 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. */ @@ -81,35 +71,35 @@ /** 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:(UIImage *)placeholderImage; + 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 request operation finishes successfully. This block has no return value and takes two arguments: the server response and the image. If the image was returned from cache, the request and response parameters will be `nil`. - @param failure A block object to be executed when the image request operation finishes unsuccessfully, or that finishes successfully. This block has no return value and takes a single argument: the error that occurred. + @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:(UIImage *)placeholderImage - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success - failure:(void (^)(NSError *error))failure; + 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; ///------------------------------- @@ -138,7 +128,7 @@ */ - (void)setBackgroundImageForState:(UIControlState)state withURL:(NSURL *)url - placeholderImage:(UIImage *)placeholderImage; + 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. @@ -150,12 +140,14 @@ @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:(UIImage *)placeholderImage - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success - failure:(void (^)(NSError *error))failure; + 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; ///------------------------------ @@ -163,19 +155,21 @@ ///------------------------------ /** - Cancels any executing image operation for the specified control state of the receiver, if one exists. - + Cancels any executing image task for the specified control state of the receiver, if one exists. + @param state The control state. */ -- (void)cancelImageRequestOperationForState:(UIControlState)state; +- (void)cancelImageDownloadTaskForState:(UIControlState)state; /** - Cancels any executing background image operation for the specified control state of the receiver, if one exists. - + Cancels any executing background image task for the specified control state of the receiver, if one exists. + @param state The control state. */ -- (void)cancelBackgroundImageRequestOperationForState:(UIControlState)state; +- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state; @end +NS_ASSUME_NONNULL_END + #endif diff --git a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m index a225290a..2729506e 100644 --- a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m @@ -1,6 +1,5 @@ // UIButton+AFNetworking.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2015 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 @@ -24,89 +23,76 @@ #import -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - -#import "AFURLResponseSerialization.h" -#import "AFHTTPRequestOperation.h" +#if TARGET_OS_IOS || TARGET_OS_TV #import "UIImageView+AFNetworking.h" +#import "AFImageDownloader.h" @interface UIButton (_AFNetworking) @end @implementation UIButton (_AFNetworking) -+ (NSOperationQueue *)af_sharedImageRequestOperationQueue { - static NSOperationQueue *_af_sharedImageRequestOperationQueue = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - _af_sharedImageRequestOperationQueue = [[NSOperationQueue alloc] init]; - _af_sharedImageRequestOperationQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount; - }); - - return _af_sharedImageRequestOperationQueue; -} - #pragma mark - -static char AFImageRequestOperationNormal; -static char AFImageRequestOperationHighlighted; -static char AFImageRequestOperationSelected; -static char AFImageRequestOperationDisabled; +static char AFImageDownloadReceiptNormal; +static char AFImageDownloadReceiptHighlighted; +static char AFImageDownloadReceiptSelected; +static char AFImageDownloadReceiptDisabled; -static const char * af_imageRequestOperationKeyForState(UIControlState state) { +static const char * af_imageDownloadReceiptKeyForState(UIControlState state) { switch (state) { case UIControlStateHighlighted: - return &AFImageRequestOperationHighlighted; + return &AFImageDownloadReceiptHighlighted; case UIControlStateSelected: - return &AFImageRequestOperationSelected; + return &AFImageDownloadReceiptSelected; case UIControlStateDisabled: - return &AFImageRequestOperationDisabled; + return &AFImageDownloadReceiptDisabled; case UIControlStateNormal: default: - return &AFImageRequestOperationNormal; + return &AFImageDownloadReceiptNormal; } } -- (AFHTTPRequestOperation *)af_imageRequestOperationForState:(UIControlState)state { - return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, af_imageRequestOperationKeyForState(state)); +- (AFImageDownloadReceipt *)af_imageDownloadReceiptForState:(UIControlState)state { + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_imageDownloadReceiptKeyForState(state)); } -- (void)af_setImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation +- (void)af_setImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt forState:(UIControlState)state { - objc_setAssociatedObject(self, af_imageRequestOperationKeyForState(state), imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + objc_setAssociatedObject(self, af_imageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } #pragma mark - -static char AFBackgroundImageRequestOperationNormal; -static char AFBackgroundImageRequestOperationHighlighted; -static char AFBackgroundImageRequestOperationSelected; -static char AFBackgroundImageRequestOperationDisabled; +static char AFBackgroundImageDownloadReceiptNormal; +static char AFBackgroundImageDownloadReceiptHighlighted; +static char AFBackgroundImageDownloadReceiptSelected; +static char AFBackgroundImageDownloadReceiptDisabled; -static const char * af_backgroundImageRequestOperationKeyForState(UIControlState state) { +static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState state) { switch (state) { case UIControlStateHighlighted: - return &AFBackgroundImageRequestOperationHighlighted; + return &AFBackgroundImageDownloadReceiptHighlighted; case UIControlStateSelected: - return &AFBackgroundImageRequestOperationSelected; + return &AFBackgroundImageDownloadReceiptSelected; case UIControlStateDisabled: - return &AFBackgroundImageRequestOperationDisabled; + return &AFBackgroundImageDownloadReceiptDisabled; case UIControlStateNormal: default: - return &AFBackgroundImageRequestOperationNormal; + return &AFBackgroundImageDownloadReceiptNormal; } } -- (AFHTTPRequestOperation *)af_backgroundImageRequestOperationForState:(UIControlState)state { - return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, af_backgroundImageRequestOperationKeyForState(state)); +- (AFImageDownloadReceipt *)af_backgroundImageDownloadReceiptForState:(UIControlState)state { + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state)); } -- (void)af_setBackgroundImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation +- (void)af_setBackgroundImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt forState:(UIControlState)state { - objc_setAssociatedObject(self, af_backgroundImageRequestOperationKeyForState(state), imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + objc_setAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } @end @@ -115,34 +101,16 @@ - (void)af_setBackgroundImageRequestOperation:(AFHTTPRequestOperation *)imageReq @implementation UIButton (AFNetworking) -+ (id )sharedImageCache { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - return objc_getAssociatedObject(self, @selector(sharedImageCache)) ?: [UIImageView sharedImageCache]; -#pragma clang diagnostic pop -} - -+ (void)setSharedImageCache:(id )imageCache { - objc_setAssociatedObject(self, @selector(sharedImageCache), imageCache, OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -#pragma mark - - -- (id )imageResponseSerializer { - static id _af_defaultImageResponseSerializer = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - _af_defaultImageResponseSerializer = [AFImageResponseSerializer serializer]; - }); ++ (AFImageDownloader *)sharedImageDownloader { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" - return objc_getAssociatedObject(self, @selector(imageResponseSerializer)) ?: _af_defaultImageResponseSerializer; + return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; #pragma clang diagnostic pop } -- (void)setImageResponseSerializer:(id )serializer { - objc_setAssociatedObject(self, @selector(imageResponseSerializer), serializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { + objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } #pragma mark - @@ -165,49 +133,60 @@ - (void)setImageForState:(UIControlState)state - (void)setImageForState:(UIControlState)state withURLRequest:(NSURLRequest *)urlRequest - placeholderImage:(UIImage *)placeholderImage - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success - failure:(void (^)(NSError *error))failure + 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 { - [self cancelImageRequestOperationForState:state]; + if ([self isActiveTaskURLEqualToURLRequest:urlRequest forState:state]) { + return; + } - UIImage *cachedImage = [[[self class] sharedImageCache] cachedImageForRequest:urlRequest]; + [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(nil, nil, cachedImage); + success(urlRequest, nil, cachedImage); } else { [self setImage:cachedImage forState:state]; } - - [self af_setImageRequestOperation:nil forState:state]; + [self af_setImageDownloadReceipt:nil forState:state]; } else { if (placeholderImage) { [self setImage:placeholderImage forState:state]; } __weak __typeof(self)weakSelf = self; - AFHTTPRequestOperation *imageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest]; - imageRequestOperation.responseSerializer = self.imageResponseSerializer; - [imageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - if ([[urlRequest URL] isEqual:[operation.request URL]]) { - if (success) { - success(operation.request, operation.response, responseObject); - } else if (responseObject) { - [strongSelf setImage:responseObject forState:state]; - } - } - [[[strongSelf class] sharedImageCache] cacheImage:responseObject forRequest:urlRequest]; - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if ([[urlRequest URL] isEqual:[operation.response URL]]) { - if (failure) { - failure(error); - } - } - }]; - - [self af_setImageRequestOperation:imageRequestOperation forState:state]; - [[[self class] af_sharedImageRequestOperationQueue] addOperation:imageRequestOperation]; + AFImageDownloadReceipt *receipt; + receipt = [downloader + downloadImageForURLRequest:urlRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([strongSelf isActiveTaskURLEqualToURLRequest:request forState:state]) { + 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 isActiveTaskURLEqualToURLRequest:request forState:state]) { + if (failure) { + failure(request, response, error); + } + [strongSelf af_setImageDownloadReceipt:nil forState:state]; + } + }]; + + [self af_setImageDownloadReceipt:receipt forState:state]; } } @@ -221,7 +200,7 @@ - (void)setBackgroundImageForState:(UIControlState)state - (void)setBackgroundImageForState:(UIControlState)state withURL:(NSURL *)url - placeholderImage:(UIImage *)placeholderImage + placeholderImage:(nullable UIImage *)placeholderImage { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; @@ -231,63 +210,92 @@ - (void)setBackgroundImageForState:(UIControlState)state - (void)setBackgroundImageForState:(UIControlState)state withURLRequest:(NSURLRequest *)urlRequest - placeholderImage:(UIImage *)placeholderImage - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success - failure:(void (^)(NSError *error))failure + 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 { - [self cancelBackgroundImageRequestOperationForState:state]; + if ([self isActiveBackgroundTaskURLEqualToURLRequest:urlRequest forState:state]) { + return; + } - UIImage *cachedImage = [[[self class] sharedImageCache] cachedImageForRequest:urlRequest]; + [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(nil, nil, cachedImage); + success(urlRequest, nil, cachedImage); } else { - [self setBackgroundImage:cachedImage forState:state]; + [self setImage:cachedImage forState:state]; } - - [self af_setBackgroundImageRequestOperation:nil forState:state]; + [self af_setBackgroundImageDownloadReceipt:nil forState:state]; } else { if (placeholderImage) { - [self setBackgroundImage:placeholderImage forState:state]; + [self setImage:placeholderImage forState:state]; } __weak __typeof(self)weakSelf = self; - AFHTTPRequestOperation *backgroundImageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest]; - backgroundImageRequestOperation.responseSerializer = self.imageResponseSerializer; - [backgroundImageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - if ([[urlRequest URL] isEqual:[operation.request URL]]) { - if (success) { - success(operation.request, operation.response, responseObject); - } else if (responseObject) { - [strongSelf setBackgroundImage:responseObject forState:state]; - } - } - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if ([[urlRequest URL] isEqual:[operation.response URL]]) { - if (failure) { - failure(error); - } - } - }]; - - [self af_setBackgroundImageRequestOperation:backgroundImageRequestOperation forState:state]; - [[[self class] af_sharedImageRequestOperationQueue] addOperation:backgroundImageRequestOperation]; + AFImageDownloadReceipt *receipt; + receipt = [downloader + downloadImageForURLRequest:urlRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([strongSelf isActiveBackgroundTaskURLEqualToURLRequest:request forState:state]) { + 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 isActiveBackgroundTaskURLEqualToURLRequest:request forState:state]) { + if (failure) { + failure(request, response, error); + } + [strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state]; + } + }]; + + [self af_setBackgroundImageDownloadReceipt:receipt forState:state]; } } #pragma mark - -- (void)cancelImageRequestOperationForState:(UIControlState)state { - [[self af_imageRequestOperationForState:state] cancel]; - [self af_setImageRequestOperation:nil forState:state]; +- (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]; } -- (void)cancelBackgroundImageRequestOperationForState:(UIControlState)state { - [[self af_backgroundImageRequestOperationForState:state] cancel]; - [self af_setBackgroundImageRequestOperation:nil forState:state]; +- (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/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h new file mode 100644 index 00000000..14744cdd --- /dev/null +++ b/OHHTTPStubs/Pods/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/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h index 5d523636..ce9ae2e6 100644 --- a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h @@ -1,6 +1,5 @@ // UIImageView+AFNetworking.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2015 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 @@ -22,53 +21,44 @@ #import -#import +#import -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_TV #import -@protocol AFURLResponseSerialization, AFImageCache; +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 Image Cache -///---------------------------- +///------------------------------------ +/// @name Accessing the Image Downloader +///------------------------------------ /** - The image cache used to improve image loadiing performance on scroll views. By default, this is an `NSCache` subclass conforming to the `AFImageCache` protocol, which listens for notification warnings and evicts objects accordingly. -*/ -+ (id )sharedImageCache; + Set the shared image downloader used to download images. -/** - Set the cache used for image loading. - - @param imageCache The image cache. + @param imageDownloader The shared image downloader used to download images. */ -+ (void)setSharedImageCache:(id )imageCache; - -///------------------------------------ -/// @name Accessing Response Serializer -///------------------------------------ ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; /** - The response serializer used to create an image representation from the server response and response data. By default, this is an instance of `AFImageResponseSerializer`. - - @discussion Subclasses of `AFImageResponseSerializer` could be used to perform post-processing, such as color correction, face detection, or other effects. See https://github.com/AFNetworking/AFCoreImageSerializer + The shared image downloader used to download images. */ -@property (nonatomic, strong) id imageResponseSerializer; ++ (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. - + 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:` @@ -78,8 +68,8 @@ - (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. - + 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:` @@ -88,56 +78,32 @@ @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:(UIImage *)placeholderImage; + 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. - + 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 request operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the request and response parameters will be `nil`. - @param failure A block object to be executed when the image request operation 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. + @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:(UIImage *)placeholderImage - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; + 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)cancelImageRequestOperation; +- (void)cancelImageDownloadTask; @end -#pragma mark - - -/** - The `AFImageCache` protocol is adopted by an object used to cache images loaded by the AFNetworking category on `UIImageView`. - */ -@protocol AFImageCache - -/** - Returns a cached image for the specififed request, if available. - - @param request The image request. - - @return The cached image. - */ -- (UIImage *)cachedImageForRequest:(NSURLRequest *)request; - -/** - Caches a particular image for the specified request. - - @param image The image to cache. - @param request The request to be used as a cache key. - */ -- (void)cacheImage:(UIImage *)image - forRequest:(NSURLRequest *)request; -@end +NS_ASSUME_NONNULL_END #endif diff --git a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m index c06aa9ca..69f5eef3 100644 --- a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m @@ -1,6 +1,5 @@ // UIImageView+AFNetworking.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2015 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 @@ -24,38 +23,22 @@ #import -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - -#import "AFHTTPRequestOperation.h" +#if TARGET_OS_IOS || TARGET_OS_TV -@interface AFImageCache : NSCache -@end - -#pragma mark - +#import "AFImageDownloader.h" @interface UIImageView (_AFNetworking) -@property (readwrite, nonatomic, strong, setter = af_setImageRequestOperation:) AFHTTPRequestOperation *af_imageRequestOperation; +@property (readwrite, nonatomic, strong, setter = af_setActiveImageDownloadReceipt:) AFImageDownloadReceipt *af_activeImageDownloadReceipt; @end @implementation UIImageView (_AFNetworking) -+ (NSOperationQueue *)af_sharedImageRequestOperationQueue { - static NSOperationQueue *_af_sharedImageRequestOperationQueue = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - _af_sharedImageRequestOperationQueue = [[NSOperationQueue alloc] init]; - _af_sharedImageRequestOperationQueue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount; - }); - - return _af_sharedImageRequestOperationQueue; -} - -- (AFHTTPRequestOperation *)af_imageRequestOperation { - return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, @selector(af_imageRequestOperation)); +- (AFImageDownloadReceipt *)af_activeImageDownloadReceipt { + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, @selector(af_activeImageDownloadReceipt)); } -- (void)af_setImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperation { - objc_setAssociatedObject(self, @selector(af_imageRequestOperation), imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +- (void)af_setActiveImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt { + objc_setAssociatedObject(self, @selector(af_activeImageDownloadReceipt), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } @end @@ -63,46 +46,17 @@ - (void)af_setImageRequestOperation:(AFHTTPRequestOperation *)imageRequestOperat #pragma mark - @implementation UIImageView (AFNetworking) -@dynamic imageResponseSerializer; - -+ (id )sharedImageCache { - static AFImageCache *_af_defaultImageCache = nil; - static dispatch_once_t oncePredicate; - dispatch_once(&oncePredicate, ^{ - _af_defaultImageCache = [[AFImageCache alloc] init]; - - [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidReceiveMemoryWarningNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * __unused notification) { - [_af_defaultImageCache removeAllObjects]; - }]; - }); - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - return objc_getAssociatedObject(self, @selector(sharedImageCache)) ?: _af_defaultImageCache; -#pragma clang diagnostic pop -} - -+ (void)setSharedImageCache:(id )imageCache { - objc_setAssociatedObject(self, @selector(sharedImageCache), imageCache, OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -#pragma mark - -- (id )imageResponseSerializer { - static id _af_defaultImageResponseSerializer = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - _af_defaultImageResponseSerializer = [AFImageResponseSerializer serializer]; - }); ++ (AFImageDownloader *)sharedImageDownloader { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" - return objc_getAssociatedObject(self, @selector(imageResponseSerializer)) ?: _af_defaultImageResponseSerializer; + return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; #pragma clang diagnostic pop } -- (void)setImageResponseSerializer:(id )serializer { - objc_setAssociatedObject(self, @selector(imageResponseSerializer), serializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { + objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } #pragma mark - @@ -122,93 +76,71 @@ - (void)setImageWithURL:(NSURL *)url - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest placeholderImage:(UIImage *)placeholderImage - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure { - [self cancelImageRequestOperation]; + if ([self isActiveTaskURLEqualToURLRequest:urlRequest]){ + return; + } + + [self cancelImageDownloadTask]; + + AFImageDownloader *downloader = [[self class] sharedImageDownloader]; + id imageCache = downloader.imageCache; - UIImage *cachedImage = [[[self class] sharedImageCache] cachedImageForRequest:urlRequest]; + //Use the image from the image cache if it exists + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; if (cachedImage) { if (success) { - success(nil, nil, cachedImage); + success(urlRequest, nil, cachedImage); } else { self.image = cachedImage; } - - self.af_imageRequestOperation = nil; + self.af_activeImageDownloadReceipt = nil; } else { if (placeholderImage) { self.image = placeholderImage; } - + __weak __typeof(self)weakSelf = self; - self.af_imageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest]; - self.af_imageRequestOperation.responseSerializer = self.imageResponseSerializer; - [self.af_imageRequestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - if ([[urlRequest URL] isEqual:[strongSelf.af_imageRequestOperation.request URL]]) { - if (success) { - success(urlRequest, operation.response, responseObject); - } else if (responseObject) { - strongSelf.image = responseObject; - } - - if (operation == strongSelf.af_imageRequestOperation){ - strongSelf.af_imageRequestOperation = nil; - } - } - - [[[strongSelf class] sharedImageCache] cacheImage:responseObject forRequest:urlRequest]; - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - if ([[urlRequest URL] isEqual:[strongSelf.af_imageRequestOperation.request URL]]) { - if (failure) { - failure(urlRequest, operation.response, error); - } - - if (operation == strongSelf.af_imageRequestOperation){ - strongSelf.af_imageRequestOperation = nil; - } - } - }]; - - [[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation]; + AFImageDownloadReceipt *receipt; + receipt = [downloader + downloadImageForURLRequest:urlRequest + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([strongSelf isActiveTaskURLEqualToURLRequest:request]) { + if (success) { + success(request, response, responseObject); + } else if(responseObject) { + strongSelf.image = responseObject; + } + strongSelf.af_activeImageDownloadReceipt = nil; + } + + } + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([strongSelf isActiveTaskURLEqualToURLRequest:request]) { + if (failure) { + failure(request, response, error); + } + strongSelf.af_activeImageDownloadReceipt = nil; + } + }]; + + self.af_activeImageDownloadReceipt = receipt; } } -- (void)cancelImageRequestOperation { - [self.af_imageRequestOperation cancel]; - self.af_imageRequestOperation = nil; -} - -@end - -#pragma mark - - -static inline NSString * AFImageCacheKeyFromURLRequest(NSURLRequest *request) { - return [[request URL] absoluteString]; -} - -@implementation AFImageCache - -- (UIImage *)cachedImageForRequest:(NSURLRequest *)request { - switch ([request cachePolicy]) { - case NSURLRequestReloadIgnoringCacheData: - case NSURLRequestReloadIgnoringLocalAndRemoteCacheData: - return nil; - default: - break; - } - - return [self objectForKey:AFImageCacheKeyFromURLRequest(request)]; +- (void)cancelImageDownloadTask { + if (self.af_activeImageDownloadReceipt != nil) { + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:self.af_activeImageDownloadReceipt]; + self.af_activeImageDownloadReceipt = nil; + } } -- (void)cacheImage:(UIImage *)image - forRequest:(NSURLRequest *)request -{ - if (image && request) { - [self setObject:image forKey:AFImageCacheKeyFromURLRequest(request)]; - } +- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest { + return [self.af_activeImageDownloadReceipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; } @end diff --git a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h index 94082f6c..b36ee0c5 100644 --- a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h @@ -20,19 +20,23 @@ // 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 "UIAlertView+AFNetworking.h" #import "UIButton+AFNetworking.h" #import "UIImageView+AFNetworking.h" - #import "UIKit+AFNetworking.h" #import "UIProgressView+AFNetworking.h" - #import "UIRefreshControl+AFNetworking.h" - #import "UIWebView+AFNetworking.h" #endif /* _UIKIT_AFNETWORKING_ */ +#endif diff --git a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h index 3f1bc086..a0c463b5 100644 --- a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h @@ -1,6 +1,5 @@ // UIProgressView+AFNetworking.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2015 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 @@ -22,16 +21,17 @@ #import -#import +#import -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_TV #import -@class AFURLConnectionOperation; +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 or request operation. + 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) @@ -41,14 +41,12 @@ /** 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. */ -#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 - (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task animated:(BOOL)animated; -#endif /** Binds the progress to the download progress of the specified session task. @@ -56,33 +54,11 @@ @param task The session task. @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. */ -#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 - (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task animated:(BOOL)animated; -#endif - -///------------------------------------ -/// @name Setting Session Task Progress -///------------------------------------ - -/** - Binds the progress to the upload progress of the specified request operation. - - @param operation The request operation. - @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. - */ -- (void)setProgressWithUploadProgressOfOperation:(AFURLConnectionOperation *)operation - animated:(BOOL)animated; - -/** - Binds the progress to the download progress of the specified request operation. - - @param operation The request operation. - @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. - */ -- (void)setProgressWithDownloadProgressOfOperation:(AFURLConnectionOperation *)operation - animated:(BOOL)animated; @end +NS_ASSUME_NONNULL_END + #endif diff --git a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m index 927f56d8..6680bacc 100644 --- a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m @@ -1,6 +1,5 @@ // UIProgressView+AFNetworking.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2015 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 @@ -24,33 +23,13 @@ #import -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - -#import "AFURLConnectionOperation.h" +#if TARGET_OS_IOS || TARGET_OS_TV -#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 #import "AFURLSessionManager.h" -#endif static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext; static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext; -@interface AFURLConnectionOperation (_UIProgressView) -@property (readwrite, nonatomic, copy) void (^uploadProgress)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected); -@property (readwrite, nonatomic, assign, setter = af_setUploadProgressAnimated:) BOOL af_uploadProgressAnimated; - -@property (readwrite, nonatomic, copy) void (^downloadProgress)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected); -@property (readwrite, nonatomic, assign, setter = af_setDownloadProgressAnimated:) BOOL af_downloadProgressAnimated; -@end - -@implementation AFURLConnectionOperation (_UIProgressView) -@dynamic uploadProgress; // Implemented in AFURLConnectionOperation -@dynamic af_uploadProgressAnimated; - -@dynamic downloadProgress; // Implemented in AFURLConnectionOperation -@dynamic af_downloadProgressAnimated; -@end - #pragma mark - @implementation UIProgressView (AFNetworking) @@ -73,7 +52,6 @@ - (void)af_setDownloadProgressAnimated:(BOOL)animated { #pragma mark - -#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 - (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task animated:(BOOL)animated { @@ -91,47 +69,6 @@ - (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task [self af_setDownloadProgressAnimated:animated]; } -#endif - -#pragma mark - - -- (void)setProgressWithUploadProgressOfOperation:(AFURLConnectionOperation *)operation - animated:(BOOL)animated -{ - __weak __typeof(self)weakSelf = self; - void (^original)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) = [operation.uploadProgress copy]; - [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { - if (original) { - original(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); - } - - dispatch_async(dispatch_get_main_queue(), ^{ - if (totalBytesExpectedToWrite > 0) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - [strongSelf setProgress:(totalBytesWritten / (totalBytesExpectedToWrite * 1.0f)) animated:animated]; - } - }); - }]; -} - -- (void)setProgressWithDownloadProgressOfOperation:(AFURLConnectionOperation *)operation - animated:(BOOL)animated -{ - __weak __typeof(self)weakSelf = self; - void (^original)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) = [operation.downloadProgress copy]; - [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { - if (original) { - original(bytesRead, totalBytesRead, totalBytesExpectedToRead); - } - - dispatch_async(dispatch_get_main_queue(), ^{ - if (totalBytesExpectedToRead > 0) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - [strongSelf setProgress:(totalBytesRead / (totalBytesExpectedToRead * 1.0f)) animated:animated]; - } - }); - }]; -} #pragma mark - NSKeyValueObserving @@ -140,7 +77,6 @@ - (void)observeValueForKeyPath:(NSString *)keyPath change:(__unused NSDictionary *)change context:(void *)context { -#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) { if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) { if ([object countOfBytesExpectedToSend] > 0) { @@ -175,7 +111,6 @@ - (void)observeValueForKeyPath:(NSString *)keyPath } } } -#endif } @end diff --git a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h index 37ce772d..f6930a98 100644 --- a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h @@ -22,16 +22,16 @@ #import -#import +#import -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS #import -@class AFURLConnectionOperation; +NS_ASSUME_NONNULL_BEGIN /** - This category adds methods to the UIKit framework's `UIRefreshControl` class. The methods in this category provide support for automatically begining and ending refreshing depending on the loading state of a request operation or session task. + 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) @@ -42,23 +42,12 @@ /** 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 diabled. + @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. */ -#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; -#endif - -///---------------------------------------- -/// @name Refreshing for Request Operations -///---------------------------------------- - -/** - Binds the refreshing state to the execution state of the specified operation. - - @param operation The operation. If `nil`, automatic updating from any previously specified operation will be disabled. - */ -- (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation; @end +NS_ASSUME_NONNULL_END + #endif diff --git a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m index e266451f..ddc033b9 100644 --- a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m @@ -21,18 +21,48 @@ // THE SOFTWARE. #import "UIRefreshControl+AFNetworking.h" +#import -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS -#import "AFHTTPRequestOperation.h" - -#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 #import "AFURLSessionManager.h" -#endif + +@interface AFRefreshControlNotificationObserver : NSObject +@property (readonly, nonatomic, weak) UIRefreshControl *refreshControl; +- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl; + +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; + +@end @implementation UIRefreshControl (AFNetworking) -#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 +- (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]; @@ -41,36 +71,19 @@ - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { [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 beginRefreshing]; + [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 endRefreshing]; - } - } -} -#endif - -- (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation { - NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - - [notificationCenter removeObserver:self name:AFNetworkingOperationDidStartNotification object:nil]; - [notificationCenter removeObserver:self name:AFNetworkingOperationDidFinishNotification object:nil]; - - if (operation) { - if (![operation isFinished]) { - if ([operation isExecuting]) { - [self beginRefreshing]; - } else { - [self endRefreshing]; - } - - [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingOperationDidStartNotification object:operation]; - [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingOperationDidFinishNotification object:operation]; + [self.refreshControl endRefreshing]; } +#pragma clang diagnostic pop } } @@ -78,16 +91,32 @@ - (void)setRefreshingWithStateOfOperation:(AFURLConnectionOperation *)operation - (void)af_beginRefreshing { dispatch_async(dispatch_get_main_queue(), ^{ - [self beginRefreshing]; +#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(), ^{ - [self endRefreshing]; +#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/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h index 202e8f4e..ef68e19b 100644 --- a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h @@ -1,6 +1,5 @@ // UIWebView+AFNetworking.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2015 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 @@ -22,44 +21,40 @@ #import -#import +#import -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS #import -@class AFHTTPRequestSerializer, AFHTTPResponseSerializer; -@protocol AFURLRequestSerialization, AFURLResponseSerialization; +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 request serializer used to serialize requests made with the `-loadRequest:...` category methods. By default, this is an instance of `AFHTTPRequestSerializer`. - */ -@property (nonatomic, strong) AFHTTPRequestSerializer * requestSerializer; - -/** - The response serializer used to serialize responses made with the `-loadRequest:...` category methods. By default, this is an instance of `AFHTTPResponseSerializer`. + The session manager used to download all requests. */ -@property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; +@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 block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread. + @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 request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred. + @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:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress - success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success - failure:(void (^)(NSError *error))failure; + 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. @@ -67,17 +62,19 @@ @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 block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread. +@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 request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred. + @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:(NSString *)MIMEType - textEncodingName:(NSString *)textEncodingName - progress:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress - success:(NSData * (^)(NSHTTPURLResponse *response, NSData *data))success - failure:(void (^)(NSError *error))failure; + 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 -#endif +NS_ASSUME_NONNULL_END + +#endif \ No newline at end of file diff --git a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m index 525d02ae..4aa4640d 100644 --- a/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m +++ b/OHHTTPStubs/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m @@ -1,6 +1,5 @@ // UIWebView+AFNetworking.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2015 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 @@ -24,24 +23,24 @@ #import -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS -#import "AFHTTPRequestOperation.h" +#import "AFHTTPSessionManager.h" #import "AFURLResponseSerialization.h" #import "AFURLRequestSerialization.h" @interface UIWebView (_AFNetworking) -@property (readwrite, nonatomic, strong, setter = af_setHTTPRequestOperation:) AFHTTPRequestOperation *af_HTTPRequestOperation; +@property (readwrite, nonatomic, strong, setter = af_setURLSessionTask:) NSURLSessionDataTask *af_URLSessionTask; @end @implementation UIWebView (_AFNetworking) -- (AFHTTPRequestOperation *)af_HTTPRequestOperation { - return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, @selector(af_HTTPRequestOperation)); +- (NSURLSessionDataTask *)af_URLSessionTask { + return (NSURLSessionDataTask *)objc_getAssociatedObject(self, @selector(af_URLSessionTask)); } -- (void)af_setHTTPRequestOperation:(AFHTTPRequestOperation *)operation { - objc_setAssociatedObject(self, @selector(af_HTTPRequestOperation), operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +- (void)af_setURLSessionTask:(NSURLSessionDataTask *)af_URLSessionTask { + objc_setAssociatedObject(self, @selector(af_URLSessionTask), af_URLSessionTask, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } @end @@ -50,21 +49,23 @@ - (void)af_setHTTPRequestOperation:(AFHTTPRequestOperation *)operation { @implementation UIWebView (AFNetworking) -- (AFHTTPRequestSerializer *)requestSerializer { - static AFHTTPRequestSerializer *_af_defaultRequestSerializer = nil; +- (AFHTTPSessionManager *)sessionManager { + static AFHTTPSessionManager *_af_defaultHTTPSessionManager = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - _af_defaultRequestSerializer = [AFHTTPRequestSerializer serializer]; + _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(requestSerializer)) ?: _af_defaultRequestSerializer; + return objc_getAssociatedObject(self, @selector(sessionManager)) ?: _af_defaultHTTPSessionManager; #pragma clang diagnostic pop } -- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { - objc_setAssociatedObject(self, @selector(requestSerializer), requestSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +- (void)setSessionManager:(AFHTTPSessionManager *)sessionManager { + objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (AFHTTPResponseSerializer *)responseSerializer { @@ -87,7 +88,7 @@ - (void)setResponseSerializer:(AFHTTPResponseSerializer #endif +#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 diff --git a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs Mac Tests/Pods-OHHTTPStubs Mac Tests-acknowledgements.markdown b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs Mac Tests/Pods-OHHTTPStubs Mac Tests-acknowledgements.markdown index 59a17508..779c02f8 100644 --- a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs Mac Tests/Pods-OHHTTPStubs Mac Tests-acknowledgements.markdown +++ b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs Mac Tests/Pods-OHHTTPStubs Mac Tests-acknowledgements.markdown @@ -3,7 +3,7 @@ This application makes use of the following third party libraries: ## AFNetworking -Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com/) +Copyright (c) 2011–2015 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 diff --git a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs Mac Tests/Pods-OHHTTPStubs Mac Tests-acknowledgements.plist b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs Mac Tests/Pods-OHHTTPStubs Mac Tests-acknowledgements.plist index 899e8ae4..fcc49f07 100644 --- a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs Mac Tests/Pods-OHHTTPStubs Mac Tests-acknowledgements.plist +++ b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs Mac Tests/Pods-OHHTTPStubs Mac Tests-acknowledgements.plist @@ -14,7 +14,7 @@ FooterText - Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com/) + Copyright (c) 2011–2015 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 diff --git a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Fmk Tests-AFNetworking/Pods-OHHTTPStubs iOS Fmk Tests-AFNetworking-prefix.pch b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Fmk Tests-AFNetworking/Pods-OHHTTPStubs iOS Fmk Tests-AFNetworking-prefix.pch index aa992a4a..b52cf0d6 100644 --- a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Fmk Tests-AFNetworking/Pods-OHHTTPStubs iOS Fmk Tests-AFNetworking-prefix.pch +++ b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Fmk Tests-AFNetworking/Pods-OHHTTPStubs iOS Fmk Tests-AFNetworking-prefix.pch @@ -2,3 +2,14 @@ #import #endif +#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 diff --git a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Fmk Tests/Pods-OHHTTPStubs iOS Fmk Tests-acknowledgements.markdown b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Fmk Tests/Pods-OHHTTPStubs iOS Fmk Tests-acknowledgements.markdown index 59a17508..779c02f8 100644 --- a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Fmk Tests/Pods-OHHTTPStubs iOS Fmk Tests-acknowledgements.markdown +++ b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Fmk Tests/Pods-OHHTTPStubs iOS Fmk Tests-acknowledgements.markdown @@ -3,7 +3,7 @@ This application makes use of the following third party libraries: ## AFNetworking -Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com/) +Copyright (c) 2011–2015 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 diff --git a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Fmk Tests/Pods-OHHTTPStubs iOS Fmk Tests-acknowledgements.plist b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Fmk Tests/Pods-OHHTTPStubs iOS Fmk Tests-acknowledgements.plist index 899e8ae4..fcc49f07 100644 --- a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Fmk Tests/Pods-OHHTTPStubs iOS Fmk Tests-acknowledgements.plist +++ b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Fmk Tests/Pods-OHHTTPStubs iOS Fmk Tests-acknowledgements.plist @@ -14,7 +14,7 @@ FooterText - Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com/) + Copyright (c) 2011–2015 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 diff --git a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Lib Tests-AFNetworking/Pods-OHHTTPStubs iOS Lib Tests-AFNetworking-prefix.pch b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Lib Tests-AFNetworking/Pods-OHHTTPStubs iOS Lib Tests-AFNetworking-prefix.pch index aa992a4a..b52cf0d6 100644 --- a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Lib Tests-AFNetworking/Pods-OHHTTPStubs iOS Lib Tests-AFNetworking-prefix.pch +++ b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Lib Tests-AFNetworking/Pods-OHHTTPStubs iOS Lib Tests-AFNetworking-prefix.pch @@ -2,3 +2,14 @@ #import #endif +#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 diff --git a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Lib Tests/Pods-OHHTTPStubs iOS Lib Tests-acknowledgements.markdown b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Lib Tests/Pods-OHHTTPStubs iOS Lib Tests-acknowledgements.markdown index 59a17508..779c02f8 100644 --- a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Lib Tests/Pods-OHHTTPStubs iOS Lib Tests-acknowledgements.markdown +++ b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Lib Tests/Pods-OHHTTPStubs iOS Lib Tests-acknowledgements.markdown @@ -3,7 +3,7 @@ This application makes use of the following third party libraries: ## AFNetworking -Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com/) +Copyright (c) 2011–2015 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 diff --git a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Lib Tests/Pods-OHHTTPStubs iOS Lib Tests-acknowledgements.plist b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Lib Tests/Pods-OHHTTPStubs iOS Lib Tests-acknowledgements.plist index 899e8ae4..fcc49f07 100644 --- a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Lib Tests/Pods-OHHTTPStubs iOS Lib Tests-acknowledgements.plist +++ b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs iOS Lib Tests/Pods-OHHTTPStubs iOS Lib Tests-acknowledgements.plist @@ -14,7 +14,7 @@ FooterText - Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com/) + Copyright (c) 2011–2015 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 diff --git a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking/Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking-dummy.m b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking/Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking-dummy.m new file mode 100644 index 00000000..965cc8b9 --- /dev/null +++ b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking/Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_OHHTTPStubs_tvOS_Fmk_Tests_AFNetworking : NSObject +@end +@implementation PodsDummy_Pods_OHHTTPStubs_tvOS_Fmk_Tests_AFNetworking +@end diff --git a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking/Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking-prefix.pch b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking/Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking-prefix.pch new file mode 100644 index 00000000..b52cf0d6 --- /dev/null +++ b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking/Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking-prefix.pch @@ -0,0 +1,15 @@ +#ifdef __OBJC__ +#import +#endif + +#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 diff --git a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking/Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking.xcconfig b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking/Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking.xcconfig new file mode 100644 index 00000000..b0cd17d6 --- /dev/null +++ b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking/Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking.xcconfig @@ -0,0 +1,5 @@ +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Private/AFNetworking" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/AFNetworking" +OTHER_LDFLAGS = -framework "Security" -framework "SystemConfiguration" +PODS_ROOT = ${SRCROOT} +SKIP_INSTALL = YES \ No newline at end of file diff --git a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests-acknowledgements.markdown b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests-acknowledgements.markdown new file mode 100644 index 00000000..779c02f8 --- /dev/null +++ b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests-acknowledgements.markdown @@ -0,0 +1,26 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## AFNetworking + +Copyright (c) 2011–2015 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. + +Generated by CocoaPods - http://cocoapods.org diff --git a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests-acknowledgements.plist b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests-acknowledgements.plist new file mode 100644 index 00000000..fcc49f07 --- /dev/null +++ b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests-acknowledgements.plist @@ -0,0 +1,56 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2011–2015 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. + + Title + AFNetworking + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - http://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests-dummy.m b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests-dummy.m new file mode 100644 index 00000000..0f6b8c2f --- /dev/null +++ b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_OHHTTPStubs_tvOS_Fmk_Tests : NSObject +@end +@implementation PodsDummy_Pods_OHHTTPStubs_tvOS_Fmk_Tests +@end diff --git a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests-frameworks.sh b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests-frameworks.sh new file mode 100755 index 00000000..6f763443 --- /dev/null +++ b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests-frameworks.sh @@ -0,0 +1,84 @@ +#!/bin/sh +set -e + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" + +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink "${source}")" + fi + + # use filter instead of exclude so missing patterns dont' throw errors + echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identitiy + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements \"$1\"" + /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} --preserve-metadata=identifier,entitlements "$1" + fi +} + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + # Get architectures for current file + archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" + stripped="" + for arch in $archs; do + if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" || exit 1 + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi +} + diff --git a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests-resources.sh b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests-resources.sh new file mode 100755 index 00000000..16774fb4 --- /dev/null +++ b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests-resources.sh @@ -0,0 +1,95 @@ +#!/bin/sh +set -e + +mkdir -p "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +realpath() { + DIRECTORY="$(cd "${1%/*}" && pwd)" + FILENAME="${1##*/}" + echo "$DIRECTORY/$FILENAME" +} + +install_resource() +{ + case $1 in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc ${PODS_ROOT}/$1 --sdk ${SDKROOT}" + ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc" "${PODS_ROOT}/$1" --sdk "${SDKROOT}" + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib ${PODS_ROOT}/$1 --sdk ${SDKROOT}" + ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib" "${PODS_ROOT}/$1" --sdk "${SDKROOT}" + ;; + *.framework) + echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync -av ${PODS_ROOT}/$1 ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + rsync -av "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1"`.mom\"" + xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodeld`.momd\"" + xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodeld`.momd" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcmappingmodel`.cdm\"" + xcrun mapc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE=$(realpath "${PODS_ROOT}/$1") + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + /*) + echo "$1" + echo "$1" >> "$RESOURCES_TO_COPY" + ;; + *) + echo "${PODS_ROOT}/$1" + echo "${PODS_ROOT}/$1" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then + mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi +rm -f "$RESOURCES_TO_COPY" + +if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ] +then + case "${TARGETED_DEVICE_FAMILY}" in + 1,2) + TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" + ;; + 1) + TARGET_DEVICE_ARGS="--target-device iphone" + ;; + 2) + TARGET_DEVICE_ARGS="--target-device ipad" + ;; + *) + TARGET_DEVICE_ARGS="--target-device mac" + ;; + esac + + # Find all other xcassets (this unfortunately includes those of path pods and other targets). + OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) + while read line; do + if [[ $line != "`realpath $PODS_ROOT`*" ]]; then + XCASSET_FILES+=("$line") + fi + done <<<"$OTHER_XCASSETS" + + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${IPHONEOS_DEPLOYMENT_TARGET}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi diff --git a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests.debug.xcconfig b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests.debug.xcconfig new file mode 100644 index 00000000..d47ce568 --- /dev/null +++ b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests.debug.xcconfig @@ -0,0 +1,5 @@ +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/AFNetworking" +OTHER_CFLAGS = $(inherited) -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/AFNetworking" +OTHER_LDFLAGS = $(inherited) -ObjC -l"Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking" -framework "Security" -framework "SystemConfiguration" +PODS_ROOT = ${SRCROOT}/Pods \ No newline at end of file diff --git a/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests.release.xcconfig b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests.release.xcconfig new file mode 100644 index 00000000..d47ce568 --- /dev/null +++ b/OHHTTPStubs/Pods/Target Support Files/Pods-OHHTTPStubs tvOS Fmk Tests/Pods-OHHTTPStubs tvOS Fmk Tests.release.xcconfig @@ -0,0 +1,5 @@ +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/AFNetworking" +OTHER_CFLAGS = $(inherited) -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/AFNetworking" +OTHER_LDFLAGS = $(inherited) -ObjC -l"Pods-OHHTTPStubs tvOS Fmk Tests-AFNetworking" -framework "Security" -framework "SystemConfiguration" +PODS_ROOT = ${SRCROOT}/Pods \ No newline at end of file diff --git a/OHHTTPStubs/UnitTests/Test Suites/AFNetworkingTests.m b/OHHTTPStubs/UnitTests/Test Suites/AFNetworkingTests.m index 229a4f46..8363f694 100644 --- a/OHHTTPStubs/UnitTests/Test Suites/AFNetworkingTests.m +++ b/OHHTTPStubs/UnitTests/Test Suites/AFNetworkingTests.m @@ -23,6 +23,7 @@ ***********************************************************************************/ #import +#import #if OHHTTPSTUBS_USE_STATIC_LIBRARY #import "OHHTTPStubs.h" @@ -31,7 +32,7 @@ @import OHHTTPStubs; #endif -#import "AFHTTPRequestOperation.h" +#import "AFHTTPSessionManager.h" static const NSTimeInterval kResponseTimeTolerence = 1.0; @@ -59,18 +60,18 @@ -(void)test_AFHTTPRequestOperation_success XCTestExpectation* expectation = [self expectationWithDescription:@"AFHTTPRequestOperation request finished"]; - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - AFHTTPRequestOperation* op = [[AFHTTPRequestOperation alloc] initWithRequest:req]; - [op setResponseSerializer:[AFHTTPResponseSerializer serializer]]; + NSURL *URL = [NSURL URLWithString:@"http://www.iana.org/domains/example/"]; + __block __strong id response = nil; - [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { + AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; + [manager setResponseSerializer:[AFHTTPResponseSerializer serializer]]; + [manager GET:URL.absoluteString parameters:nil success:^(NSURLSessionTask *task, id responseObject) { response = responseObject; // keep strong reference [expectation fulfill]; - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + } failure:^(NSURLSessionTask *operation, NSError *error) { XCTFail(@"Unexpected network failure"); [expectation fulfill]; }]; - [op start]; [self waitForExpectationsWithTimeout:kRequestTime+kResponseTime+kResponseTimeTolerence handler:nil]; @@ -91,29 +92,28 @@ -(void)test_AFHTTPRequestOperation_multiple_choices XCTestExpectation* expectation = [self expectationWithDescription:@"AFHTTPRequestOperation request finished"]; - NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - AFHTTPRequestOperation* op = [[AFHTTPRequestOperation alloc] initWithRequest:req]; + NSURL *URL = [NSURL URLWithString:@"http://www.iana.org/domains/example/"]; + AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; AFHTTPResponseSerializer* serializer = [AFHTTPResponseSerializer serializer]; [serializer setAcceptableStatusCodes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 101)]]; - [op setResponseSerializer:serializer]; - + [manager setResponseSerializer:serializer]; + __block __strong id response = nil; - [op setRedirectResponseBlock:^NSURLRequest *(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse) { - if (redirectResponse == nil) { + [manager setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest * (NSURLSession * session, NSURLSessionTask * task, NSURLResponse * response, NSURLRequest * request) { + if (response == nil) { return request; } XCTFail(@"Unexpected redirect"); return nil; }]; - [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { + [manager GET:URL.absoluteString parameters:nil success:^(NSURLSessionTask *task, id responseObject) { response = responseObject; // keep strong reference [expectation fulfill]; - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + } failure:^(NSURLSessionTask *operation, NSError *error) { XCTFail(@"Unexpected network failure"); [expectation fulfill]; }]; - [op start]; [self waitForExpectationsWithTimeout:kRequestTime+kResponseTime+kResponseTimeTolerence handler:nil]; @@ -136,12 +136,12 @@ -(void)test_AFHTTPRequestOperation_redirect XCTestExpectation* expectation = [self expectationWithDescription:@"AFHTTPRequestOperation request finished"]; NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.iana.org/domains/example/"]]; - AFHTTPRequestOperation* op = [[AFHTTPRequestOperation alloc] initWithRequest:req]; - [op setResponseSerializer:[AFHTTPResponseSerializer serializer]]; + AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; + [manager setResponseSerializer:[AFHTTPResponseSerializer serializer]]; __block __strong NSURL* url = nil; - [op setRedirectResponseBlock:^NSURLRequest *(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse) { - if (redirectResponse == nil) { + [manager setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest * (NSURLSession * session, NSURLSessionTask * task, NSURLResponse * response, NSURLRequest * request) { + if (response == nil) { return request; } url = request.URL; @@ -149,14 +149,13 @@ -(void)test_AFHTTPRequestOperation_redirect return nil; }]; - [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { + [manager GET:req.URL.absoluteString parameters:nil success:^(NSURLSessionTask *task, id responseObject) { XCTFail(@"Unexpected response"); [expectation fulfill]; - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + } failure:^(NSURLSessionTask *operation, NSError *error) { XCTFail(@"Unexpected network failure"); [expectation fulfill]; }]; - [op start]; [self waitForExpectationsWithTimeout:kRequestTime+kResponseTime+kResponseTimeTolerence handler:nil]; @@ -172,7 +171,9 @@ -(void)test_AFHTTPRequestOperation_redirect // Compile this only if SDK version (…MAX_ALLOWED) is iOS7+/10.9+ because NSURLSession is a class only known starting these SDKs // (this code won't compile if we use an eariler SDKs, like when building with Xcode4) #if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) \ - || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) + || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) \ + || (defined(__TV_OS_VERSION_MIN_REQUIRED) || defined(__WATCH_OS_VERSION_MIN_REQUIRED)) + #import "AFHTTPSessionManager.h" diff --git a/OHHTTPStubs/UnitTests/Test Suites/NSURLConnectionDelegateTests.m b/OHHTTPStubs/UnitTests/Test Suites/NSURLConnectionDelegateTests.m index 3fa370db..90046781 100644 --- a/OHHTTPStubs/UnitTests/Test Suites/NSURLConnectionDelegateTests.m +++ b/OHHTTPStubs/UnitTests/Test Suites/NSURLConnectionDelegateTests.m @@ -22,6 +22,10 @@ * ***********************************************************************************/ +#import +// tvOS & WatchOS deprecate use of NSURLConnection but these tests are based on it +#if (!defined(__TV_OS_VERSION_MIN_REQUIRED) && !defined(__WATCH_OS_VERSION_MIN_REQUIRED)) + #import #if OHHTTPSTUBS_USE_STATIC_LIBRARY @@ -397,3 +401,5 @@ - (void)test_NSURLConnection_redirected } @end + +#endif diff --git a/OHHTTPStubs/UnitTests/Test Suites/NSURLConnectionTests.m b/OHHTTPStubs/UnitTests/Test Suites/NSURLConnectionTests.m index 842591d6..7e2baf98 100644 --- a/OHHTTPStubs/UnitTests/Test Suites/NSURLConnectionTests.m +++ b/OHHTTPStubs/UnitTests/Test Suites/NSURLConnectionTests.m @@ -22,6 +22,10 @@ * ***********************************************************************************/ +#import +// tvOS & WatchOS deprecate use of NSURLConnection but these tests are based on it +#if (!defined(__TV_OS_VERSION_MIN_REQUIRED) && !defined(__WATCH_OS_VERSION_MIN_REQUIRED)) + #import #if OHHTTPSTUBS_USE_STATIC_LIBRARY @@ -190,3 +194,5 @@ -(void)test_NSURLConnection_sendMultipleAsyncronousRequests_parallelQueue @end + +#endif diff --git a/OHHTTPStubs/UnitTests/Test Suites/NSURLSessionTests.m b/OHHTTPStubs/UnitTests/Test Suites/NSURLSessionTests.m index b274ba86..a4cb91f4 100644 --- a/OHHTTPStubs/UnitTests/Test Suites/NSURLSessionTests.m +++ b/OHHTTPStubs/UnitTests/Test Suites/NSURLSessionTests.m @@ -22,11 +22,12 @@ * ***********************************************************************************/ - +#import // Compile this only if SDK version (…MAX_ALLOWED) is iOS7+/10.9+ because NSURLSession is a class only known starting these SDKs // (this code won't compile if we use an eariler SDKs, like when building with Xcode4) #if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) \ - || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) + || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) \ + || (defined(__TV_OS_VERSION_MIN_REQUIRED) || defined(__WATCH_OS_VERSION_MIN_REQUIRED)) #import diff --git a/OHHTTPStubs/UnitTests/Test Suites/NilValuesTests.m b/OHHTTPStubs/UnitTests/Test Suites/NilValuesTests.m index d3cc8d08..534f36a0 100644 --- a/OHHTTPStubs/UnitTests/Test Suites/NilValuesTests.m +++ b/OHHTTPStubs/UnitTests/Test Suites/NilValuesTests.m @@ -22,6 +22,10 @@ * ***********************************************************************************/ +#import +// tvOS & WatchOS deprecate use of NSURLConnection but these tests are based on it +#if (!defined(__TV_OS_VERSION_MIN_REQUIRED) && !defined(__WATCH_OS_VERSION_MIN_REQUIRED)) + #import #if OHHTTPSTUBS_USE_STATIC_LIBRARY @@ -272,3 +276,5 @@ - (void)test_NilURLAndCookieHandlingDisabled } @end + +#endif diff --git a/OHHTTPStubs/UnitTests/Test Suites/TimingTests.m b/OHHTTPStubs/UnitTests/Test Suites/TimingTests.m index aa1dc0c0..4133874e 100644 --- a/OHHTTPStubs/UnitTests/Test Suites/TimingTests.m +++ b/OHHTTPStubs/UnitTests/Test Suites/TimingTests.m @@ -22,6 +22,9 @@ * ***********************************************************************************/ +#import +// tvOS & WatchOS deprecate use of NSURLConnection but these tests are based on it +#if (!defined(__TV_OS_VERSION_MIN_REQUIRED) && !defined(__WATCH_OS_VERSION_MIN_REQUIRED)) #import @@ -165,3 +168,5 @@ -(void)test_VeryLongData_RequestTime1_ResponseTime0 } @end + +#endif diff --git a/Rakefile b/Rakefile index 6965f7db..074e4b39 100644 --- a/Rakefile +++ b/Rakefile @@ -3,15 +3,22 @@ desc 'Build an iOS scheme' task :ios, [:scheme, :ios_version, :action] do |_,args| destination = "platform=iOS Simulator,name=iPhone 5,OS=#{args.ios_version}" - build("OHHTTPStubs #{args.scheme}", "iphonesimulator", destination, args.action) + build("OHHTTPStubs #{args.scheme}", destination, args.action) end desc 'Build an OSX scheme' task :osx, [:scheme, :arch, :action] do |_,args| destination = "platform=OS X,arch=#{args.arch}" - build("OHHTTPStubs #{args.scheme}", "macosx", destination, args.action) + build("OHHTTPStubs #{args.scheme}", destination, args.action) end +desc 'Build a tvOS scheme' +task :tvos, [:scheme, :tvos_version, :action] do |_,args| + destination = "platform=tvOS Simulator,name=Apple TV 1080p,OS=#{args.tvos_version}" + build("OHHTTPStubs #{args.scheme}", destination, args.action) +end + + desc 'List installed simulators' task :simlist do sh 'xcrun simctl list' @@ -30,7 +37,7 @@ end # Build the xcodebuild command and run it -def build(scheme, sdk, destination, action) +def build(scheme, destination, action) puts <<-ANNOUNCE ============================= | Action: #{action} @@ -44,7 +51,6 @@ def build(scheme, sdk, destination, action) xcodebuild -workspace OHHTTPStubs/OHHTTPStubs.xcworkspace -scheme "#{scheme}" - -sdk #{sdk} -configuration Debug ONLY_ACTIVE_ARCH=NO -destination '#{destination}'