diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..45091a9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +# Xcode +# +build/ +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata +*.xccheckout +*.moved-aside +DerivedData +*.hmap +*.ipa +*.xcuserstate + +## Other +*.xcscmblueprint + +# CocoaPods +# +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control +# +# Pods/ + +.idea diff --git a/Astro.podspec b/Astro.podspec new file mode 100644 index 0000000..c147595 --- /dev/null +++ b/Astro.podspec @@ -0,0 +1,63 @@ +# +# Be sure to run `pod lib lint Astro.podspec' to ensure this is a +# valid spec before submitting. +# +# Any lines starting with a # are optional, but their use is encouraged +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html +# + +Pod::Spec.new do |s| + s.name = "Astro" + s.version = "1.0.0" + s.summary = "A RoboPod containing a small collection of utilities for project reuse" + s.homepage = "https://RobotsAndPencils.com" +# s.actualHomepage = "https://github.com/RobotsAndPencils/Astro" <-- we needed a publicly accessible s.homepage or else we couldn't publish to our own repository + s.license = { + :type => 'MIT', + :text => <<-LICENSE +Copyright (c) 2015 Robots and Pencils, Inc. All rights reserved. +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: +Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +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. + LICENSE + } + s.authors = { + "Chad Sykes" => "Chad.Sykes@RobotsAndPencils.com", + "Colin Gislason" => "Colin.Gislason@RobotsAndPencils.com", + "Dominic Pepin" => "Dominic.Pepin@RobotsAndPencils.com", + "Michael Beaureguard" => "Michael.Beauregard@RobotsAndPencils.com" + } + s.source = { :git => "git@github.com:RobotsAndPencils/Astro.git", :tag => s.version.to_s } + + s.ios.deployment_target = '8.0' + s.platform = :ios, '8.0' + s.requires_arc = true + + s.subspec 'Logging' do | log | + log.source_files = 'Astro/Logging/**/*.swift' + end + + s.subspec 'Networking' do | net | + net.source_files = 'Astro/Networking/**/*.swift' + net.dependency 'Astro/Logging' + net.dependency 'Alamofire', '~> 3.3' + net.dependency 'Freddy', '~> 2.0' + net.dependency 'SwiftTask', '5.0' + end + + s.subspec 'Security' do | security | + security.source_files = 'Astro/Security/**/*.swift' + security.dependency 'Astro/Logging' + end + + s.subspec 'UI' do | ui | + ui.source_files = 'Astro/UI/**/*.swift' + ui.frameworks = 'UIKit' + end + + s.subspec 'Utils' do | utils | + utils.source_files = 'Astro/Utils/**/*.swift' + end + +end diff --git a/Astro.xcodeproj/project.pbxproj b/Astro.xcodeproj/project.pbxproj new file mode 100644 index 0000000..8ecdf8a --- /dev/null +++ b/Astro.xcodeproj/project.pbxproj @@ -0,0 +1,721 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 2E93419DA70B2DFA04A8D50E /* HTTPStatusCodeSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E934B3DCE343BE7D9CECCCD /* HTTPStatusCodeSpec.swift */; }; + 2E9342BC5B4FE98B693084A6 /* UIView+AstroGadgetsSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E93428725B0114A0FC9064E /* UIView+AstroGadgetsSpec.swift */; }; + 2E9345EE0AEB18FB859A8D06 /* UIView+AstroGadgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E93420DB2E8AE3339E2E9C0 /* UIView+AstroGadgets.swift */; }; + 2E93487124A5E044E0199250 /* HTTPStatusCode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E934F99FFAF39F046F75750 /* HTTPStatusCode.swift */; }; + 2E934B8A416AF015C76347DC /* UIViewController+AstroGadgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E9348D0FB90D68FC7E5C3D7 /* UIViewController+AstroGadgets.swift */; }; + 2E934D1B02F8932284DCF220 /* UIViewController+AstroGadgetsSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E9348C107F407A4402AB69F /* UIViewController+AstroGadgetsSpec.swift */; }; + 3F78B5501CC35D4900A0E30C /* Queue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F78B54F1CC35D4900A0E30C /* Queue.swift */; }; + 3F8E16F51CCA801000E0B4DD /* NetworkServiceSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F8E16F41CCA801000E0B4DD /* NetworkServiceSpec.swift */; }; + 3F8E16FA1CCA843100E0B4DD /* NetworkService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F8E16F71CCA843100E0B4DD /* NetworkService.swift */; }; + 3F8E16FB1CCA843100E0B4DD /* Route.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F8E16F81CCA843100E0B4DD /* Route.swift */; }; + 3FCD95D71CCC2D3400A5442F /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FCD95D61CCC2D3400A5442F /* User.swift */; }; + 535DF10A1C87864E00961785 /* LayoutLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 535DF1091C87864E00961785 /* LayoutLabel.swift */; }; + 535DF10C1C87886500961785 /* LayoutLabelSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 535DF10B1C87886500961785 /* LayoutLabelSpec.swift */; }; + 63379D7F1C063B8800DDD95B /* KeychainAccess.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63379D7E1C063B8800DDD95B /* KeychainAccess.swift */; }; + 63379D811C063BA900DDD95B /* KeychainAccessSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63379D801C063BA900DDD95B /* KeychainAccessSpec.swift */; }; + 6367D7851C0BCC6C0045BDFE /* testdata.json in Resources */ = {isa = PBXBuildFile; fileRef = 6367D7841C0BCC6C0045BDFE /* testdata.json */; }; + 638C62521BD454FD0004ECE1 /* Astro.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 638C62471BD454FD0004ECE1 /* Astro.framework */; }; + B69726CE1BD9162F0047EEB9 /* LoggerSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = B69726CD1BD9162F0047EEB9 /* LoggerSpec.swift */; }; + BD62EA481C929BF0004A02DF /* EnumCountable.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD62EA471C929BF0004A02DF /* EnumCountable.swift */; }; + BD62EA4B1C929C1C004A02DF /* EnumCountableSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD62EA4A1C929C1C004A02DF /* EnumCountableSpec.swift */; }; + CA5380CB1C5C195900204A68 /* UIColor+AstroGadgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA5380CA1C5C195900204A68 /* UIColor+AstroGadgets.swift */; }; + CA5380CD1C5C196E00204A68 /* UIColor+AstroGadgetsSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA5380CC1C5C196E00204A68 /* UIColor+AstroGadgetsSpec.swift */; }; + D0C3176529877E28CFD27E77 /* Log.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0C31A257874127AD224738D /* Log.swift */; }; + D6F831A48F327D5367262464 /* Pods_AstroTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2D24B772E4EC6454D9C2C893 /* Pods_AstroTests.framework */; }; + F454FB4E1A6FC16378B23DF1 /* Pods_Astro.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 273FFD8472B2BF5BD8B6DF9F /* Pods_Astro.framework */; }; + E62F9D221D623675005402BF /* ReusableViewSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = E62F9D211D623675005402BF /* ReusableViewSpec.swift */; }; + E62F9D1C1D62264F005402BF /* UICollectionView+AstroGadgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = E62F9D1B1D62264F005402BF /* UICollectionView+AstroGadgets.swift */; }; + E62F9D1E1D6227DE005402BF /* UITableView+AstroGadgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = E62F9D1D1D6227DE005402BF /* UITableView+AstroGadgets.swift */; }; + E665B02B1D35BB4B0099C89E /* NibLoadableView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E665B02A1D35BB4B0099C89E /* NibLoadableView.swift */; }; + E6D5F8841D35B55600CB4D5F /* ReusableView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6D5F8831D35B55600CB4D5F /* ReusableView.swift */; }; + E6F32EE51D6264FE00D31F64 /* NibLoadableViewSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6F32EE41D6264FE00D31F64 /* NibLoadableViewSpec.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 638C62531BD454FD0004ECE1 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 638C623E1BD454FD0004ECE1 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 638C62461BD454FD0004ECE1; + remoteInfo = Astro; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 1FF6722A4F1235471A201686 /* Pods-AstroTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AstroTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests.release.xcconfig"; sourceTree = ""; }; + 273FFD8472B2BF5BD8B6DF9F /* Pods_Astro.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Astro.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 2D24B772E4EC6454D9C2C893 /* Pods_AstroTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_AstroTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 2E93420DB2E8AE3339E2E9C0 /* UIView+AstroGadgets.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIView+AstroGadgets.swift"; sourceTree = ""; }; + 2E93428725B0114A0FC9064E /* UIView+AstroGadgetsSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIView+AstroGadgetsSpec.swift"; sourceTree = ""; }; + 2E9348C107F407A4402AB69F /* UIViewController+AstroGadgetsSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIViewController+AstroGadgetsSpec.swift"; sourceTree = ""; }; + 2E9348D0FB90D68FC7E5C3D7 /* UIViewController+AstroGadgets.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIViewController+AstroGadgets.swift"; sourceTree = ""; }; + 2E934B3DCE343BE7D9CECCCD /* HTTPStatusCodeSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HTTPStatusCodeSpec.swift; sourceTree = ""; }; + 2E934F99FFAF39F046F75750 /* HTTPStatusCode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HTTPStatusCode.swift; sourceTree = ""; }; + 3F78B54F1CC35D4900A0E30C /* Queue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Queue.swift; path = Utils/Queue.swift; sourceTree = ""; }; + 3F8E16F41CCA801000E0B4DD /* NetworkServiceSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NetworkServiceSpec.swift; sourceTree = ""; }; + 3F8E16F71CCA843100E0B4DD /* NetworkService.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NetworkService.swift; sourceTree = ""; }; + 3F8E16F81CCA843100E0B4DD /* Route.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Route.swift; sourceTree = ""; }; + 3FCD95D61CCC2D3400A5442F /* User.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; + 535DF1091C87864E00961785 /* LayoutLabel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LayoutLabel.swift; sourceTree = ""; }; + 535DF10B1C87886500961785 /* LayoutLabelSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LayoutLabelSpec.swift; sourceTree = ""; }; + 63379D7E1C063B8800DDD95B /* KeychainAccess.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = KeychainAccess.swift; path = Security/KeychainAccess.swift; sourceTree = ""; }; + 63379D801C063BA900DDD95B /* KeychainAccessSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = KeychainAccessSpec.swift; path = Security/KeychainAccessSpec.swift; sourceTree = ""; }; + 6367D7841C0BCC6C0045BDFE /* testdata.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = testdata.json; sourceTree = ""; }; + 638C62471BD454FD0004ECE1 /* Astro.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Astro.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 638C624C1BD454FD0004ECE1 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 638C62511BD454FD0004ECE1 /* AstroTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = AstroTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 638C62581BD454FD0004ECE1 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 7CC6FB4E4A3FE9D093738307 /* Pods-AstroTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AstroTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests.debug.xcconfig"; sourceTree = ""; }; + B69726CD1BD9162F0047EEB9 /* LoggerSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LoggerSpec.swift; sourceTree = ""; }; + BD62EA471C929BF0004A02DF /* EnumCountable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = EnumCountable.swift; path = Utils/EnumCountable.swift; sourceTree = ""; }; + BD62EA4A1C929C1C004A02DF /* EnumCountableSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = EnumCountableSpec.swift; path = Utils/EnumCountableSpec.swift; sourceTree = ""; }; + BD95704572604E86D00F715F /* Pods-Astro.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Astro.release.xcconfig"; path = "Pods/Target Support Files/Pods-Astro/Pods-Astro.release.xcconfig"; sourceTree = ""; }; + CA5380CA1C5C195900204A68 /* UIColor+AstroGadgets.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIColor+AstroGadgets.swift"; sourceTree = ""; }; + CA5380CC1C5C196E00204A68 /* UIColor+AstroGadgetsSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIColor+AstroGadgetsSpec.swift"; sourceTree = ""; }; + D0C31A257874127AD224738D /* Log.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Log.swift; sourceTree = ""; }; + D5D8E2A7279FA75989658B29 /* Pods-Astro.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Astro.debug.xcconfig"; path = "Pods/Target Support Files/Pods-Astro/Pods-Astro.debug.xcconfig"; sourceTree = ""; }; + E62F9D211D623675005402BF /* ReusableViewSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReusableViewSpec.swift; sourceTree = ""; }; + E62F9D1B1D62264F005402BF /* UICollectionView+AstroGadgets.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UICollectionView+AstroGadgets.swift"; sourceTree = ""; }; + E62F9D1D1D6227DE005402BF /* UITableView+AstroGadgets.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UITableView+AstroGadgets.swift"; sourceTree = ""; }; + E665B02A1D35BB4B0099C89E /* NibLoadableView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NibLoadableView.swift; sourceTree = ""; }; + E6D5F8831D35B55600CB4D5F /* ReusableView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReusableView.swift; sourceTree = ""; }; + E6F32EE41D6264FE00D31F64 /* NibLoadableViewSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NibLoadableViewSpec.swift; sourceTree = ""; }; + FB15C2DB1FFCE31DEC4C7201 /* Pods-AstroTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AstroTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests.release.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 638C62431BD454FD0004ECE1 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + F454FB4E1A6FC16378B23DF1 /* Pods_Astro.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 638C624E1BD454FD0004ECE1 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 638C62521BD454FD0004ECE1 /* Astro.framework in Frameworks */, + D6F831A48F327D5367262464 /* Pods_AstroTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 2E934444499338145ADBF923 /* Networking */ = { + isa = PBXGroup; + children = ( + 2E934B3DCE343BE7D9CECCCD /* HTTPStatusCodeSpec.swift */, + 3F8E16F41CCA801000E0B4DD /* NetworkServiceSpec.swift */, + 3FCD95D61CCC2D3400A5442F /* User.swift */, + ); + path = Networking; + sourceTree = ""; + }; + 2E934A2D9C9120E1AF7D0556 /* UI */ = { + isa = PBXGroup; + children = ( + CA5380CA1C5C195900204A68 /* UIColor+AstroGadgets.swift */, + 2E93420DB2E8AE3339E2E9C0 /* UIView+AstroGadgets.swift */, + E62F9D1B1D62264F005402BF /* UICollectionView+AstroGadgets.swift */, + E62F9D1D1D6227DE005402BF /* UITableView+AstroGadgets.swift */, + 2E9348D0FB90D68FC7E5C3D7 /* UIViewController+AstroGadgets.swift */, + 535DF1091C87864E00961785 /* LayoutLabel.swift */, + E6D5F8831D35B55600CB4D5F /* ReusableView.swift */, + E665B02A1D35BB4B0099C89E /* NibLoadableView.swift */, + ); + path = UI; + sourceTree = ""; + }; + 2E934BF4A4C69C31C5403859 /* UI */ = { + isa = PBXGroup; + children = ( + 2E93428725B0114A0FC9064E /* UIView+AstroGadgetsSpec.swift */, + 2E9348C107F407A4402AB69F /* UIViewController+AstroGadgetsSpec.swift */, + CA5380CC1C5C196E00204A68 /* UIColor+AstroGadgetsSpec.swift */, + 535DF10B1C87886500961785 /* LayoutLabelSpec.swift */, + E62F9D211D623675005402BF /* ReusableViewSpec.swift */, + E6F32EE41D6264FE00D31F64 /* NibLoadableViewSpec.swift */, + ); + path = UI; + sourceTree = ""; + }; + 2E934C6B173CE2849F181E64 /* Unit Tests */ = { + isa = PBXGroup; + children = ( + D0C31C4EC3779F933478EE7E /* Logging */, + 2E934444499338145ADBF923 /* Networking */, + 63379D771C06394900DDD95B /* Security */, + 2E934BF4A4C69C31C5403859 /* UI */, + BD62EA491C929C04004A02DF /* Utils */, + ); + path = "Unit Tests"; + sourceTree = ""; + }; + 2E934EE07BB108477AD37BC1 /* Networking */ = { + isa = PBXGroup; + children = ( + 2E934F99FFAF39F046F75750 /* HTTPStatusCode.swift */, + 3F8E16F71CCA843100E0B4DD /* NetworkService.swift */, + 3F8E16F81CCA843100E0B4DD /* Route.swift */, + ); + path = Networking; + sourceTree = ""; + }; + 63379D741C0638C900DDD95B /* Security */ = { + isa = PBXGroup; + children = ( + 63379D7E1C063B8800DDD95B /* KeychainAccess.swift */, + ); + name = Security; + sourceTree = ""; + }; + 63379D771C06394900DDD95B /* Security */ = { + isa = PBXGroup; + children = ( + 63379D801C063BA900DDD95B /* KeychainAccessSpec.swift */, + ); + name = Security; + sourceTree = ""; + }; + 6367D7831C0BCC6C0045BDFE /* Supporting Files */ = { + isa = PBXGroup; + children = ( + 6367D7841C0BCC6C0045BDFE /* testdata.json */, + ); + path = "Supporting Files"; + sourceTree = ""; + }; + 638C623D1BD454FD0004ECE1 = { + isa = PBXGroup; + children = ( + 638C62491BD454FD0004ECE1 /* Astro */, + 638C62551BD454FD0004ECE1 /* AstroTests */, + 638C62481BD454FD0004ECE1 /* Products */, + D313362ACAA8672CCBFCCCCC /* Pods */, + C03FAE7E5E2D5A7C58BAD5ED /* Frameworks */, + ); + sourceTree = ""; + }; + 638C62481BD454FD0004ECE1 /* Products */ = { + isa = PBXGroup; + children = ( + 638C62471BD454FD0004ECE1 /* Astro.framework */, + 638C62511BD454FD0004ECE1 /* AstroTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 638C62491BD454FD0004ECE1 /* Astro */ = { + isa = PBXGroup; + children = ( + 638C624C1BD454FD0004ECE1 /* Info.plist */, + D0C315CE2C98B7DA62D463A3 /* Logging */, + 2E934EE07BB108477AD37BC1 /* Networking */, + 63379D741C0638C900DDD95B /* Security */, + 2E934A2D9C9120E1AF7D0556 /* UI */, + BD62EA461C928F6C004A02DF /* Utils */, + ); + path = Astro; + sourceTree = ""; + }; + 638C62551BD454FD0004ECE1 /* AstroTests */ = { + isa = PBXGroup; + children = ( + 6367D7831C0BCC6C0045BDFE /* Supporting Files */, + 2E934C6B173CE2849F181E64 /* Unit Tests */, + 638C62581BD454FD0004ECE1 /* Info.plist */, + ); + path = AstroTests; + sourceTree = ""; + }; + BD62EA461C928F6C004A02DF /* Utils */ = { + isa = PBXGroup; + children = ( + 3F78B54F1CC35D4900A0E30C /* Queue.swift */, + BD62EA471C929BF0004A02DF /* EnumCountable.swift */, + ); + name = Utils; + sourceTree = ""; + }; + BD62EA491C929C04004A02DF /* Utils */ = { + isa = PBXGroup; + children = ( + BD62EA4A1C929C1C004A02DF /* EnumCountableSpec.swift */, + ); + name = Utils; + sourceTree = ""; + }; + C03FAE7E5E2D5A7C58BAD5ED /* Frameworks */ = { + isa = PBXGroup; + children = ( + 2D24B772E4EC6454D9C2C893 /* Pods_AstroTests.framework */, + 273FFD8472B2BF5BD8B6DF9F /* Pods_Astro.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + D0C315CE2C98B7DA62D463A3 /* Logging */ = { + isa = PBXGroup; + children = ( + D0C31A257874127AD224738D /* Log.swift */, + ); + path = Logging; + sourceTree = ""; + }; + D0C31C4EC3779F933478EE7E /* Logging */ = { + isa = PBXGroup; + children = ( + B69726CD1BD9162F0047EEB9 /* LoggerSpec.swift */, + ); + path = Logging; + sourceTree = ""; + }; + D313362ACAA8672CCBFCCCCC /* Pods */ = { + isa = PBXGroup; + children = ( + 7CC6FB4E4A3FE9D093738307 /* Pods-AstroTests.debug.xcconfig */, + 1FF6722A4F1235471A201686 /* Pods-AstroTests.release.xcconfig */, + D5D8E2A7279FA75989658B29 /* Pods-Astro.debug.xcconfig */, + BD95704572604E86D00F715F /* Pods-Astro.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 638C62441BD454FD0004ECE1 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 638C62461BD454FD0004ECE1 /* Astro */ = { + isa = PBXNativeTarget; + buildConfigurationList = 638C625B1BD454FD0004ECE1 /* Build configuration list for PBXNativeTarget "Astro" */; + buildPhases = ( + E12FAB773EF2299A29253D6A /* [CP] Check Pods Manifest.lock */, + 638C62421BD454FD0004ECE1 /* Sources */, + 638C62431BD454FD0004ECE1 /* Frameworks */, + 638C62441BD454FD0004ECE1 /* Headers */, + 638C62451BD454FD0004ECE1 /* Resources */, + 434C28018B913E94E3422A3A /* [CP] Copy Pods Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Astro; + productName = Astro; + productReference = 638C62471BD454FD0004ECE1 /* Astro.framework */; + productType = "com.apple.product-type.framework"; + }; + 638C62501BD454FD0004ECE1 /* AstroTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 638C625E1BD454FD0004ECE1 /* Build configuration list for PBXNativeTarget "AstroTests" */; + buildPhases = ( + C501F883BF7A2BA184E74035 /* [CP] Check Pods Manifest.lock */, + 638C624D1BD454FD0004ECE1 /* Sources */, + 638C624E1BD454FD0004ECE1 /* Frameworks */, + 638C624F1BD454FD0004ECE1 /* Resources */, + 2D428D42B6F0E93D6F4FB498 /* [CP] Embed Pods Frameworks */, + 9B92CE763EAC68888AFADCA6 /* [CP] Copy Pods Resources */, + ); + buildRules = ( + ); + dependencies = ( + 638C62541BD454FD0004ECE1 /* PBXTargetDependency */, + ); + name = AstroTests; + productName = AstroTests; + productReference = 638C62511BD454FD0004ECE1 /* AstroTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 638C623E1BD454FD0004ECE1 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0700; + LastUpgradeCheck = 0700; + ORGANIZATIONNAME = "Robots and Pencils"; + TargetAttributes = { + 638C62461BD454FD0004ECE1 = { + CreatedOnToolsVersion = 7.0.1; + }; + 638C62501BD454FD0004ECE1 = { + CreatedOnToolsVersion = 7.0.1; + }; + }; + }; + buildConfigurationList = 638C62411BD454FD0004ECE1 /* Build configuration list for PBXProject "Astro" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 638C623D1BD454FD0004ECE1; + productRefGroup = 638C62481BD454FD0004ECE1 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 638C62461BD454FD0004ECE1 /* Astro */, + 638C62501BD454FD0004ECE1 /* AstroTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 638C62451BD454FD0004ECE1 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 638C624F1BD454FD0004ECE1 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6367D7851C0BCC6C0045BDFE /* testdata.json in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 2D428D42B6F0E93D6F4FB498 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 434C28018B913E94E3422A3A /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-Astro/Pods-Astro-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + 9B92CE763EAC68888AFADCA6 /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + C501F883BF7A2BA184E74035 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] 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; + }; + E12FAB773EF2299A29253D6A /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] 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; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 638C62421BD454FD0004ECE1 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 3F8E16FA1CCA843100E0B4DD /* NetworkService.swift in Sources */, + BD62EA481C929BF0004A02DF /* EnumCountable.swift in Sources */, + 535DF10A1C87864E00961785 /* LayoutLabel.swift in Sources */, + E6D5F8841D35B55600CB4D5F /* ReusableView.swift in Sources */, + 2E9345EE0AEB18FB859A8D06 /* UIView+AstroGadgets.swift in Sources */, + 2E934B8A416AF015C76347DC /* UIViewController+AstroGadgets.swift in Sources */, + 2E93487124A5E044E0199250 /* HTTPStatusCode.swift in Sources */, + 63379D7F1C063B8800DDD95B /* KeychainAccess.swift in Sources */, + D0C3176529877E28CFD27E77 /* Log.swift in Sources */, + E62F9D1E1D6227DE005402BF /* UITableView+AstroGadgets.swift in Sources */, + E665B02B1D35BB4B0099C89E /* NibLoadableView.swift in Sources */, + E62F9D1C1D62264F005402BF /* UICollectionView+AstroGadgets.swift in Sources */, + 3F78B5501CC35D4900A0E30C /* Queue.swift in Sources */, + 3F8E16FB1CCA843100E0B4DD /* Route.swift in Sources */, + CA5380CB1C5C195900204A68 /* UIColor+AstroGadgets.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 638C624D1BD454FD0004ECE1 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 535DF10C1C87886500961785 /* LayoutLabelSpec.swift in Sources */, + 2E93419DA70B2DFA04A8D50E /* HTTPStatusCodeSpec.swift in Sources */, + 2E9342BC5B4FE98B693084A6 /* UIView+AstroGadgetsSpec.swift in Sources */, + E6F32EE51D6264FE00D31F64 /* NibLoadableViewSpec.swift in Sources */, + 63379D811C063BA900DDD95B /* KeychainAccessSpec.swift in Sources */, + 3F8E16F51CCA801000E0B4DD /* NetworkServiceSpec.swift in Sources */, + B69726CE1BD9162F0047EEB9 /* LoggerSpec.swift in Sources */, + CA5380CD1C5C196E00204A68 /* UIColor+AstroGadgetsSpec.swift in Sources */, + 2E934D1B02F8932284DCF220 /* UIViewController+AstroGadgetsSpec.swift in Sources */, + 3FCD95D71CCC2D3400A5442F /* User.swift in Sources */, + E62F9D221D623675005402BF /* ReusableViewSpec.swift in Sources */, + BD62EA4B1C929C1C004A02DF /* EnumCountableSpec.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 638C62541BD454FD0004ECE1 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 638C62461BD454FD0004ECE1 /* Astro */; + targetProxy = 638C62531BD454FD0004ECE1 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 638C62591BD454FD0004ECE1 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + APPLICATION_EXTENSION_API_ONLY = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 638C625A1BD454FD0004ECE1 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + APPLICATION_EXTENSION_API_ONLY = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 638C625C1BD454FD0004ECE1 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D5D8E2A7279FA75989658B29 /* Pods-Astro.debug.xcconfig */; + buildSettings = { + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = Astro/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = RNP.Astro; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 638C625D1BD454FD0004ECE1 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = BD95704572604E86D00F715F /* Pods-Astro.release.xcconfig */; + buildSettings = { + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = Astro/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = RNP.Astro; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + }; + name = Release; + }; + 638C625F1BD454FD0004ECE1 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7CC6FB4E4A3FE9D093738307 /* Pods-AstroTests.debug.xcconfig */; + buildSettings = { + INFOPLIST_FILE = AstroTests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks $(FRAMEWORK_SEARCH_PATHS)"; + PRODUCT_BUNDLE_IDENTIFIER = RNP.AstroTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 638C62601BD454FD0004ECE1 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1FF6722A4F1235471A201686 /* Pods-AstroTests.release.xcconfig */; + buildSettings = { + INFOPLIST_FILE = AstroTests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks $(FRAMEWORK_SEARCH_PATHS)"; + PRODUCT_BUNDLE_IDENTIFIER = RNP.AstroTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 638C62411BD454FD0004ECE1 /* Build configuration list for PBXProject "Astro" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 638C62591BD454FD0004ECE1 /* Debug */, + 638C625A1BD454FD0004ECE1 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 638C625B1BD454FD0004ECE1 /* Build configuration list for PBXNativeTarget "Astro" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 638C625C1BD454FD0004ECE1 /* Debug */, + 638C625D1BD454FD0004ECE1 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 638C625E1BD454FD0004ECE1 /* Build configuration list for PBXNativeTarget "AstroTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 638C625F1BD454FD0004ECE1 /* Debug */, + 638C62601BD454FD0004ECE1 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 638C623E1BD454FD0004ECE1 /* Project object */; +} diff --git a/Astro.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Astro.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..913ba85 --- /dev/null +++ b/Astro.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Astro.xcodeproj/xcshareddata/xcschemes/Astro.xcscheme b/Astro.xcodeproj/xcshareddata/xcschemes/Astro.xcscheme new file mode 100644 index 0000000..2961477 --- /dev/null +++ b/Astro.xcodeproj/xcshareddata/xcschemes/Astro.xcscheme @@ -0,0 +1,118 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Astro.xcworkspace/contents.xcworkspacedata b/Astro.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d441ff --- /dev/null +++ b/Astro.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/Astro/Info.plist b/Astro/Info.plist new file mode 100644 index 0000000..60b9c00 --- /dev/null +++ b/Astro/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + NSPrincipalClass + + + diff --git a/Astro/Logging/Log.swift b/Astro/Logging/Log.swift new file mode 100644 index 0000000..6a277d8 --- /dev/null +++ b/Astro/Logging/Log.swift @@ -0,0 +1,79 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +import Foundation + +public protocol Logger { + func log(level: Log.Level, message: String); +} + +public struct Log { + + public enum Level: Int { + case Debug + case Info + case Warning + case Error + case Silent + } + + public struct BasicLogger: Logger { + public func log(level: Level, message: String) { + var prefix = "" + + switch level { + case .Debug: + prefix = "DEBUG" + break + case .Info: + prefix = "INFO" + break + case .Warning: + prefix = "WARN" + break + case .Error: + prefix = "ERROR" + break + default: + prefix = "" + } + NSLog("%@", "\(prefix): \(message)") + } + } + + public static var level = Level.Error + public static var logger: Logger = BasicLogger() + + public static func debug(@autoclosure msg: () -> String) { + if level.rawValue <= Level.Debug.rawValue { + logger.log(.Debug, message: msg()) + } + } + + public static func info(@autoclosure msg: () -> String) { + if level.rawValue <= Level.Info.rawValue { + logger.log(.Info, message: msg()) + } + } + + public static func warn(@autoclosure msg: () -> String) { + if level.rawValue <= Level.Warning.rawValue { + logger.log(.Warning, message: msg()) + } + } + + public static func error(@autoclosure msg: () -> String) { + if level.rawValue <= Level.Error.rawValue { + logger.log(.Error, message: msg()) + } + } +} + diff --git a/Astro/Networking/HTTPStatusCode.swift b/Astro/Networking/HTTPStatusCode.swift new file mode 100644 index 0000000..1444c54 --- /dev/null +++ b/Astro/Networking/HTTPStatusCode.swift @@ -0,0 +1,229 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// 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. +// +// ================================================================= +// +// List of status codes where taken from W3C: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html +// + +import Foundation + +@objc public enum HTTPStatusCode: Int, CustomStringConvertible, CustomDebugStringConvertible { + // Informational - 1xx codes + case Code100Continue = 100 + case Code101SwitchingProtocols = 101 + + // Successful - 2xx codes + case Code200OK = 200 + case Code201Created = 201 + case Code202Accepted = 202 + case Code203NonAuthoritative = 203 + case Code204NoContent = 204 + case Code205ResetContent = 205 + case Code206PartialContent = 206 + + // Redirection - 3xx codes + case Code300MultipleChoices = 300 + case Code301MovedPermanently = 301 + case Code302Found = 302 + case Code303SeeOther = 303 + case Code304NotModified = 304 + case Code305UseProxy = 305 + case Code307TemporaryRedirect = 307 + + // Client errors - 4xx codes + case Code400BadRequest = 400 + case Code401Unauthorized = 401 + case Code402PaymentRequired = 402 + case Code403Forbidden = 403 + case Code404NotFound = 404 + case Code405MethodNotAllowed = 405 + case Code406NotAcceptable = 406 + case Code407ProxyAuthenticationRequired = 407 + case Code408RequestTimeout = 408 + case Code409Conflict = 409 + case Code410Gone = 410 + case Code411LengthRequired = 411 + case Code412PreconditionFailed = 412 + case Code413RequestEntityTooLarge = 413 + case Code414RequestURITooLong = 414 + case Code415UnsupportedMediaType = 415 + case Code416RequestedRangeNotSatisfiable = 416 + case Code417ExpectationFailed = 417 + case Code429TooManyRequests = 429 + + // Server errors - 5xx codes + case Code500InternalServerError = 500 + case Code501NotImplemented = 501 + case Code502BadGateway = 502 + case Code503ServiceUnavailable = 503 + case Code504GatewayTimeout = 504 + case Code505HTTPVersionNotSupported = 505 + + + // MARK: CustomStringConvertible + + public var description: String { + return NSHTTPURLResponse.localizedStringForStatusCode(rawValue).capitalizedString + } + + // MARK: CustomDebugStringConvertible + + public var debugDescription: String { + return "HTTPStatusCode: \(rawValue) - \(string)" + } + + public var string: String { + switch self { + case .Code100Continue: return "Continue" + case .Code101SwitchingProtocols: return "Switching Protocols" + case .Code200OK: return "OK" + case .Code201Created: return "Created" + case .Code202Accepted: return "Accepted" + case .Code203NonAuthoritative: return "Non Authoritative" + case .Code204NoContent: return "No Content" + case .Code205ResetContent: return "Reset Content" + case .Code206PartialContent: return "Partial Content" + case .Code300MultipleChoices: return "Multiple Choices" + case .Code301MovedPermanently: return "Moved Permanently" + case .Code302Found: return "Found" + case .Code303SeeOther: return "See Other" + case .Code304NotModified: return "Not Modified" + case .Code305UseProxy: return "Use Proxy" + case .Code307TemporaryRedirect: return "Temporary Redirect" + case .Code400BadRequest: return "Bad Request" + case .Code401Unauthorized: return "Unauthorized" + case .Code402PaymentRequired: return "Payment Required" + case .Code403Forbidden: return "Forbidden" + case .Code404NotFound: return "Not Found" + case .Code405MethodNotAllowed: return "Method Not Allowed" + case .Code406NotAcceptable: return "Not Acceptable" + case .Code407ProxyAuthenticationRequired: return "Proxy Authentication Required" + case .Code408RequestTimeout: return "Request Timeout" + case .Code409Conflict: return "Conflict" + case .Code410Gone: return "Gone" + case .Code411LengthRequired: return "Length Required" + case .Code412PreconditionFailed: return "Precondition Failed" + case .Code413RequestEntityTooLarge: return "Request Entity Too Large" + case .Code414RequestURITooLong: return "Request URI Too Long" + case .Code415UnsupportedMediaType: return "Unsupported Media Type" + case .Code416RequestedRangeNotSatisfiable: return "Requested Range Not Satisfiable" + case .Code417ExpectationFailed: return "Expectation Failed" + case .Code429TooManyRequests: return "Too Many Requests" + case .Code500InternalServerError: return "Internal Server Error" + case .Code501NotImplemented: return "Not Implemented" + case .Code502BadGateway: return "Bad Gateway" + case .Code503ServiceUnavailable: return "Service Unavailable" + case .Code504GatewayTimeout: return "Gateway Timeout" + case .Code505HTTPVersionNotSupported: return "HTTP Version Not Supported" + } + } + + // MARK: Lifecycle + + public init?(intValue: Int) { + guard let statusCode = HTTPStatusCode(rawValue: intValue) else { + return nil + } + + self = statusCode + } + + // MARK: Public + + public var isInformational: Bool { + return rawValue >= 100 && rawValue < 200 + } + + public var isSuccessful: Bool { + return rawValue >= 200 && rawValue < 300 + } + + public var isRedirection: Bool { + return rawValue >= 300 && rawValue < 400 + } + + public var isClientError: Bool { + return rawValue >= 400 && rawValue < 500 + } + + public var isServerError: Bool { + return rawValue >= 500 + } + + public var isError: Bool { + return isServerError || isClientError + } +} + +extension HTTPStatusCode { + public var failureReason: String { + if !self.isError { return "" } + + switch self { + // Client errors - 4xx codes + case Code400BadRequest: return "A bad request was made to the server." + case Code401Unauthorized: return "An unauthorized request was made to the server." + case Code402PaymentRequired: return "Payment is required to access this resource." + case Code403Forbidden: return "Access to that resource is forbidden." + case Code404NotFound: return "That resource wasn't found." + case Code405MethodNotAllowed: return "That kind of request isn't allowed." + case Code406NotAcceptable: return "That request isn't acceptable." + case Code407ProxyAuthenticationRequired: return "Proxy authentication is required." + case Code408RequestTimeout: return "The request timed out." + case Code409Conflict: return "There was a conflict with that resource." + case Code410Gone: return "That resource is gone." + case Code411LengthRequired: return "The length of the resource is required." + case Code412PreconditionFailed: return "A precondition failed." + case Code413RequestEntityTooLarge: return "The request entity was too large." + case Code414RequestURITooLong: return "The request URI was too long." + case Code415UnsupportedMediaType: return "The server doesn't support the type of media in that request." + case Code416RequestedRangeNotSatisfiable: return "The requested range isn't able to be satisfied by the server." + case Code417ExpectationFailed: return "An expectation failed." + case Code429TooManyRequests: return "The user has sent too many requests in a given amount of time." + + // Server errors - 5xx codes + case Code500InternalServerError: return "An error occurred in the server." + case Code501NotImplemented: return "That feature of the server isn't implemented." + case Code502BadGateway: return "The gateway is bad." + case Code503ServiceUnavailable: return "The server is unavailable." + case Code504GatewayTimeout: return "The request timed out." + case Code505HTTPVersionNotSupported: return "That HTTP version is unsupported by the server." + + default: return "" + } + } + + public var recoverySuggestion: String { + if !self.isError { return "" } + + switch self { + // Client errors - 4xx codes + case .Code400BadRequest, .Code405MethodNotAllowed, .Code406NotAcceptable, .Code407ProxyAuthenticationRequired, .Code408RequestTimeout, .Code409Conflict, .Code411LengthRequired, .Code412PreconditionFailed, .Code413RequestEntityTooLarge, .Code414RequestURITooLong, .Code415UnsupportedMediaType, .Code416RequestedRangeNotSatisfiable, .Code417ExpectationFailed: + return "This is an application error, try signing out and back in again. If this doesn't resolve the issue, please contact support." + case .Code401Unauthorized: return "Try signing out and back in again. If the issue persists, please contact support." + case .Code402PaymentRequired: return "Please make a payment for this resource and try again." + case .Code403Forbidden: return "If the issue persists, please contact support." + case .Code404NotFound: return "If you think this is incorrect, please contact support." + case .Code410Gone: return "If you think this is incorrect, please contact support." + case .Code429TooManyRequests: return "The system has received too many requests and has stopped responding, you can try again shortly but if the issue persists please contact support." + + // Server errors - 5xx codes + case .Code500InternalServerError: return "You can try the same action again, but if the issue persists please contact support." + case .Code501NotImplemented: return "" + case .Code502BadGateway: return "Please contact support if the issue persists." + case .Code503ServiceUnavailable: return "You can try again shortly, but if the issue persists please contact support." + case .Code504GatewayTimeout: return "You can try again shortly, but if the issue persists please contact support." + case .Code505HTTPVersionNotSupported: return "You can try the same action again, but if the issue persists please contact support." + + default: return "" + } + } +} diff --git a/Astro/Networking/NetworkService.swift b/Astro/Networking/NetworkService.swift new file mode 100644 index 0000000..a902993 --- /dev/null +++ b/Astro/Networking/NetworkService.swift @@ -0,0 +1,421 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +import Foundation +import Alamofire +import SwiftTask +import Freddy + +/// Error Type. +public struct NetworkError { + public let response: Response? + public let error: ErrorType + + public var statusCode: HTTPStatusCode? { + guard let response = response?.response else { return nil } + return HTTPStatusCode(intValue: response.statusCode) + } + + public var json: JSON? { + guard let data = response?.data else { return nil } + return try? JSON(data: data) + } + + public init(response: Response? = nil, error: ErrorType) { + self.response = response + self.error = error + } +} + +/// Success Type. +public struct ResponseValue { + public let response: Response? + public let value: T + + public var statusCode: HTTPStatusCode? { + guard let response = response?.response else { return nil } + return HTTPStatusCode(intValue: response.statusCode) + } + + public init(response: Response? = nil, value: T) { + self.response = response + self.value = value + } +} + +public protocol NetworkServiceType { + /** + Performs the specified request and ignores any returned data. Does not validate that the response is valid JSON. Useful for POSTs where the response body doesn't provide any useful information. + + - parameter URLRequest: the request + - returns: A task + */ + func request(URLRequest: URLRequestConvertible) -> Task, NetworkError> + + /** + Performs the specified request for a single object of type T. The response body is + expected to be a JSON dictionary which is then automatically converted to an + instance of T using Decodable. + + - parameter URLRequest: the request + - returns: A task for type T + */ + func request(URLRequest: URLRequestConvertible) -> Task, NetworkError> + + /** + Performs the specified request for a single object of type T. The response body is + expected to be a nillable JSON dictionary which is then automatically converted to an + instance of T using Decodable. + If the request does not return any data, we will return nil. + + - parameter URLRequest: the request + - returns: A task for type T? + */ + func request(URLRequest: URLRequestConvertible) -> Task, NetworkError> + + /** + Performs the specified request for an array of type T. The response body is expected + to be a JSON array which is then automatically converted to instances of T using + Decodable. Elements of the array that fail decoding are ignored in this implementation. + + - parameter URLRequest: the request + - returns: A task for type [T] + */ + func request(URLRequest: URLRequestConvertible) -> Task, NetworkError> + + /** + Performs the specified request for an array of type T. The response body is expected + to be a nillable JSON array which is then automatically converted to instances of T using + Decodable. Elements of the array that fail decoding are ignored in this implementation. + If the request does not return any data, we will return nil. + + - parameter URLRequest: the request + - returns: A task for type [T] + */ + func request(URLRequest: URLRequestConvertible) -> Task, NetworkError> + + /** + Performs the specified request for a JSON dictionary. + + - parameter URLRequest: the request + - returns: A task for a JSON dictionary + */ + func requestJSONDictionary(URLRequest: URLRequestConvertible) -> Task, NetworkError> + + /** + Performs the specified request for a JSON array. + + - parameter URLRequest: the request + - returns: A task for a JSON array + */ + func requestJSONArray(URLRequest: URLRequestConvertible) -> Task, NetworkError> + + /** + Performs the specified request for a JSON array. + + - parameter URLRequest: the request + - returns: A task for a JSON array + */ + func requestJSONArray(URLRequest: URLRequestConvertible) -> Task, NetworkError> + + /** + Performs the specified request for some JSON (which may be either an array or a dictionary). + + - parameter URLRequest: the request + - returns: A task for a JSON object which is either an array or dictionary + */ + func requestJSON(URLRequest: URLRequestConvertible) -> Task, NetworkError> + + /** + Performs the specified request for some JSON (which may be either an array or a dictionary). + + - parameter URLRequest: the request + - returns: A task for a JSON object which is either an array or dictionary + */ + func requestJSON(URLRequest: URLRequestConvertible) -> Task, NetworkError> + + /** + Performs the specified request for some data. + + - parameter URLRequest: the request + - returns: A task for NSData + */ + func requestData(URLRequest: URLRequestConvertible) -> Task, NetworkError> +} + +/// Convenience methods without underlying NSHTTPURLResponse +public extension NetworkServiceType { + func request(URLRequest: URLRequestConvertible) -> Task { + return request(URLRequest).success { $0.value } + } + + func request(URLRequest: URLRequestConvertible) -> Task { + return request(URLRequest).success { $0.value } + } + + func request(URLRequest: URLRequestConvertible) -> Task { + return request(URLRequest).success { $0.value } + } + + func request(URLRequest: URLRequestConvertible) -> Task { + return request(URLRequest).success { $0.value } + } + + func request(URLRequest: URLRequestConvertible) -> Task { + return request(URLRequest).success { $0.value } + } + + func requestJSONDictionary(URLRequest: URLRequestConvertible) -> Task { + return requestJSONDictionary(URLRequest).success { $0.value } + } + + func requestJSONArray(URLRequest: URLRequestConvertible) -> Task { + return requestJSONArray(URLRequest).success { $0.value } + } + + func requestJSONArray(URLRequest: URLRequestConvertible) -> Task { + return requestJSONArray(URLRequest).success { $0.value } + } + + func requestJSON(URLRequest: URLRequestConvertible) -> Task { + return requestJSON(URLRequest).success { $0.value } + } + + func requestJSON(URLRequest: URLRequestConvertible) -> Task { + return requestJSON(URLRequest).success { $0.value } + } + + func requestData(URLRequest: URLRequestConvertible) -> Task { + return self.requestData(URLRequest).success { return $0.value } + } +} + +/** + NetworkService is a simple networking layer that assumes usage of Alamofire, SwiftTask, and Freddy. By making these + assumptions we can provide tasks that directly produce model classes on success and provide Alamofire or JSON errors + on failure. The NSHTTPURLResponse is provided in both the success and failure case as it is often required to have + custom behaviour based on something like statusCode. Designed to implement NetworkServiceType so that it can be + easily mocked. + */ +public class NetworkService: NetworkServiceType { + + public struct AssertionError: ErrorType {} + private let requestManager: Alamofire.Manager + + public convenience init() { + let requestManager: Alamofire.Manager = { + let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() + configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders + + return Alamofire.Manager(configuration: configuration) + }() + self.init(requestManager: requestManager) + } + + public init(requestManager: Alamofire.Manager) { + self.requestManager = requestManager + } + + public func request(URLRequest: URLRequestConvertible) -> Task, NetworkError> { + return requestData(URLRequest).success { value in return ResponseValue(response: value.response, value: ()) } + } + + public func request(URLRequest: URLRequestConvertible) -> Task, NetworkError> { + return requestJSON(URLRequest).success { (value: ResponseValue) -> Task, NetworkError> in + let json = value.value + do { + let result = try T(json: json) + return Task(value: ResponseValue(response: value.response, value: result)) + } catch let error { + return Task(error: NetworkError(response: value.response, error: error)) + } + } + } + + public func request(URLRequest: URLRequestConvertible) -> Task, NetworkError> { + return requestJSON(URLRequest).success { (value: ResponseValue) -> Task, NetworkError> in + guard let json = value.value else { + return Task(value: ResponseValue(response: value.response, value: nil)) + } + do { + let result = try T(json: json) + return Task(value: ResponseValue(response: value.response, value: result)) + } catch let error { + return Task(error: NetworkError(response: value.response, error: error)) + } + } + } + + public func request(URLRequest: URLRequestConvertible) -> Task, NetworkError> { + return requestJSONArray(URLRequest).success { (value: ResponseValue<[JSON]>) -> Task, NetworkError> in + let json = value.value + do { + let models = try json.map(T.init) + return Task(value: ResponseValue(response: value.response, value: models)) + } catch let error { + return Task(error: NetworkError(response: value.response, error: error)) + } + } + } + + public func request(URLRequest: URLRequestConvertible) -> Task, NetworkError> { + return requestJSONArray(URLRequest).success { (value: ResponseValue<[JSON]?>) -> Task, NetworkError> in + guard let json = value.value else { + return Task(value: ResponseValue(response: value.response, value: nil)) + } + do { + let models = try json.map(T.init) + return Task(value: ResponseValue(response: value.response, value: models)) + } catch let error { + return Task(error: NetworkError(response: value.response, error: error)) + } + } + } + + public func requestJSONDictionary(URLRequest: URLRequestConvertible) -> Task, NetworkError> { + return requestJSON(URLRequest).success { (value: ResponseValue) -> Task, NetworkError> in + let json = value.value + guard case let JSON.Dictionary(dictionary) = json else { + let error = JSON.Error.ValueNotConvertible(value: json, to: Swift.Dictionary) + return Task, NetworkError>(error: NetworkError(response: value.response, error: error)) + } + return Task(value: ResponseValue(response: value.response, value: dictionary)) + } + } + + public func requestJSONArray(URLRequest: URLRequestConvertible) -> Task, NetworkError> { + return requestJSON(URLRequest).success { (value: ResponseValue) -> Task, NetworkError> in + let json = value.value + guard case let JSON.Array(array) = json else { + let error = JSON.Error.ValueNotConvertible(value: json, to: Swift.Array) + return Task, NetworkError>(error: NetworkError(response: value.response, error: error)) + } + return Task(value: ResponseValue(response: value.response, value: array)) + } + } + + public func requestJSONArray(URLRequest: URLRequestConvertible) -> Task, NetworkError> { + return requestJSON(URLRequest).success { (value: ResponseValue) -> Task, NetworkError> in + guard let json = value.value else { + return Task(value: ResponseValue(response: value.response, value: nil)) + } + guard case let JSON.Array(array) = json else { + let error = JSON.Error.ValueNotConvertible(value: json, to: Swift.Array) + return Task, NetworkError>(error: NetworkError(response: value.response, error: error)) + } + return Task(value: ResponseValue(response: value.response, value: array)) + } + } + + public func requestJSON(URLRequest: URLRequestConvertible) -> Task, NetworkError> { + return requestData(URLRequest).success { value -> Task, NetworkError> in + do { + let json = try JSON(data: value.value) + return Task(value: ResponseValue(response: value.response, value: json)) + } catch let error { + return Task(error: NetworkError(response: value.response, error: error)) + } + } + } + + public func requestJSON(URLRequest: URLRequestConvertible) -> Task, NetworkError> { + return requestData(URLRequest).success { value -> Task, NetworkError> in + if value.value.length == 0 { + return Task(value: ResponseValue(response: value.response, value: nil)) + } + do { + let json = try JSON(data: value.value) + return Task(value: ResponseValue(response: value.response, value: json)) + } catch let error { + return Task(error: NetworkError(response: value.response, error: error)) + } + } + } + + public func requestData(URLRequest: URLRequestConvertible) -> Task, NetworkError> { + return Task { [weak self] progress, fulfill, reject, configure in + let request = self?.requestManager.request(URLRequest) + .progress { bytesRead, totalBytesRead, totalExpectedBytes -> Void in + progress(Float(totalBytesRead) / Float(totalExpectedBytes)) + } + .validate() // Covers error status code and content type mismatch + .responseData { response in + guard let data = response.result.value where response.result.isSuccess else { + // We should always have an error in the non success case but use AssertionError to avoid a bang (!) + let error: ErrorType = response.result.error ?? AssertionError() + reject(NetworkError(response: response, error: error)) + return + } + fulfill(ResponseValue(response: response, value: data)) + } + configure.cancel = { [weak request] in + request?.cancel() + } + } + } +} + +private extension URLRequestConvertible { + func logRequest(headers includeHeaders: Bool = false, body includeBody: Bool = false) -> String { + let request = self.URLRequest + let method = request.HTTPMethod + + guard let url = request.URL?.absoluteString else { + return "**Unable to log request**" + } + + var result = "\(method) \(url)" + + if includeHeaders { + let headers = request.allHTTPHeaderFields?.map { "\($0): \($1)" } + if let headers = headers { + result.appendContentsOf(": \(headers)") + } + } + + if includeBody { + if let bodyData = request.HTTPBody, + body = String(data: bodyData, encoding: NSUTF8StringEncoding) { + result.appendContentsOf("\n") + result.appendContentsOf(body) + } + } + return result + } +} + +private extension Response { + func logResponse(headers includeHeaders: Bool = false, body includeBody: Bool = false) -> String { + guard let url = request?.URL?.absoluteString, + statusCodeInt = self.response?.statusCode, + statusCode = HTTPStatusCode(intValue: statusCodeInt) else { + return "**Unable to log response**" + } + + var result = "\(statusCodeInt) \(url)" + + if includeHeaders || statusCode.isError { + let headers = self.response?.allHeaderFields.map { "\($0): \($1)" } + if let headers = headers { + result.appendContentsOf(": \(headers)") + } + } + + if includeBody || statusCode.isError { + if let bodyData = self.data, + body = String(data: bodyData, encoding: NSUTF8StringEncoding) { + result.appendContentsOf("\n") + result.appendContentsOf(body) + } + } + return result + } +} diff --git a/Astro/Networking/Route.swift b/Astro/Networking/Route.swift new file mode 100644 index 0000000..c139aaa --- /dev/null +++ b/Astro/Networking/Route.swift @@ -0,0 +1,99 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// 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 Alamofire +import Freddy + +public struct Route: URLRequestConvertible { + public let baseURL: NSURL + public let path: String + public let method: Alamofire.Method + public let parameters: RequestParameters? + public let additionalHeaders: [String: String] + + public init(baseURL: NSURL, path: String, method: Alamofire.Method = .GET, JSON: Freddy.JSON, additionalHeaders: [String: String] = [:]) { + self.init(baseURL: baseURL, path: path, method: method, parameters: RequestParameters.JSON(parameters: JSON), additionalHeaders: additionalHeaders) + } + + public init(baseURL: NSURL, path: String, method: Alamofire.Method = .GET, parameters: RequestParameters? = nil, additionalHeaders: [String: String] = [:]) { + self.baseURL = baseURL + self.path = path + self.method = method + self.parameters = parameters + self.additionalHeaders = additionalHeaders + } + + public var URL: NSURL { + return baseURL.URLByAppendingPathComponent(self.path) + } + + // MARK: - URLRequestConvertible + + public var URLRequest: NSMutableURLRequest { + var mutableURLRequest = NSMutableURLRequest(URL: self.URL) + mutableURLRequest.HTTPMethod = self.method.rawValue + + for (header, value) in self.additionalHeaders { + mutableURLRequest.setValue(value, forHTTPHeaderField: header) + } + + if let parameters = self.parameters { + mutableURLRequest = parameters.encode(mutableURLRequest).0 + } + + return mutableURLRequest + } +} + +extension Route: CustomStringConvertible { + public var description: String { + let request = URLRequest + let method = request.HTTPMethod ?? "" + let url = request.URLString ?? "" + return "\(method) \(url)" + } +} + +public enum RequestParameters { + case JSON(parameters: Freddy.JSON) + case Dictionary(parameters: [String: AnyObject], parameterEncoding: Alamofire.ParameterEncoding) + + public func encode(URLRequest: URLRequestConvertible) -> (NSMutableURLRequest, NSError?) { + switch self { + case .JSON(let parameters): + let mutableURLRequest = URLRequest.URLRequest + var encodingError: NSError? = nil + do { + let data = try parameters.serialize() + + if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { + mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + mutableURLRequest.HTTPBody = data + } catch { + encodingError = error as NSError + Log.error("Unable to encode JSON parameters: \(encodingError)") + } + return (mutableURLRequest, encodingError) + + case .Dictionary(let parameters, let encoding): + return encoding.encode(URLRequest, parameters: parameters) + } + } +} + +public extension String { + public func base64Encode() -> String { + let data = self.dataUsingEncoding(NSUTF8StringEncoding) + return data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) + } +} diff --git a/Astro/Security/KeychainAccess.swift b/Astro/Security/KeychainAccess.swift new file mode 100644 index 0000000..03f9ebe --- /dev/null +++ b/Astro/Security/KeychainAccess.swift @@ -0,0 +1,215 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +import Foundation +import Security + +let KeychainAccessServiceBundleID: String = { + if NSClassFromString("XCTestCase") != nil { + Log.level = Log.Level.Debug + return "com.robotsandpencils.TestTarget" + } else { + return NSBundle.mainBundle().bundleIdentifier ?? "" + } +}() + +let KeychainAccessErrorDomain = "\(KeychainAccessServiceBundleID).error" + +public class KeychainAccess { + + let keychainAccessAccount: String? + + public init(account: String) { + keychainAccessAccount = account + } + + /** + Retrieve a string for the given key. + + - parameter key: the key to find the string in the keychain + - returns: the value stored for that key as a string. nil if there is no value or the value is not a string + */ + public func getString(key: String) -> String? { + guard let data = self.get(key) else { + return nil + } + return NSString(data: data, encoding: NSUTF8StringEncoding) as? String + } + + /** + Retrieve data for the given key. + + - parameter key: the key to find the data in the keychain + - returns: the value stored for that key as NSData. nil if there is no value or the value is not NSData + */ + public func get(key: String) -> NSData? { + let query = self.query(key, get: true) + + var result: AnyObject? + let status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } + + if status == errSecSuccess { + guard let data = result as? NSData else { + Log.debug("No data fetched for the key from keychain with status=\(status). Attempted to get value for key [\(key)]") + return nil + } + return data + } else { + Log.debug("Failed to fetch value from keychain with status=\(status).Attempted to get value for key [\(key)]") + return nil + } + } + + /** + Set a string for the given key. + + - parameter key: the key to store the string for in the keychain + - parameter value: the string to store in the keychain (if nil then no data will be stored for the key) + - returns: true if the store was successful, false if there was an error + */ + public func putString(key: String, value: String?) -> Bool { + return self.put(key, data: value?.dataUsingEncoding(NSUTF8StringEncoding)) + } + + /** + Set data for the given key. + + - parameter key: the key to store the data for in the keychain + - parameter value: the data to store in the keychain (if nil then no data will be stored for the key) + - returns: true if the store was successful, false if there was an error + */ + public func put(key: String, data: NSData?) -> Bool { + let query = self.query(key, value: data) + var result: AnyObject? + + var status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } + if status == errSecSuccess { + // Key previously existed + if let data = data { + // Updating the data to a new value + let attributesToUpdate: [String: AnyObject] = [kSecValueData as String : data] + status = SecItemUpdate(query, attributesToUpdate as CFDictionaryRef) + if status == errSecSuccess { + return true + } + Log.debug("Failed to update data in keychain with status=\(status). Attempted to update data [\(data)] for key [\(key)]") + return false + } else { + // Explicitly clearing the old data since we can't update to a nil value + var status = SecItemDelete(query) + if status == errSecSuccess { + status = SecItemAdd(query, nil) + if status == errSecSuccess { + return true + } + } + Log.debug("Failed to clear data in keychain with status=\(status). Attempted to clear data for key [\(key)]") + return false + } + } else if status == errSecItemNotFound { + // Key doesn't exist so add it + status = SecItemAdd(query, nil) + if status == errSecSuccess { + return true + } + Log.debug("Failed to add data to keychain with status=\(status). Attempted to add data [\(data)] for key [\(key)]") + return false + } else { + Log.debug("Failed to add key to keychain with status=\(status). Attempted to add key [\(key)]") + return false + } + } + + /** + Delete the data for the given key. + + - parameter key: the key to delete the data for in the keychain + - returns: true if the delete was successful, false if there was an error + */ + public func delete(key: String) -> Bool { + let query = self.query(key) + let status = SecItemDelete(query) + + if status == errSecSuccess || status == errSecItemNotFound { + return true + } else { + Log.debug("Failed to delete key from keychain with status=\(status). Attempted to delete key [\(key)]") + return false + } + } + + /** + Delete the all keys and data for the app. + + - returns: true if the delete was successful, false if there was an error + */ + public func deleteAllKeysAndDataForApp() -> Bool { + var query: [String: AnyObject] = [:] + query[kSecClass as String] = kSecClassGenericPassword + + let status = SecItemDelete(query) + if status == errSecSuccess || status == errSecItemNotFound { + return true + } else { + Log.debug("Failed to delete all app keys and data from keychain with status=\(status).") + return false + } + } + + public subscript(key: String) -> String? { + get { + return self.getString(key) + } + + set { + self.putString(key, value: newValue) + } + } + + public subscript(data key: String) -> NSData? { + get { + return self.get(key) + } + + set { + self.put(key, data: newValue) + } + } + + //MARK: Private + /** + Set up the query for use with the keychain functions. + + - parameter key: the key to use for searching or saving + - parameter value: the data to store in the keychain + - parameter get: the query is for retrieving data and should have the parameters to do that + - returns: a dictionary for use as the query + */ + private func query(key: String, value: AnyObject? = nil, get: Bool = false) -> CFDictionaryRef { + var query: [String: AnyObject] = [:] + query[kSecAttrService as String] = key + query[kSecAttrAccount as String] = self.keychainAccessAccount + query[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlocked + query[kSecClass as String] = kSecClassGenericPassword + + if let value = value { + query[kSecValueData as String] = value + } + + if get { + query[kSecReturnData as String] = kCFBooleanTrue + query[kSecMatchLimit as String] = kSecMatchLimitOne + } + + return query as CFDictionaryRef + } + +} diff --git a/Astro/UI/LayoutLabel.swift b/Astro/UI/LayoutLabel.swift new file mode 100644 index 0000000..f02d031 --- /dev/null +++ b/Astro/UI/LayoutLabel.swift @@ -0,0 +1,45 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +import UIKit + +/** + LayoutLabel implements some logic to ensure that a UILabel properly resizes itself based on its content. + Used in situations like determining cell height in a UITableView, ensuring that labels fit their content + after a constraint change, etc... + Based on http://stackoverflow.com/questions/18118021/how-to-resize-superview-to-fit-all-subviews-with-autolayout + */ +public class LayoutLabel: UILabel { + + override public func layoutSubviews() { + super.layoutSubviews() + + if numberOfLines == 0 && preferredMaxLayoutWidth != frame.size.width { + preferredMaxLayoutWidth = frame.size.width + setNeedsUpdateConstraints() + } + } + + override public func intrinsicContentSize() -> CGSize { + var contentSize = super.intrinsicContentSize() + + guard let text = text else { + return contentSize + } + + if numberOfLines == 0 && text.characters.count > 0 { + // found out that sometimes intrinsicContentSize is 1pt too short! + contentSize.height += 1 + } + + return contentSize + } +} diff --git a/Astro/UI/NibLoadableView.swift b/Astro/UI/NibLoadableView.swift new file mode 100644 index 0000000..f64272c --- /dev/null +++ b/Astro/UI/NibLoadableView.swift @@ -0,0 +1,37 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +import UIKit + +/** + NibLoadableView is a way to generalize the pattern of declaring a constant for + every nib file. Much of this is based off of the ideas from: + https://medium.com/@gonzalezreal/ios-cell-registration-reusing-with-swift-protocol-extensions-and-generics-c5ac4fb5b75e + */ + +/** + A protocol for views having a corresponding nib to expose a default name, but + can easily be overridden if the corresponding nib filename is different from + that of its class + */ +public protocol NibLoadableView: class { + static var nibName: String { get } +} + +/** + Provide a default implementation for UIViews that is a safer way of getting the + nib name + */ +public extension NibLoadableView where Self: UIView { + static var nibName: String { + return String(Self) + } +} diff --git a/Astro/UI/ReusableView.swift b/Astro/UI/ReusableView.swift new file mode 100644 index 0000000..98ef86d --- /dev/null +++ b/Astro/UI/ReusableView.swift @@ -0,0 +1,35 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +import UIKit + +/** + ReusableView is a way to generalize the pattern of declaring a constant for + every reuse identifier. Much of this is based off of the ideas from: + https://medium.com/@gonzalezreal/ios-cell-registration-reusing-with-swift-protocol-extensions-and-generics-c5ac4fb5b75e + */ + +/** + A protocol for reusable-type views to provide a default reuse identifier + */ +public protocol ReusableView: class { + static var defaultReuseIdentifier: String { get } +} + +/** + Provide a default implementation constrained to UIView subclasses which is the + string representation of the class name + */ +public extension ReusableView where Self: UIView { + static var defaultReuseIdentifier: String { + return String(Self) + } +} diff --git a/Astro/UI/UICollectionView+AstroGadgets.swift b/Astro/UI/UICollectionView+AstroGadgets.swift new file mode 100644 index 0000000..b01618b --- /dev/null +++ b/Astro/UI/UICollectionView+AstroGadgets.swift @@ -0,0 +1,52 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +import UIKit + +/** + Extends UICollectionView to simplify cell registration and dequeueing + */ +public extension UICollectionView { + /** + Registration method for subclasses implementing only ReusableView + + - parameter cellType: The cell subclass type that conforms to the ReusableView protocol + */ + public func register(cellType: T.Type) { + registerClass(cellType.self, forCellWithReuseIdentifier: cellType.defaultReuseIdentifier) + } + + /** + Registration method for subclasses implementing both ReusableView and + NibLoadableView + + - parameter cellType: The cell subclass type that conforms to both ReusableView and NibLoadableView protocols + */ + public func register(cellType: T.Type) { + let bundle = NSBundle(forClass: cellType.self) + let nib = UINib(nibName: cellType.nibName, bundle: bundle) + registerNib(nib, forCellWithReuseIdentifier: cellType.defaultReuseIdentifier) + } + + /** + Ideal cell dequeueing method for cell subclasses which conform to + ReusableView – a nice detail is that it accepts a type, rather than reuse + identifier + + - parameter indexPath: The index path of the cell to dequeue + */ + public func dequeueReusableCell(forIndexPath indexPath: NSIndexPath) -> T { + guard let cell = dequeueReusableCellWithReuseIdentifier(T.defaultReuseIdentifier, forIndexPath: indexPath) as? T else { + fatalError("Could not dequeue collection view cell with identifier: \(T.defaultReuseIdentifier)") + } + return cell + } +} diff --git a/Astro/UI/UIColor+AstroGadgets.swift b/Astro/UI/UIColor+AstroGadgets.swift new file mode 100644 index 0000000..99d9319 --- /dev/null +++ b/Astro/UI/UIColor+AstroGadgets.swift @@ -0,0 +1,83 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +import UIKit + +extension UIColor { + /** + Create a color from a string of hexadecimal characters. + + - parameter hexString: A six or eight-character string of hexadecimal (0-9, A-F) characters, optionally preceded with a # character. Every two characters represents the 0-255 value of a RGBA color component. For example, #FF0000 represents the color red, and #FF000099 would be a translucent red. + - parameter alpha: The desired alpha of the created color, from 0.0 to 1.0. If `hexString` contains an alpha component it will be multiplied with this value. Default value is 1.0. + + - returns: A new color created from the parsed values. + */ + public convenience init?(hexString: String, alpha: Double = 1.0) { + var parsedRed: UInt32 = 255 + var parsedGreen: UInt32 = 255 + var parsedBlue: UInt32 = 255 + var parsedAlpha: UInt32 = 255 + + let hexCharacterSet = NSCharacterSet(charactersInString: "0123456789abcdefABCDEF") + let hexOnlyString = hexString.componentsSeparatedByCharactersInSet(hexCharacterSet.invertedSet).joinWithSeparator("") + + guard hexOnlyString.characters.count >= 6 else { + // There is a bug in stable Xcode 7.3 (SR-704) where returning nil + // here will crash with EXC_BAD_ACCESS. Current workaround is to + // call self/super.init() before returning nil. + // Source: https://bugs.swift.org/browse/SR-704 + self.init() + return nil + } + + let redCharacterRange = hexOnlyString.startIndex.. String { + var r: CGFloat = 0 + var g: CGFloat = 0 + var b: CGFloat = 0 + var a: CGFloat = 0 + assert(getRed(&r, green: &g, blue: &b, alpha: &a), "Unable to get RGB channels from UIColor") + return NSString(format:"%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255)) as String + } + + /** + Creates a hexadecimal string representation of a color. For example, UIColor.redColor().hexRGBA() will return the string "FF0000FF". + + - returns: The hex string representation. + */ + public func hexRGBA() -> String { + var r: CGFloat = 0 + var g: CGFloat = 0 + var b: CGFloat = 0 + var a: CGFloat = 0 + assert(getRed(&r, green: &g, blue: &b, alpha: &a), "Unable to get RGBA channels from UIColor") + return NSString(format: "%02X%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255), Int(a * 255)) as String + } +} diff --git a/Astro/UI/UITableView+AstroGadgets.swift b/Astro/UI/UITableView+AstroGadgets.swift new file mode 100644 index 0000000..41e4e5c --- /dev/null +++ b/Astro/UI/UITableView+AstroGadgets.swift @@ -0,0 +1,52 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +import UIKit + +/** + Extends UITableView to simplify cell registration and dequeueing + */ +public extension UITableView { + /** + Registration method for subclasses implementing only ReusableView + + - parameter cellType: The cell subclass type that conforms to the ReusableView protocol + */ + public func register(cellType: T.Type) { + registerClass(cellType.self, forCellReuseIdentifier: cellType.defaultReuseIdentifier) + } + + /** + Registration method for subclasses implementing both ReusableView and + NibLoadableView + + - parameter cellType: The cell subclass type that conforms to both ReusableView and NibLoadableView protocols + */ + public func register(cellType: T.Type) { + let bundle = NSBundle(forClass: cellType.self) + let nib = UINib(nibName: cellType.nibName, bundle: bundle) + registerNib(nib, forCellReuseIdentifier: cellType.defaultReuseIdentifier) + } + + /** + Ideal cell dequeueing method for cell subclasses which conform to + ReusableView – a nice detail is that it accepts a type, rather than reuse + identifier + + - parameter indexPath: The index path of the cell to dequeue + */ + public func dequeueReusableCell(forIndexPath indexPath: NSIndexPath) -> T { + guard let cell = dequeueReusableCellWithIdentifier(T.defaultReuseIdentifier, forIndexPath: indexPath) as? T else { + fatalError("Could not dequeue table view cell with identifier: \(T.defaultReuseIdentifier)") + } + return cell + } +} diff --git a/Astro/UI/UIView+AstroGadgets.swift b/Astro/UI/UIView+AstroGadgets.swift new file mode 100644 index 0000000..541db42 --- /dev/null +++ b/Astro/UI/UIView+AstroGadgets.swift @@ -0,0 +1,83 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +import UIKit + +public extension UIView { + + // MARK: Shortcuts for getting and setting the frame properties + + public var frameSize:CGSize { + get { + return self.frame.size + } + set { + var frame = self.frame + frame.size = newValue + self.frame = frame + } + } + + public var frameHeight:CGFloat { + get { + return self.frame.size.height + } + set { + var frame = self.frame + frame.size.height = newValue + self.frame = frame + } + } + + public var frameWidth:CGFloat { + get { + return self.frame.size.width + } + set { + var frame = self.frame + frame.size.width = newValue + self.frame = frame + } + } + + public var frameOrigin:CGPoint { + get { + return self.frame.origin + } + set { + var frame = self.frame + frame.origin = newValue + self.frame = frame + } + } + + public var frameX:CGFloat { + get { + return self.frame.origin.x + } + set { + var frame = self.frame + frame.origin.x = newValue + self.frame = frame + } + } + + public var frameY:CGFloat { + get { + return self.frame.origin.y + } + set { + var frame = self.frame + frame.origin.y = newValue + self.frame = frame + } + } +} diff --git a/Astro/UI/UIViewController+AstroGadgets.swift b/Astro/UI/UIViewController+AstroGadgets.swift new file mode 100644 index 0000000..c2c7429 --- /dev/null +++ b/Astro/UI/UIViewController+AstroGadgets.swift @@ -0,0 +1,49 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +import UIKit + +public extension UIViewController { + + // MARK: General + + /** + Ensure that a view controller is added properly to another view controller + */ + public func addChildViewController(childViewController: UIViewController, inContainer view: UIView) { + self.addChildViewController(childViewController) + view.addSubview(childViewController.view) + childViewController.didMoveToParentViewController(self) + } +} + + +public extension UIViewController { + + // MARK: Alerts + + /** + Shorten way to prompt an alert + */ + public func quickAlert(title title: String?, message: String?) { + let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) + alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) + presentViewController(alert, animated: true, completion: nil) + } + + /** + Prompts an alert indicating that the feature has not been implemented + */ + public func featureNotImplemented() { + NSLog("FEATURE NOT IMPLEMENTED") + quickAlert(title: "Coming Soon", message: "Feature Not Implemented Yet.") + } +} diff --git a/Astro/Utils/EnumCountable.swift b/Astro/Utils/EnumCountable.swift new file mode 100644 index 0000000..ef2e50e --- /dev/null +++ b/Astro/Utils/EnumCountable.swift @@ -0,0 +1,44 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// 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. +// + +/** + EnumCountable allows you to add a "count" constant to Swift enums of type Int. + + Requirements: + - The enum must be of type Int + - The first case must start at 0 + - All cases must be continous + + Usage: + enum MyEnum: Int, EnumCountable { + case case1 = 0 + case case2 + case case3 + + static let count = MyEnum.countCases() // Lazy-initialize the constant 'count' to the number of enum cases + } + */ + +public protocol EnumCountable { + static var count : Int { get } +} + +public extension EnumCountable where Self : RawRepresentable, Self.RawValue == Int { + + // Counts the number of cases in the enum, starting at 0 + static func countCases() -> Int { + var count = 0 + while let _ = Self(rawValue: count) { + count += 1 + } + return count + } +} diff --git a/Astro/Utils/Queue.swift b/Astro/Utils/Queue.swift new file mode 100644 index 0000000..2994494 --- /dev/null +++ b/Astro/Utils/Queue.swift @@ -0,0 +1,49 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +import Foundation + +public protocol ExecutableQueue { + var queue: dispatch_queue_t { get } +} + +public extension ExecutableQueue { + public func execute(closure: () -> Void) { + dispatch_async(queue, closure) + } + public func executeAfter(delay delay: NSTimeInterval, closure: () -> Void) { + let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))) + dispatch_after(delayTime, queue, closure) + } +} + +public enum Queue: ExecutableQueue { + case Main + case UserInteractive + case UserInitiated + case Utility + case Background + + public var queue: dispatch_queue_t { + switch self { + case .Main: + return dispatch_get_main_queue() + case .UserInteractive: + return dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0) + case .UserInitiated: + return dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0) + case .Utility: + return dispatch_get_global_queue(QOS_CLASS_UTILITY, 0) + case .Background: + return dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0) + } + } +} diff --git a/AstroTests/Info.plist b/AstroTests/Info.plist new file mode 100644 index 0000000..ba72822 --- /dev/null +++ b/AstroTests/Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + + diff --git a/AstroTests/Supporting Files/testdata.json b/AstroTests/Supporting Files/testdata.json new file mode 100644 index 0000000..19862ea --- /dev/null +++ b/AstroTests/Supporting Files/testdata.json @@ -0,0 +1,68 @@ +{ + "dashboard": [ + "Taking a nanosecond to breathe.", + "Reminding you that you’re changing lives!", + "You’re here and that’s great!", + "Crunching so many numbers.", + "Going as fast as I possibly can!", + "Waiting for a hug...", + "Finding homework eaten by dogs.", + "Reminding you to get up and stretch.", + "Wishing you could see this from my perspective.", + "Having a chit chat with a server.", + "Hoping you're having a great day!", + "Reminding you to drink a glass of water.", + "Marveling at the progress.", + "Packaging everything up nice and neat.", + "Thanking you for being you!", + "Waiting for server hamsters.", + "Once upon a time, in a land far, far away....", + "Sorry, the pixel fairies are taking a dust break...", + "There is no easy way from the earth to the stars.", + "The dog ate my server request", + "Showing our work", + "Live as if you were to die tomorrow. Learn as if you were to live forever." + ], + "login": [ + "Stretching muscles.", + "Brewing coffee.", + "Welcoming you back!", + "Wishing you a wonderful day!", + "Reminding you to smile!", + "Trying to contain my excitement.", + "Reminding you to reach for your goals!", + "Loading up the learning!", + "Beep Beep Boop...", + "Dissecting databases.", + "Visualizing this being done.", + "Doing a crazy number of calculations.", + "Converting to imperial.", + "You are great!", + "Enjoying every nanosecond of this!", + "Live as if you were to die tomorrow. Learn as if you were to live forever.", + "Taking a moment to look at your awesomeness!" + ], + "module": [ + "Learning something new!", + "Taking a nanosecond to breathe.", + "Reminding you that you’re the future!", + "You’re here and that’s great!", + "Crunching so many numbers.", + "Going as fast as I possibly can!", + "Waiting for a hug...", + "Getting excited about the future!", + "Reminding you to get up and stretch.", + "Checking where you left off.", + "Having a chit chat with a server.", + "Hoping you're having a great day!", + "Double checking everything.", + "Reminding you to drink a glass of water.", + "Proof reading my work.", + "Packaging everything up nice and neat.", + "Thanking you for being you!", + "Live as if you were to die tomorrow. Learn as if you were to live forever.", + "Once upon a time, in a land far, far away....", + "Sorry, the pixel fairies are taking a dust break...", + "There is no easy way from the earth to the stars." + ] +} diff --git a/AstroTests/Unit Tests/Logging/LoggerSpec.swift b/AstroTests/Unit Tests/Logging/LoggerSpec.swift new file mode 100644 index 0000000..53c66b9 --- /dev/null +++ b/AstroTests/Unit Tests/Logging/LoggerSpec.swift @@ -0,0 +1,144 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// 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 Quick +import Nimble +@testable import Astro + +class LogSpec: QuickSpec { + + override func spec() { + + class LogRecorder: Logger { + var messages = [String]() + + func log(level: Log.Level, message: String) { + messages.append(message) + } + } + + let generateLogs = { () -> () in + Log.debug("debug") + Log.info("info") + Log.warn("warn") + Log.error("error") + } + + var recorder: LogRecorder! + var defaultLogger: Logger! + var defaultLevel: Log.Level! + + beforeEach { + // remember the logger before replacing it + defaultLogger = Log.logger + defaultLevel = Log.level + + recorder = LogRecorder() + Log.logger = recorder + } + afterEach { + Log.level = defaultLevel + Log.logger = defaultLogger + } + + describe("Given we are logging at the Debug level") { + beforeEach { + Log.level = .Debug + generateLogs() + } + + it("then all messages should be logged") { + expect(recorder.messages.count).to(equal(4)) + expect(recorder.messages).to(equal(["debug", "info", "warn", "error"])) + } + } + + describe("Given we are logging at the Info level") { + beforeEach { + Log.level = .Info + + generateLogs() + } + it("then all debug messages should not be logged") { + expect(recorder.messages.count).to(equal(3)) + expect(recorder.messages).to(equal(["info", "warn", "error"])) + } + } + + describe("Given we are logging at the Warning level") { + beforeEach { + Log.level = .Warning + + generateLogs() + } + it("then neither debug nor info messages should not be logged") { + expect(recorder.messages.count).to(equal(2)) + expect(recorder.messages).to(equal(["warn", "error"])) + } + } + + describe("Given we are logging at the Error level") { + beforeEach { + Log.level = .Error + + generateLogs() + } + it("then only error messages should be logged") { + expect(recorder.messages.count).to(equal(1)) + expect(recorder.messages).to(equal(["error"])) + } + } + + describe("Given we are logging at the Silent level") { + beforeEach { + Log.level = .Silent + + generateLogs() + } + it("then nothing should be logged") { + expect(recorder.messages.count).to(equal(0)) + } + } + + struct VeryExpensiveThingToPrint : CustomStringConvertible { + static let interval: NSTimeInterval = 100 + static let testThreshold: NSTimeInterval = 10 + + var description: String { + NSThread.sleepForTimeInterval(VeryExpensiveThingToPrint.interval) + return "thing" + } + } + + describe("Given we are logging a really expensive statement") { + + let thing = VeryExpensiveThingToPrint() + var logInterval: NSTimeInterval! + + beforeEach { + Log.level = .Silent + + let start = NSDate() + Log.debug("Really expensive log statement: \(thing)") + + logInterval = NSDate().timeIntervalSinceDate(start) + } + context("when that statement is not displayed because it's exclude by the logging level") { + it("then it should not log anything") { + expect(recorder.messages.count).to(equal(0)) + } + it("then it should not incur expensive log overhead if not actually logged") { + expect(logInterval).to(beLessThan(VeryExpensiveThingToPrint.testThreshold )) + } + } + } + } +} \ No newline at end of file diff --git a/AstroTests/Unit Tests/Networking/HTTPStatusCodeSpec.swift b/AstroTests/Unit Tests/Networking/HTTPStatusCodeSpec.swift new file mode 100644 index 0000000..083155c --- /dev/null +++ b/AstroTests/Unit Tests/Networking/HTTPStatusCodeSpec.swift @@ -0,0 +1,83 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// 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 Quick +import Nimble +@testable import Astro + +class HTTPStatusCodeSpec: QuickSpec { + override func spec() { + describe("init(intValue:) - Given we are creating a new HTTPStatusCode") { + context("when using an enum value that exists") { + it("then we should get the expected status code") { + // Arrange + // Act + let statusCode = HTTPStatusCode(intValue: HTTPStatusCode.Code200OK.rawValue) + // Assert + expect(statusCode).to(equal(HTTPStatusCode.Code200OK)) + } + } + context("when using an enum value that does not exist") { + it("then we should get the invalid status code") { + // Arrange + // Act + let statusCode = HTTPStatusCode(intValue: 100000) + // Assert + expect(statusCode).to(beNil()) + } + } + } + + describe("Given a Status Code") { + context("when the code between 100 and 199"){ + it("then it should have an informational status"){ + expect(HTTPStatusCode.Code100Continue.isInformational).to(beTrue()) + expect(HTTPStatusCode.Code200OK.isInformational).to(beFalse()) + } + } + context("when the code between 200 and 299"){ + it("then it should have a successful status"){ + expect(HTTPStatusCode.Code101SwitchingProtocols.isSuccessful).to(beFalse()) + expect(HTTPStatusCode.Code200OK.isSuccessful).to(beTrue()) + expect(HTTPStatusCode.Code300MultipleChoices.isSuccessful).to(beFalse()) + } + } + context("when the code between 300 and 399"){ + it("then should have a redirection status"){ + expect(HTTPStatusCode.Code206PartialContent.isRedirection).to(beFalse()) + expect(HTTPStatusCode.Code300MultipleChoices.isRedirection).to(beTrue()) + expect(HTTPStatusCode.Code400BadRequest.isRedirection).to(beFalse()) + } + } + context("when the code between 400 and 499"){ + it("then should have a client error status"){ + expect(HTTPStatusCode.Code307TemporaryRedirect.isClientError).to(beFalse()) + expect(HTTPStatusCode.Code400BadRequest.isClientError).to(beTrue()) + expect(HTTPStatusCode.Code500InternalServerError.isClientError).to(beFalse()) + expect(HTTPStatusCode.Code429TooManyRequests.isClientError).to(beTrue()) + } + it("is an error") { + expect(HTTPStatusCode.Code307TemporaryRedirect.isError).to(beFalse()) + expect(HTTPStatusCode.Code400BadRequest.isError).to(beTrue()) + } + } + context("when the code between 500 and 599"){ + it("then should have a server error status"){ + expect(HTTPStatusCode.Code417ExpectationFailed.isServerError).to(beFalse()) + expect(HTTPStatusCode.Code500InternalServerError.isServerError).to(beTrue()) + } + it("is an error"){ + expect(HTTPStatusCode.Code500InternalServerError.isError).to(beTrue()) + } + } + } + } +} diff --git a/AstroTests/Unit Tests/Networking/NetworkServiceSpec.swift b/AstroTests/Unit Tests/Networking/NetworkServiceSpec.swift new file mode 100644 index 0000000..ad39297 --- /dev/null +++ b/AstroTests/Unit Tests/Networking/NetworkServiceSpec.swift @@ -0,0 +1,475 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// 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 Quick +import Nimble +import Nocilla +import Alamofire +import Freddy +import SwiftTask +@testable import Astro + +class NetworkServiceSpec: QuickSpec { + override func spec() { + beforeSuite { + LSNocilla.sharedInstance().start() + } + afterSuite { + LSNocilla.sharedInstance().stop() + } + afterEach { + LSNocilla.sharedInstance().clearStubs() + } + + describe("NetworkService") { + var subject: NetworkService! + var userJSON: JSON! + var userArrayJSON: JSON! + var request: NSMutableURLRequest! + let expectedUser = User(userID: "1", email: "user@example.com") + + beforeEach { + subject = NetworkService() + userJSON = [ + "id": "1", + "email": "user@example.com", + ] + userArrayJSON = [userJSON, userJSON] + request = NSMutableURLRequest(URL: NSURL(string: "https://example.com/path")!) + } + + describe(".requestJSONDictionary") { + var dictTask: Task, NetworkError>! + + describe("success") { + beforeEach { + stubAnyRequest().andReturn(.Code200OK).withJSON(userJSON) + dictTask = subject.requestJSONDictionary(request) + } + + it("task should be fulfilled") { + expect(dictTask.state).toEventually(equal(TaskState.Fulfilled)) + } + it("should eventually return token JSON") { + expect({ + dictTask.value != nil ? JSON.Dictionary(dictTask.value!.value) : nil + }()).toEventually(equal(userJSON)) + } + } + + describe("401 Unauthorized") { + beforeEach { + stubAnyRequest().andReturn(.Code401Unauthorized).withJSON(["Error": "Unauthorized"]) + dictTask = subject.requestJSONDictionary(request) + } + + it("task should be rejected") { + expect(dictTask.state).toEventually(equal(TaskState.Rejected)) + } + it("errors on status code") { + expect((dictTask.errorInfo?.error?.error as? NSError)?.code).toEventually(equal(Error.Code.StatusCodeValidationFailed.rawValue), timeout: 1) + } + } + + describe("connection error") { + var connectionError: NSError! + + beforeEach { + connectionError = NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotConnectToHost, userInfo:nil) + + stubAnyRequest().andFailWithError(connectionError) + dictTask = subject.requestJSONDictionary(request) + } + + it("task should be rejected") { + expect(dictTask.state).toEventually(equal(TaskState.Rejected)) + } + it("error should be connectionError") { + expect(dictTask.errorInfo?.error?.error as? NSError).toEventually(equal(connectionError)) + } + } + + describe("invalid JSON in response") { + beforeEach { + stubAnyRequest().andReturn(.Code200OK).withBody("not valid JSON!") + dictTask = subject.requestJSONDictionary(request) + } + + it("task should be rejected") { + expect(dictTask.state).toEventually(equal(TaskState.Rejected)) + } + it("should fail to parse json") { + expect((dictTask.errorInfo?.error?.error as? NSError)?.domain).toEventually(equal("Freddy.JSONParser.Error")) + } + } + + describe("received json [] instead of {}") { + beforeEach { + stubAnyRequest().andReturn(.Code200OK).withJSON([]) + dictTask = subject.requestJSONDictionary(request) + } + + it("task should be rejected") { + expect(dictTask.state).toEventually(equal(TaskState.Rejected)) + } + it("should fail to parse json") { + let expectedError = JSON.Error.ValueNotConvertible(value: [], to: Swift.Dictionary) + expect({ + dictTask.errorInfo?.error?.error as? JSON.Error + }()).toEventually(equal(expectedError)) + } + } + } + + describe(".requestJSONArray -> JSON") { + var arrayTask: Task, NetworkError>! + context("Given a successful response (200 OK)") { + context("with a valid array") { + beforeEach { + stubAnyRequest().andReturn(.Code200OK).withJSON(userArrayJSON) + arrayTask = subject.requestJSONArray(request) + } + it("then it should fulfill with the correct user JSON") { + expect(arrayTask.state).toEventually(equal(TaskState.Fulfilled)) + expect(arrayTask.value?.value.count).toEventually(equal(2)) + expect(arrayTask.value?.value[0]).toEventually(equal(userJSON)) + expect(arrayTask.value?.value[1]).toEventually(equal(userJSON)) + } + } + context("with an empty response") { + beforeEach { + stubAnyRequest().andReturn(.Code200OK) + arrayTask = subject.requestJSONArray(request) + } + it("then the task should be rejected") { + expect(arrayTask.state).toEventually(equal(TaskState.Rejected)) + } + } + } + context("Given a failed status code (404 Not Found)") { + beforeEach { + stubAnyRequest().andReturn(.Code404NotFound).withJSON(userJSON) + arrayTask = subject.requestJSONArray(request) + } + it("then task should be rejected") { + expect(arrayTask.state).toEventually(equal(TaskState.Rejected)) + } + } + + describe("Given a invalid json {} instead of []") { + beforeEach { + stubAnyRequest().andReturn(.Code200OK).withJSON([:]) + arrayTask = subject.requestJSONArray(request) + } + it("task should be rejected") { + expect(arrayTask.state).toEventually(equal(TaskState.Rejected)) + } + } + } + + describe(".requestJSONArray -> JSON?") { + var arrayTask: Task, NetworkError>! + context("Given a successful response (200 OK)") { + context("with a valid array") { + beforeEach { + stubAnyRequest().andReturn(.Code200OK).withJSON(userArrayJSON) + arrayTask = subject.requestJSONArray(request) + } + it("then it should fulfill with the correct user JSON") { + expect(arrayTask.state).toEventually(equal(TaskState.Fulfilled)) + expect(arrayTask.value?.value?.count).toEventually(equal(2)) + expect(arrayTask.value?.value?[0]).toEventually(equal(userJSON)) + expect(arrayTask.value?.value?[1]).toEventually(equal(userJSON)) + } + } + context("with an empty response") { + beforeEach { + stubAnyRequest().andReturn(.Code200OK) + arrayTask = subject.requestJSONArray(request) + } + it("then the task should be fulfilled") { + expect(arrayTask.state).toEventually(equal(TaskState.Fulfilled)) + } + it("then the response should be nil") { + expect(arrayTask.state).toEventually(equal(TaskState.Fulfilled)) + expect(arrayTask.value?.value).to(beNil()) + } + } + } + context("Given a failed status code (404 Not Found)") { + beforeEach { + stubAnyRequest().andReturn(.Code404NotFound).withJSON(userJSON) + arrayTask = subject.requestJSONArray(request) + } + it("then task should be rejected") { + expect(arrayTask.state).toEventually(equal(TaskState.Rejected)) + } + } + + describe("Given a invalid json {} instead of []") { + beforeEach { + stubAnyRequest().andReturn(.Code200OK).withJSON([:]) + arrayTask = subject.requestJSONArray(request) + } + it("task should be rejected") { + expect(arrayTask.state).toEventually(equal(TaskState.Rejected)) + } + } + } + + describe(".requestJSON -> JSON") { + var task: Task, NetworkError>! + context("given a successful response (200 OK)") { + context("with a valid object") { + beforeEach { + stubAnyRequest().andReturn(.Code200OK).withJSON(userJSON) + task = subject.requestJSON(request) + } + it("then it should fulfill with the correct JSON") { + expect({ () -> JSON? in + guard let data = task.value?.response?.data else { return nil } + return try? JSON(data: data) + }()).toEventually(equal(userJSON)) + } + it("then the response should contain the expected User") { + expect(task.value?.value).toEventually(equal(userJSON)) + } + } + context("with an empty response") { + beforeEach { + stubAnyRequest().andReturn(.Code200OK) + task = subject.requestJSON(request) + } + it("then the task should be rejected") { + expect(task.state).toEventually(equal(TaskState.Rejected)) + } + } + } + context("with a failed status code (404 Not Found)") { + beforeEach { + stubAnyRequest().andReturn(.Code404NotFound).withJSON(userJSON) + task = subject.requestJSON(request) + } + it("then task should be rejected") { + expect(task.state).toEventually(equal(TaskState.Rejected)) + } + it("then the response should not return any JSON"){ + expect(task.state).toEventually(equal(TaskState.Rejected)) + expect(task.value?.value).to(beNil()) + } + it("then the response.data should still return the unparsed JSON"){ + expect({ () -> JSON? in + guard let data = task.errorInfo?.error?.response?.data else { return nil } + return try? JSON(data: data) + }()).toEventually(equal(userJSON)) + } + } + } + + describe(".request - Given a request to deserialize an object") { + var task: Task, NetworkError>! + context("given a successful response (200 OK)") { + context("with a valid object") { + beforeEach { + stubAnyRequest().andReturn(.Code200OK).withJSON(userJSON) + task = subject.request(request) + } + it("then it should fulfill with the correct JSON") { + expect({ () -> JSON? in + guard let data = task.value?.response?.data else { return nil } + return try? JSON(data: data) + }()).toEventually(equal(userJSON)) + } + it("then the response should contain the expected User") { + expect(task.value?.value).toEventually(equal(expectedUser)) + } + } + context("with an empty response") { + + beforeEach { + stubAnyRequest().andReturn(.Code200OK) + task = subject.request(request) + } + it("then the task should be rejected") { + expect(task.state).toEventually(equal(TaskState.Rejected)) + } + } + } + context("with a failed status code (404 Not Found)") { + beforeEach { + stubAnyRequest().andReturn(.Code404NotFound).withJSON(userJSON) + task = subject.request(request) + } + it("then task should be rejected") { + expect(task.state).toEventually(equal(TaskState.Rejected)) + } + } + } + describe(".request - Given a request to deserialize an nillable object") { + var task: Task, NetworkError>! + context("Given a successful response (200 OK)") { + context("with a valid object") { + beforeEach { + stubAnyRequest().andReturn(.Code200OK).withJSON(userJSON) + task = subject.request(request) + } + it("then it should fulfills with the correct JSON") { + expect({ () -> JSON? in + guard let data = task.value?.response?.data else { return nil } + return try? JSON(data: data) + }()).toEventually(equal(userJSON)) + } + it("then the response should contain the expected User") { + expect(task.value?.value).toEventually(equal(expectedUser)) + } + } + context("with an empty response") { + beforeEach { + stubAnyRequest().andReturn(.Code200OK) + task = subject.request(request) + } + it("then the task should be fulfilled") { + expect(task.state).toEventually(equal(TaskState.Fulfilled)) + } + it("then the response should be nil") { + expect(task.state).toEventually(equal(TaskState.Fulfilled)) + expect(task.value?.value).to(beNil()) + } + } + } + context("Given a failed status code (404 Not Found)") { + beforeEach { + stubAnyRequest().andReturn(.Code404NotFound).withJSON(userJSON) + task = subject.request(request) + } + it("then task should be rejected") { + expect(task.state).toEventually(equal(TaskState.Rejected)) + } + } + } + describe(".request<[T]> - Given a request to deserialize an array of objects") { + var task: Task, NetworkError>! + context("Given a successful response (200 OK)") { + context("with a valid array") { + beforeEach { + stubAnyRequest().andReturn(.Code200OK).withJSON(userArrayJSON) + task = subject.request(request) + } + it("then it should fulfill with the correct Users") { + expect(task.state).toEventually(equal(TaskState.Fulfilled)) + expect(task.value?.value.count).toEventually(equal(2)) + expect(task.value?.value[0]).toEventually(equal(expectedUser)) + expect(task.value?.value[1]).toEventually(equal(expectedUser)) + } + } + context("with an empty response") { + beforeEach { + stubAnyRequest().andReturn(.Code200OK) + task = subject.request(request) + } + it("then the task should be rejected") { + expect(task.state).toEventually(equal(TaskState.Rejected)) + } + } + } + context("Given a failed status code (404 Not Found)") { + beforeEach { + stubAnyRequest().andReturn(.Code404NotFound).withJSON(userJSON) + task = subject.request(request) + } + it("then task should be rejected") { + expect(task.state).toEventually(equal(TaskState.Rejected)) + } + } + } + describe(".request<[T]?> - Given a request to deserialize a nillable array of object") { + var task: Task, NetworkError>! + context("Given a successful response (200 OK)") { + context("with a valid array") { + beforeEach { + stubAnyRequest().andReturn(.Code200OK).withJSON(userArrayJSON) + task = subject.request(request) + } + it("then it should fulfill with the correct user") { + expect(task.state).toEventually(equal(TaskState.Fulfilled)) + expect(task.value?.value?.count).toEventually(equal(2)) + expect(task.value?.value?[0]).toEventually(equal(expectedUser)) + expect(task.value?.value?[1]).toEventually(equal(expectedUser)) + } + } + context("with an empty response") { + beforeEach { + stubAnyRequest().andReturn(.Code200OK) + task = subject.request(request) + } + it("then the task should be fulfilled") { + expect(task.state).toEventually(equal(TaskState.Fulfilled)) + } + it("then the response should be nil") { + expect(task.state).toEventually(equal(TaskState.Fulfilled)) + expect(task.value?.value).to(beNil()) + } + } + } + context("Given a failed status code (404 Not Found)") { + beforeEach { + stubAnyRequest().andReturn(.Code404NotFound).withJSON(userJSON) + task = subject.request(request) + } + it("then task should be rejected") { + expect(task.state).toEventually(equal(TaskState.Rejected)) + } + } + } + } + } +} + +// Should PR this into Freddy +extension JSON.Error: Equatable {} +public func ==(a: JSON.Error, b: JSON.Error) -> Bool { + switch (a, b) { + case (.ValueNotConvertible(let lhsValue, let lhsTo), .ValueNotConvertible(let rhsValue, let rhsTo)): + return rhsValue == lhsValue && + rhsTo == lhsTo + case (.UnexpectedSubscript(let lhsType), .UnexpectedSubscript(let rhsType)): + return lhsType == rhsType + case (.KeyNotFound(let lhsKey), .KeyNotFound(let rhsKey)): + return lhsKey == rhsKey + case (.IndexOutOfBounds(let lhsIndex), .IndexOutOfBounds(let rhsIndex)): + return lhsIndex == rhsIndex + default: return false + } +} + +// Improved DSL for Nocilla + +func stubRoute(route: Route) -> LSStubRequestDSL { + return stubRequest(route.method.rawValue, route.URL.absoluteString).withHeaders(route.URLRequest.allHTTPHeaderFields).withBody(route.URLRequest.HTTPBody) +} + +extension LSStubRequestDSL { + func andReturn(status: HTTPStatusCode) -> LSStubResponseDSL { + return andReturn(status.rawValue) + } +} + +extension LSStubResponseDSL { + func withJSON(json: JSON) -> LSStubResponseDSL { + let body = try? json.serialize() ?? NSData() + return withHeader("Content-Type", "application/json").withBody(body) + } +} + +func stubAnyRequest() -> LSStubRequestDSL { + return stubRequest(nil, ".*".regex()) +} + diff --git a/AstroTests/Unit Tests/Networking/User.swift b/AstroTests/Unit Tests/Networking/User.swift new file mode 100644 index 0000000..82d4616 --- /dev/null +++ b/AstroTests/Unit Tests/Networking/User.swift @@ -0,0 +1,46 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// 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 Freddy + +struct User { + let userID: String + let email: String +} + +extension User: JSONDecodable { + init(json: JSON) throws { + // Extract id as a string or a int + if let userID = try? json.string("id") { + self.userID = userID + } else { + let userID = try json.int("id") + self.userID = String(userID) + } + + email = try json.string("email") + } +} + +extension User: JSONEncodable { + func toJSON() -> JSON { + return .Dictionary([ + "id": .String(userID), + "email": .String(email) + ]) + } +} + +extension User: Equatable {} +func ==(lhs: User, rhs: User) -> Bool { + return lhs.email == rhs.email && + lhs.userID == rhs.userID +} diff --git a/AstroTests/Unit Tests/Security/KeychainAccessSpec.swift b/AstroTests/Unit Tests/Security/KeychainAccessSpec.swift new file mode 100644 index 0000000..9661d8c --- /dev/null +++ b/AstroTests/Unit Tests/Security/KeychainAccessSpec.swift @@ -0,0 +1,148 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// 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 Quick +import Nimble +@testable import Astro + +class KeychainAccessSpec: QuickSpec { + + override func spec() { + + describe("A keychain") { + let keychain = KeychainAccess(account: "Test@RobotsAndPencils.com") + var testKey = "AccessKey" + + afterEach { + keychain.delete(testKey) + } + + it("returns nil for retrieving a key that doesn't exist") { + let storedString = keychain.getString(testKey) + expect(storedString).to(beNil()) + } + + it("can store and retrieve a string") { + let testString = "something really boring" + keychain.putString(testKey, value: testString) + + let storedString = keychain.getString(testKey) + expect(storedString).to(equal(testString)) + } + + it("can store and retrieve data") { + testKey = "DataKey" + guard let testFilePath = NSBundle(forClass: KeychainAccessSpec.self).pathForResource("testdata", ofType: "json") else { + fail("no test file") + return + } + let testData = NSData(contentsOfFile: testFilePath) + keychain.put(testKey, data: testData) + + let storedData = keychain.get(testKey) + expect(storedData).toNot(beNil()) + expect(storedData).to(equal(testData)) + } + + it("can set a string value to nil") { + keychain.putString(testKey, value: nil) + + let storedString = keychain.getString(testKey) + expect(storedString).to(beNil()) + } + + it("can set a data value to nil") { + keychain.putString(testKey, value: nil) + + let storedData = keychain.get(testKey) + expect(storedData).to(beNil()) + } + + it("can be accessed using subscripting for strings") { + let testString = "something slightly less boring" + keychain[testKey] = testString + + let storedString = keychain[testKey] + expect(storedString).to(equal(testString)) + } + + it("can be accessed using subscripting for data") { + testKey = "DataKey" + guard let testFilePath = NSBundle(forClass: KeychainAccessSpec.self).pathForResource("testdata", ofType: "json") else { + fail("no test file") + return + } + let testData = NSData(contentsOfFile: testFilePath) + keychain[data: testKey] = testData + + let storedData = keychain[data: testKey] + expect(storedData).toNot(beNil()) + expect(storedData).to(equal(testData)) + } + + it("can override a value") { + let origString = "exciting stuff?" + let finalString = "boring stuff?" + + keychain.putString(testKey, value: origString) + let storedOrigString = keychain.getString(testKey) + expect(storedOrigString).to(equal(origString)) + + keychain.putString(testKey, value: finalString) + let storedFinalString = keychain.getString(testKey) + expect(storedFinalString).to(equal(finalString)) + } + + it("can delete a value") { + let testString = "exciting stuff?" + keychain.putString(testKey, value: testString) + let storedString = keychain.getString(testKey) + keychain.putString(testKey, value: nil) + + let storedNil = keychain.getString(testKey) + expect(storedString).to(equal(testString)) + expect(storedNil).to(beNil()) + } + + it("can delete all keys and data for the app") { + // Push in a key/data element and verify it exists + let testString = "exciting stuff?" + keychain.putString(testKey, value: testString) + var storedString = keychain.getString(testKey) + expect(storedString).to(equal(testString)) + + // Delete everything and then verify you can't access the key/data any more + let status = keychain.deleteAllKeysAndDataForApp() + expect(status).to(beTrue()) + storedString = keychain.getString(testKey) + expect(storedString).to(beNil()) + } + + it("can't access a key from a different account") { + testKey = "SuperSecretKey" + let testString = "you can't see me" + + // Push in a key/data element and verify it exists in the main account + keychain.putString(testKey, value: testString) + var storedString = keychain.getString(testKey) + expect(storedString).to(equal(testString)) + + // Try to gain access to a key from another account + let otherKeychain = KeychainAccess(account: "SomeOtherAccount@RobotsAndPencils.com") + storedString = otherKeychain.getString(testKey) + expect(storedString).to(beNil()) + } + + } + + } + +} diff --git a/AstroTests/Unit Tests/UI/LayoutLabelSpec.swift b/AstroTests/Unit Tests/UI/LayoutLabelSpec.swift new file mode 100644 index 0000000..f1e81d2 --- /dev/null +++ b/AstroTests/Unit Tests/UI/LayoutLabelSpec.swift @@ -0,0 +1,103 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// 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 Quick +import Nimble +@testable import Astro + +let mockFrame = CGRectMake(1, 2, 3, 4) + +class LayoutLabelSpec: QuickSpec { + override func spec() { + describe("Given a LayoutLabel") { + let label = LayoutLabel(frame: mockFrame) + + context("when layoutSubviews is called and numberOfLines is set to 0 ") { + beforeEach { + //Arrange + label.numberOfLines = 0 + + //Act + label.layoutSubviews() + } + + it("then the preferred max width should equal the frame width") { + //Assert + expect(label.preferredMaxLayoutWidth).to(equal(label.frame.size.width)) + } + } + + context("when intrinsicContentSize is called") { + + let comparableLabel = UILabel(frame: mockFrame) + + context("and numberOfLines is set to 0") { + beforeEach { + //Arrange + label.numberOfLines = 0 + comparableLabel.numberOfLines = 0 + } + + context("and text is empty") { + beforeEach { + //Arrange + label.text = "" + comparableLabel.text = "" + } + + it("then contentSize should remain the same") { + //Act + let contentSize = label.intrinsicContentSize() + let comparableContentSize = comparableLabel.intrinsicContentSize() + + //Assert + expect(contentSize.height).to(equal(comparableContentSize.height)) + } + } + + context("and text is not empty") { + beforeEach { + //Arrange + label.text = "a" + comparableLabel.text = "a" + } + + it("then contentSize should be 1pt taller") { + //Act + let contentSize = label.intrinsicContentSize() + let comparableContentSize = comparableLabel.intrinsicContentSize() + + //Assert + expect(contentSize.height).to(equal(comparableContentSize.height+1)) + } + } + } + + context("and numberOfLines is not 0") { + beforeEach { + //Arrange + label.numberOfLines = 1 + comparableLabel.numberOfLines = 1 + } + + it("then content size should remain the same") { + //Act + let contentSize = label.intrinsicContentSize() + let comparableContentSize = comparableLabel.intrinsicContentSize() + + //Assert + expect(contentSize.height).to(equal(comparableContentSize.height)) + } + } + } + } + } +} diff --git a/AstroTests/Unit Tests/UI/NibLoadableViewSpec.swift b/AstroTests/Unit Tests/UI/NibLoadableViewSpec.swift new file mode 100644 index 0000000..a120eeb --- /dev/null +++ b/AstroTests/Unit Tests/UI/NibLoadableViewSpec.swift @@ -0,0 +1,26 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// 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 Quick +import Nimble +@testable import Astro + +class MockNibLoadableCollectionViewCell: UICollectionViewCell, NibLoadableView {} + +class NibLoadableViewSpec: QuickSpec { + override func spec() { + describe("Given a view subclass conforming to NibLoadableView") { + it("should have a default nib name") { + expect(MockNibLoadableCollectionViewCell.nibName).to(equal("MockNibLoadableCollectionViewCell")) + } + } + } +} diff --git a/AstroTests/Unit Tests/UI/ReusableViewSpec.swift b/AstroTests/Unit Tests/UI/ReusableViewSpec.swift new file mode 100644 index 0000000..c237cb6 --- /dev/null +++ b/AstroTests/Unit Tests/UI/ReusableViewSpec.swift @@ -0,0 +1,26 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// 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 Quick +import Nimble +@testable import Astro + +class MockReusableCollectionViewCell: UICollectionViewCell, ReusableView {} + +class ReusableViewSpec: QuickSpec { + override func spec() { + describe("Given a view subclass conforming to ReusableView") { + it("should have a default reuse identifier") { + expect(MockReusableCollectionViewCell.defaultReuseIdentifier).to(equal("MockReusableCollectionViewCell")) + } + } + } +} diff --git a/AstroTests/Unit Tests/UI/UIColor+AstroGadgetsSpec.swift b/AstroTests/Unit Tests/UI/UIColor+AstroGadgetsSpec.swift new file mode 100644 index 0000000..4d3aba1 --- /dev/null +++ b/AstroTests/Unit Tests/UI/UIColor+AstroGadgetsSpec.swift @@ -0,0 +1,124 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// 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 Quick +import Nimble +@testable import Astro + +class UIColor_AstroGadgetsSpec: QuickSpec { + override func spec() { + describe("init(hexColor:)") { + var hexString: String! + + context("00") { + it("returns nil") { + hexString = "00" + let subject = UIColor(hexString: hexString) + expect(subject).to(beNil()) + } + } + + context("AABBCC") { + it("correctly deserializes the color") { + hexString = "AABBCC" + let subject = UIColor(hexString: hexString) + expect(subject).to(equal(UIColor(red: 0xAA/255.0, green: 0xBB/255.0, blue: 0xCC/255.0, alpha: 0xFF/255.0))) + } + } + + context("aabbcc") { + it("correctly deserializes the color") { + hexString = "aabbcc" + let subject = UIColor(hexString: hexString) + expect(subject).to(equal(UIColor(red: 0xAA/255.0, green: 0xBB/255.0, blue: 0xCC/255.0, alpha: 0xFF/255.0))) + } + } + + context("000000") { + it("correctly deserializes the color") { + hexString = "000000" + let subject = UIColor(hexString: hexString) + expect(subject).to(equal(UIColor(red: 0x00/255.0, green: 0x00/255.0, blue: 0x00/255.0, alpha: 0xFF/255.0))) + } + } + + context("#000000") { + it("correctly deserializes the color") { + hexString = "#000000" + let subject = UIColor(hexString: hexString) + expect(subject).to(equal(UIColor(red: 0x00/255.0, green: 0x00/255.0, blue: 0x00/255.0, alpha: 0xFF/255.0))) + } + } + + context("123456") { + it("correctly deserializes the color") { + hexString = "123456" + let subject = UIColor(hexString: hexString) + expect(subject).to(equal(UIColor(red: 0x12/255.0, green: 0x34/255.0, blue: 0x56/255.0, alpha: 0xFF/255.0))) + } + } + + context("AABBCCDD") { + it("correctly deserializes the color") { + hexString = "AABBCCDD" + let subject = UIColor(hexString: hexString) + expect(subject).to(equal(UIColor(red: 0xAA/255.0, green: 0xBB/255.0, blue: 0xCC/255.0, alpha: 0xDD/255.0))) + } + } + } + + describe("hexRGB()") { + context("AABBCC") { + it("correctly serializes the color") { + let subject = UIColor(red: 0xAA/255.0, green: 0xBB/255.0, blue: 0xCC/255.0, alpha: 0xDD/255.0).hexRGB() + expect(subject).to(equal("AABBCC")) + } + } + + context("AABBCC") { + it("correctly serializes the color") { + let subject = UIColor(red: 0xAA/255.0, green: 0xBB/255.0, blue: 0xCC/255.0, alpha: 0x00/255.0).hexRGB() + expect(subject).to(equal("AABBCC")) + } + } + + context("000000") { + it("correctly serializes the color") { + let subject = UIColor(red: 0x00/255.0, green: 0x00/255.0, blue: 0x00/255.0, alpha: 0xFF/255.0).hexRGB() + expect(subject).to(equal("000000")) + } + } + + context("01AF97") { + it("correctly serializes the color with alpha") { + let subject = UIColor(red: 0x01/255.0, green: 0xAF/255.0, blue: 0x97/255.0, alpha: 0x00/255.0).hexRGB() + expect(subject).to(equal("01AF97")) + } + } + } + + describe("hexRGBA()") { + context("AABBCCDD") { + it("correctly serializes the color with alpha") { + let subject = UIColor(red: 0xAA/255.0, green: 0xBB/255.0, blue: 0xCC/255.0, alpha: 0xDD/255.0).hexRGBA() + expect(subject).to(equal("AABBCCDD")) + } + } + + context("AABBCC00") { + it("correctly serializes the color with alpha") { + let subject = UIColor(red: 0xAA/255.0, green: 0xBB/255.0, blue: 0xCC/255.0, alpha: 0x00/255.0).hexRGBA() + expect(subject).to(equal("AABBCC00")) + } + } + } + } +} diff --git a/AstroTests/Unit Tests/UI/UIView+AstroGadgetsSpec.swift b/AstroTests/Unit Tests/UI/UIView+AstroGadgetsSpec.swift new file mode 100644 index 0000000..17d939d --- /dev/null +++ b/AstroTests/Unit Tests/UI/UIView+AstroGadgetsSpec.swift @@ -0,0 +1,82 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// 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 Quick +import Nimble +@testable import Astro + +class UIView_AstroGadgetsSpec: QuickSpec { + override func spec() { + describe("Given a UIView with a defined frame") { + let view = UIView() + beforeEach(){ + // Arrange + view.frame = CGRectMake(1, 2, 3, 4) + } + context("when updating a frame property") { + it("then the frameSize should match") { + // Arrange + let expectedSize = CGSizeMake(23, 45) + // Act + view.frameSize = expectedSize + // Assert + expect(view.frameSize).to(equal(expectedSize)) + expect(view.frame.size).to(equal(expectedSize)) + } + it ("then the frameHeight should match") { + // Arrange + let expectedHeight:CGFloat = 12.0 + // Act + view.frameHeight = expectedHeight + // Assert + expect(view.frameHeight).to(equal(expectedHeight)) + expect(view.frame.size.height).to(equal(expectedHeight)) + } + it ("then the frameWidth should match") { + // Arrange + let expectedWidth:CGFloat = 347.0 + // Act + view.frameWidth = expectedWidth + // Assert + expect(view.frameWidth).to(equal(expectedWidth)) + expect(view.frame.size.width).to(equal(expectedWidth)) + } + it ("then the frameOrigin should match") { + // Arrange + let expectedOrigin = CGPointMake(67,89) + // Act + view.frameOrigin = expectedOrigin + // Assert + expect(view.frameOrigin).to(equal(expectedOrigin)) + expect(view.frame.origin).to(equal(expectedOrigin)) + } + it ("then the frameX should match") { + // Arrange + let expectedX:CGFloat = 567.0 + // Act + view.frameX = expectedX + // Assert + expect(view.frameX).to(equal(expectedX)) + expect(view.frame.origin.x).to(equal(expectedX)) + } + it ("then the frameY should match") { + // Arrange + let expectedY:CGFloat = 678.0 + // Act + view.frameY = expectedY + // Assert + expect(view.frameY).to(equal(expectedY)) + expect(view.frame.origin.y).to(equal(expectedY)) + } + } + } + } +} diff --git a/AstroTests/Unit Tests/UI/UIViewController+AstroGadgetsSpec.swift b/AstroTests/Unit Tests/UI/UIViewController+AstroGadgetsSpec.swift new file mode 100644 index 0000000..8a47130 --- /dev/null +++ b/AstroTests/Unit Tests/UI/UIViewController+AstroGadgetsSpec.swift @@ -0,0 +1,44 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// 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 Quick +import Nimble +@testable import Astro + +class UIViewController_AstroGadgetsSpec: QuickSpec { + override func spec() { + describe("addChildViewController() - Given a view controller") { + var parentViewController:UIViewController! + var childViewController:UIViewController! + + context("when adding a child view controller") { + beforeEach(){ + // Arrange + parentViewController = UIViewController() + parentViewController.view = UIView() + childViewController = UIViewController() + childViewController.view = UIView() + // Act + parentViewController.addChildViewController(childViewController, inContainer: parentViewController.view) + } + + it("then the child view controller should have been added") { + // Assert + expect(parentViewController.childViewControllers[0]).to(equal(childViewController)) + } + it("then the child view controller view should be added to the given view") { + // Assert + expect(parentViewController.view.subviews[0]).to(equal(childViewController.view)) + } + } + } + } +} diff --git a/AstroTests/Unit Tests/Utils/EnumCountableSpec.swift b/AstroTests/Unit Tests/Utils/EnumCountableSpec.swift new file mode 100644 index 0000000..ea40a90 --- /dev/null +++ b/AstroTests/Unit Tests/Utils/EnumCountableSpec.swift @@ -0,0 +1,62 @@ +// Copyright © 2016 Robots and Pencils, Inc. All rights reserved. +// +// 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: +// +// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +// +// 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 Quick +import Nimble +@testable import Astro + +class EnumCountableSpec: QuickSpec { + + private enum Enum2: Int, EnumCountable { + case case1 = 0 + case case2 + + static let count = Enum2.countCases() + } + + private enum Enum6: Int, EnumCountable { + case case1 = 0 + case case2 + case case3 + case case4 + case case5 + case case6 + + static let count = Enum6.countCases() + } + + private enum EnumBad: Int, EnumCountable { + case case1 = 5 + case case2 + + static let count = EnumBad.countCases() + } + + override func spec() { + describe("Given you have an enum") { + context("with 2 cases") { + it("the count should be 2") { + expect(Enum2.count).to(equal(2)) + } + } + context("with 6 cases") { + it("the count should be 6") { + expect(Enum6.count).to(equal(6)) + } + } + context("with 2 cases, but the first case does not start at 0") { + it("the count should be 0") { + expect(EnumBad.count).to(equal(0)) + } + } + } + } +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..eea29fe --- /dev/null +++ b/LICENSE @@ -0,0 +1,11 @@ +Astro + +Copyright © 2016 Robots and Pencils, Inc. All rights reserved. + +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: + +Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +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. \ No newline at end of file diff --git a/Podfile b/Podfile new file mode 100644 index 0000000..3732cf2 --- /dev/null +++ b/Podfile @@ -0,0 +1,19 @@ +platform :ios, '8.0' + +# ignore all warnings from all pods +inhibit_all_warnings! +use_frameworks! + +source 'https://github.com/CocoaPods/Specs.git' + +target 'Astro' do + pod "Astro", :path => "." + + target 'AstroTests' do + inherit! :search_paths + + pod 'Quick', '~> 0.9' + pod 'Nimble', '~> 3.2' + pod 'Nocilla', '~> 0.10' + end +end diff --git a/Podfile.lock b/Podfile.lock new file mode 100644 index 0000000..0df7efb --- /dev/null +++ b/Podfile.lock @@ -0,0 +1,46 @@ +PODS: + - Alamofire (3.4.1) + - Astro (0.8.7): + - Astro/Logging (= 0.8.7) + - Astro/Networking (= 0.8.7) + - Astro/Security (= 0.8.7) + - Astro/UI (= 0.8.7) + - Astro/Utils (= 0.8.7) + - Astro/Logging (0.8.7) + - Astro/Networking (0.8.7): + - Alamofire (~> 3.3) + - Astro/Logging + - Freddy (~> 2.0) + - SwiftTask (= 5.0) + - Astro/Security (0.8.7): + - Astro/Logging + - Astro/UI (0.8.7) + - Astro/Utils (0.8.7) + - Freddy (2.1.0) + - Nimble (3.2.0) + - Nocilla (0.11.0) + - Quick (0.9.3) + - SwiftTask (5.0.0) + +DEPENDENCIES: + - Astro (from `.`) + - Nimble (~> 3.2) + - Nocilla (~> 0.10) + - Quick (~> 0.9) + +EXTERNAL SOURCES: + Astro: + :path: . + +SPEC CHECKSUMS: + Alamofire: 01a82e2f6c0f860ade35534c8dd88be61bdef40c + Astro: f82a0d1983abf285fdddb40017cdd72a5ac1fea7 + Freddy: bbdca013977db29638b24baf6572ce94452bec29 + Nimble: 703854335d181df169bbca9c97117b5cf8c47c1d + Nocilla: 7af7a386071150cc8aa5da4da97d060f049dd61c + Quick: 13a2a2b19a5d8e3ed4fd0c36ee46597fd77ebf71 + SwiftTask: 7fcd92f8ac16876e82c0e4ced0cea7e028456b6b + +PODFILE CHECKSUM: bc9ce865bd684a337e5df1b14f2a1427f0613efa + +COCOAPODS: 1.0.1 diff --git a/Pods/Alamofire/LICENSE b/Pods/Alamofire/LICENSE new file mode 100644 index 0000000..4cfbf72 --- /dev/null +++ b/Pods/Alamofire/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Pods/Alamofire/README.md b/Pods/Alamofire/README.md new file mode 100644 index 0000000..56a6771 --- /dev/null +++ b/Pods/Alamofire/README.md @@ -0,0 +1,1297 @@ +![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) + +[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg)](https://travis-ci.org/Alamofire/Alamofire) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.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/Alamofire.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire) +[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF) + +Alamofire is an HTTP networking library written in Swift. + +## Features + +- [x] Chainable Request / Response methods +- [x] URL / JSON / plist Parameter Encoding +- [x] Upload File / Data / Stream / MultipartFormData +- [x] Download using Request or Resume data +- [x] Authentication with NSURLCredential +- [x] HTTP Response Validation +- [x] TLS Certificate and Public Key Pinning +- [x] Progress Closure & NSProgress +- [x] cURL Debug Output +- [x] Comprehensive Unit Test Coverage +- [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) + +## Component Libraries + +In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. + +* [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. +* [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `NSURLSession` instances not managed by Alamofire. + +## Requirements + +- iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+ +- Xcode 7.3+ + +## Migration Guides + +- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) +- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) + +## Communication + +- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). (Tag 'alamofire') +- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). +- If you **found a bug**, open an issue. +- If you **have a feature request**, open an issue. +- If you **want to contribute**, submit a pull request. + +## Installation + +> **Embedded frameworks require a minimum deployment target of iOS 8 or OS X Mavericks (10.9).** +> +> Alamofire is no longer supported on iOS 7 due to the lack of support for frameworks. Without frameworks, running Travis-CI against iOS 7 would require a second duplicated test target. The separate test suite would need to import all the Swift files and the tests would need to be duplicated and re-written. This split would be too difficult to maintain to ensure the highest possible quality of the Alamofire ecosystem. + +### CocoaPods + +[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +> CocoaPods 0.39.0+ is required to build Alamofire 3.0.0+. + +To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '9.0' +use_frameworks! + +target '' do + pod 'Alamofire', '~> 3.4' +end +``` + +Then, run the following command: + +```bash +$ pod install +``` + +### 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 Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "Alamofire/Alamofire" ~> 3.4 +``` + +Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. + +### Manually + +If you prefer not to use either of the aforementioned dependency managers, you can integrate Alamofire into your project manually. + +#### Embedded Framework + +- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: + +```bash +$ git init +``` + +- Add Alamofire as a git [submodule](http://git-scm.com/docs/git-submodule) by running the following command: + +```bash +$ git submodule add https://github.com/Alamofire/Alamofire.git +``` + +- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. + + > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. + +- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. +- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. +- In the tab bar at the top of that window, open the "General" panel. +- Click on the `+` button under the "Embedded Binaries" section. +- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. + + > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. + +- Select the top `Alamofire.framework` for iOS and the bottom one for OS X. + + > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS` or `Alamofire OSX`. + +- And that's it! + +> The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. + +--- + +## Usage + +### Making a Request + +```swift +import Alamofire + +Alamofire.request(.GET, "https://httpbin.org/get") +``` + +### Response Handling + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .responseJSON { response in + print(response.request) // original URL request + print(response.response) // URL response + print(response.data) // server data + print(response.result) // result of response serialization + + if let JSON = response.result.value { + print("JSON: \(JSON)") + } + } +``` + +> Networking in Alamofire is done _asynchronously_. Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are [very good reasons](https://developer.apple.com/library/ios/qa/qa1693/_index.html) for doing it this way. + +> Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) is specified to handle the response once it's received. The result of a request is only available inside the scope of a response handler. Any execution contingent on the response or data received from the server must be done within a handler. + +### Validation + +By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. + +#### Manual Validation + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate(statusCode: 200..<300) + .validate(contentType: ["application/json"]) + .response { response in + print(response) + } +``` + +#### Automatic Validation + +Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() + .responseJSON { response in + switch response.result { + case .Success: + print("Validation Successful") + case .Failure(let error): + print(error) + } + } +``` + +### Response Serialization + +**Built-in Response Methods** + +- `response()` +- `responseData()` +- `responseString(encoding: NSStringEncoding)` +- `responseJSON(options: NSJSONReadingOptions)` +- `responsePropertyList(options: NSPropertyListReadOptions)` + +#### Response Handler + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() + .response { request, response, data, error in + print(request) + print(response) + print(data) + print(error) + } +``` + +> The `response` serializer does NOT evaluate any of the response data. It merely forwards on all the information directly from the URL session delegate. We strongly encourage you to leverage the other response serializers taking advantage of `Response` and `Result` types. + +#### Response Data Handler + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() + .responseData { response in + print(response.request) + print(response.response) + print(response.result) + } +``` + +#### Response String Handler + +```swift +Alamofire.request(.GET, "https://httpbin.org/get") + .validate() + .responseString { response in + print("Success: \(response.result.isSuccess)") + print("Response String: \(response.result.value)") + } +``` + +#### Response JSON Handler + +```swift +Alamofire.request(.GET, "https://httpbin.org/get") + .validate() + .responseJSON { response in + debugPrint(response) + } +``` + +#### Chained Response Handlers + +Response handlers can even be chained: + +```swift +Alamofire.request(.GET, "https://httpbin.org/get") + .validate() + .responseString { response in + print("Response String: \(response.result.value)") + } + .responseJSON { response in + print("Response JSON: \(response.result.value)") + } +``` + +### HTTP Methods + +`Alamofire.Method` lists the HTTP methods defined in [RFC 7231 §4.3](http://tools.ietf.org/html/rfc7231#section-4.3): + +```swift +public enum Method: String { + case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT +} +``` + +These values can be passed as the first argument of the `Alamofire.request` method: + +```swift +Alamofire.request(.POST, "https://httpbin.org/post") + +Alamofire.request(.PUT, "https://httpbin.org/put") + +Alamofire.request(.DELETE, "https://httpbin.org/delete") +``` + +### Parameters + +#### GET Request With URL-Encoded Parameters + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) +// https://httpbin.org/get?foo=bar +``` + +#### POST Request With URL-Encoded Parameters + +```swift +let parameters = [ + "foo": "bar", + "baz": ["a", 1], + "qux": [ + "x": 1, + "y": 2, + "z": 3 + ] +] + +Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters) +// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3 +``` + +### Parameter Encoding + +Parameters can also be encoded as JSON, Property List, or any custom format, using the `ParameterEncoding` enum: + +```swift +enum ParameterEncoding { + case URL + case URLEncodedInURL + case JSON + case PropertyList(format: NSPropertyListFormat, options: NSPropertyListWriteOptions) + case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) + + func encode(request: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) + { ... } +} +``` + +- `URL`: A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. _Since there is no published specification for how to encode collection types, Alamofire follows the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`)._ +- `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same implementation as the `.URL` case, but always applies the encoded result to the URL. +- `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. +- `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`. +- `Custom`: Uses the associated closure value to construct a new request given an existing request and parameters. + +#### Manual Parameter Encoding of an NSURLRequest + +```swift +let URL = NSURL(string: "https://httpbin.org/get")! +var request = NSMutableURLRequest(URL: URL) + +let parameters = ["foo": "bar"] +let encoding = Alamofire.ParameterEncoding.URL +(request, _) = encoding.encode(request, parameters: parameters) +``` + +#### POST Request with JSON-encoded Parameters + +```swift +let parameters = [ + "foo": [1,2,3], + "bar": [ + "baz": "qux" + ] +] + +Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters, encoding: .JSON) +// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}} +``` + +### HTTP Headers + +Adding a custom HTTP header to a `Request` is supported directly in the global `request` method. This makes it easy to attach HTTP headers to a `Request` that can be constantly changing. + +> For HTTP headers that do not change, it is recommended to set them on the `NSURLSessionConfiguration` so they are automatically applied to any `NSURLSessionTask` created by the underlying `NSURLSession`. + +```swift +let headers = [ + "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", + "Accept": "application/json" +] + +Alamofire.request(.GET, "https://httpbin.org/get", headers: headers) + .responseJSON { response in + debugPrint(response) + } +``` + +### Caching + +Caching is handled on the system framework level by [`NSURLCache`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLCache_Class/Reference/Reference.html#//apple_ref/occ/cl/NSURLCache). + +### Uploading + +**Supported Upload Types** + +- File +- Data +- Stream +- MultipartFormData + +#### Uploading a File + +```swift +let fileURL = NSBundle.mainBundle().URLForResource("Default", withExtension: "png") +Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL) +``` + +#### Uploading with Progress + +```swift +Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL) + .progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in + print(totalBytesWritten) + + // This closure is NOT called on the main queue for performance + // reasons. To update your ui, dispatch to the main queue. + dispatch_async(dispatch_get_main_queue()) { + print("Total bytes written on main queue: \(totalBytesWritten)") + } + } + .validate() + .responseJSON { response in + debugPrint(response) + } +``` + +#### Uploading MultipartFormData + +```swift +Alamofire.upload( + .POST, + "https://httpbin.org/post", + multipartFormData: { multipartFormData in + multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn") + multipartFormData.appendBodyPart(fileURL: rainbowImageURL, name: "rainbow") + }, + encodingCompletion: { encodingResult in + switch encodingResult { + case .Success(let upload, _, _): + upload.responseJSON { response in + debugPrint(response) + } + case .Failure(let encodingError): + print(encodingError) + } + } +) +``` + +### Downloading + +**Supported Download Types** + +- Request +- Resume Data + +#### Downloading a File + +```swift +Alamofire.download(.GET, "https://httpbin.org/stream/100") { temporaryURL, response in + let fileManager = NSFileManager.defaultManager() + let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] + let pathComponent = response.suggestedFilename + + return directoryURL.URLByAppendingPathComponent(pathComponent!) +} +``` + +#### Using the Default Download Destination + +```swift +let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask) +Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) +``` + +#### Downloading a File w/Progress + +```swift +Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) + .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in + print(totalBytesRead) + + // This closure is NOT called on the main queue for performance + // reasons. To update your ui, dispatch to the main queue. + dispatch_async(dispatch_get_main_queue()) { + print("Total bytes read on main queue: \(totalBytesRead)") + } + } + .response { _, _, _, error in + if let error = error { + print("Failed with error: \(error)") + } else { + print("Downloaded file successfully") + } + } +``` + +#### Accessing Resume Data for Failed Downloads + +```swift +Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) + .response { _, _, data, _ in + if let + data = data, + resumeDataString = NSString(data: data, encoding: NSUTF8StringEncoding) + { + print("Resume Data: \(resumeDataString)") + } else { + print("Resume Data was empty") + } + } +``` + +> The `data` parameter is automatically populated with the `resumeData` if available. + +```swift +let download = Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination) +download.response { _, _, _, _ in + if let + resumeData = download.resumeData, + resumeDataString = NSString(data: resumeData, encoding: NSUTF8StringEncoding) + { + print("Resume Data: \(resumeDataString)") + } else { + print("Resume Data was empty") + } +} +``` + +### Authentication + +Authentication is handled on the system framework level by [`NSURLCredential` and `NSURLAuthenticationChallenge`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLAuthenticationChallenge_Class/Reference/Reference.html). + +**Supported Authentication Schemes** + +- [HTTP Basic](http://en.wikipedia.org/wiki/Basic_access_authentication) +- [HTTP Digest](http://en.wikipedia.org/wiki/Digest_access_authentication) +- [Kerberos](http://en.wikipedia.org/wiki/Kerberos_%28protocol%29) +- [NTLM](http://en.wikipedia.org/wiki/NT_LAN_Manager) + +#### HTTP Basic Authentication + +The `authenticate` method on a `Request` will automatically provide an `NSURLCredential` to an `NSURLAuthenticationChallenge` when appropriate: + +```swift +let user = "user" +let password = "password" + +Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)") + .authenticate(user: user, password: password) + .responseJSON { response in + debugPrint(response) + } +``` + +Depending upon your server implementation, an `Authorization` header may also be appropriate: + +```swift +let user = "user" +let password = "password" + +let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)! +let base64Credentials = credentialData.base64EncodedStringWithOptions([]) + +let headers = ["Authorization": "Basic \(base64Credentials)"] + +Alamofire.request(.GET, "https://httpbin.org/basic-auth/user/password", headers: headers) + .responseJSON { response in + debugPrint(response) + } +``` + +#### Authentication with NSURLCredential + +```swift +let user = "user" +let password = "password" + +let credential = NSURLCredential(user: user, password: password, persistence: .ForSession) + +Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)") + .authenticate(usingCredential: credential) + .responseJSON { response in + debugPrint(response) + } +``` + +### Timeline + +Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on a `Response`. + +```swift +Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + .validate() + .responseJSON { response in + print(response.timeline) + } +``` + +The above reports the following `Timeline` info: + +- `Latency`: 0.428 seconds +- `Request Duration`: 0.428 seconds +- `Serialization Duration`: 0.001 seconds +- `Total Duration`: 0.429 seconds + +### Printable + +```swift +let request = Alamofire.request(.GET, "https://httpbin.org/ip") + +print(request) +// GET https://httpbin.org/ip (200) +``` + +### DebugPrintable + +```swift +let request = Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) + +debugPrint(request) +``` + +#### Output (cURL) + +```bash +$ curl -i \ + -H "User-Agent: Alamofire" \ + -H "Accept-Encoding: Accept-Encoding: gzip;q=1.0,compress;q=0.5" \ + -H "Accept-Language: en;q=1.0,fr;q=0.9,de;q=0.8,zh-Hans;q=0.7,zh-Hant;q=0.6,ja;q=0.5" \ + "https://httpbin.org/get?foo=bar" +``` + +--- + +## Advanced Usage + +> Alamofire is built on `NSURLSession` and the Foundation URL Loading System. To make the most of +this framework, it is recommended that you be familiar with the concepts and capabilities of the underlying networking stack. + +**Recommended Reading** + +- [URL Loading System Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html) +- [NSURLSession Class Reference](https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/Introduction/Introduction.html#//apple_ref/occ/cl/NSURLSession) +- [NSURLCache Class Reference](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLCache_Class/Reference/Reference.html#//apple_ref/occ/cl/NSURLCache) +- [NSURLAuthenticationChallenge Class Reference](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLAuthenticationChallenge_Class/Reference/Reference.html) + +### Manager + +Top-level convenience methods like `Alamofire.request` use a shared instance of `Alamofire.Manager`, which is configured with the default `NSURLSessionConfiguration`. + +As such, the following two statements are equivalent: + +```swift +Alamofire.request(.GET, "https://httpbin.org/get") +``` + +```swift +let manager = Alamofire.Manager.sharedInstance +manager.request(NSURLRequest(URL: NSURL(string: "https://httpbin.org/get")!)) +``` + +Applications can create managers for background and ephemeral sessions, as well as new managers that customize the default session configuration, such as for default headers (`HTTPAdditionalHeaders`) or timeout interval (`timeoutIntervalForRequest`). + +#### Creating a Manager with Default Configuration + +```swift +let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() +let manager = Alamofire.Manager(configuration: configuration) +``` + +#### Creating a Manager with Background Configuration + +```swift +let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.example.app.background") +let manager = Alamofire.Manager(configuration: configuration) +``` + +#### Creating a Manager with Ephemeral Configuration + +```swift +let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration() +let manager = Alamofire.Manager(configuration: configuration) +``` + +#### Modifying Session Configuration + +```swift +var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:] +defaultHeaders["DNT"] = "1 (Do Not Track Enabled)" + +let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() +configuration.HTTPAdditionalHeaders = defaultHeaders + +let manager = Alamofire.Manager(configuration: configuration) +``` + +> This is **not** recommended for `Authorization` or `Content-Type` headers. Instead, use `URLRequestConvertible` and `ParameterEncoding`, respectively. + +### Request + +The result of a `request`, `upload`, or `download` method is an instance of `Alamofire.Request`. A request is always created using a constructor method from an owning manager, and never initialized directly. + +Methods like `authenticate`, `validate` and `responseData` return the caller in order to facilitate chaining. + +Requests can be suspended, resumed, and cancelled: + +- `suspend()`: Suspends the underlying task and dispatch queue +- `resume()`: Resumes the underlying task and dispatch queue. If the owning manager does not have `startRequestsImmediately` set to `true`, the request must call `resume()` in order to start. +- `cancel()`: Cancels the underlying task, producing an error that is passed to any registered response handlers. + +### Response Serialization + +#### Handling Errors + +Before implementing custom response serializers or object serialization methods, it's important to be prepared to handle any errors that may occur. Alamofire recommends handling these through the use of either your own `NSError` creation methods, or a simple `enum` that conforms to `ErrorType`. For example, this `BackendError` type, which will be used in later examples: + +```swift +enum BackendError: ErrorType { + case Network(error: NSError) + case DataSerialization(reason: String) + case JSONSerialization(error: NSError) + case ObjectSerialization(reason: String) + case XMLSerialization(error: NSError) +} +``` + +#### Creating a Custom Response Serializer + +Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.Request`. + +For example, here's how a response handler using [Ono](https://github.com/mattt/Ono) might be implemented: + +```swift +extension Request { + public static func XMLResponseSerializer() -> ResponseSerializer { + return ResponseSerializer { request, response, data, error in + guard error == nil else { return .Failure(.Network(error: error!)) } + + guard let validData = data else { + return .Failure(.DataSerialization(reason: "Data could not be serialized. Input data was nil.")) + } + + do { + let XML = try ONOXMLDocument(data: validData) + return .Success(XML) + } catch { + return .Failure(.XMLSerialization(error: error as NSError)) + } + } + } + + public func responseXMLDocument(completionHandler: Response -> Void) -> Self { + return response(responseSerializer: Request.XMLResponseSerializer(), completionHandler: completionHandler) + } +} +``` + +#### Generic Response Object Serialization + +Generics can be used to provide automatic, type-safe response object serialization. + +```swift +public protocol ResponseObjectSerializable { + init?(response: NSHTTPURLResponse, representation: AnyObject) +} + +extension Request { + public func responseObject(completionHandler: Response -> Void) -> Self { + let responseSerializer = ResponseSerializer { request, response, data, error in + guard error == nil else { return .Failure(.Network(error: error!)) } + + let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments) + let result = JSONResponseSerializer.serializeResponse(request, response, data, error) + + switch result { + case .Success(let value): + if let + response = response, + responseObject = T(response: response, representation: value) + { + return .Success(responseObject) + } else { + return .Failure(.ObjectSerialization(reason: "JSON could not be serialized into response object: \(value)")) + } + case .Failure(let error): + return .Failure(.JSONSerialization(error: error)) + } + } + + return response(responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} +``` + +```swift +final class User: ResponseObjectSerializable { + let username: String + let name: String + + init?(response: NSHTTPURLResponse, representation: AnyObject) { + self.username = response.URL!.lastPathComponent! + self.name = representation.valueForKeyPath("name") as! String + } +} +``` + +```swift +Alamofire.request(.GET, "https://example.com/users/mattt") + .responseObject { (response: Response) in + debugPrint(response) + } +``` + +The same approach can also be used to handle endpoints that return a representation of a collection of objects: + +```swift +public protocol ResponseCollectionSerializable { + static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] +} + +extension ResponseCollectionSerializable where Self: ResponseObjectSerializable { + static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [Self] { + var collection = [Self]() + + if let representation = representation as? [[String: AnyObject]] { + for itemRepresentation in representation { + if let item = Self(response: response, representation: itemRepresentation) { + collection.append(item) + } + } + } + + return collection + } +} + +extension Alamofire.Request { + public func responseCollection(completionHandler: Response<[T], BackendError> -> Void) -> Self { + let responseSerializer = ResponseSerializer<[T], BackendError> { request, response, data, error in + guard error == nil else { return .Failure(.Network(error: error!)) } + + let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments) + let result = JSONSerializer.serializeResponse(request, response, data, error) + + switch result { + case .Success(let value): + if let response = response { + return .Success(T.collection(response: response, representation: value)) + } else { + return .Failure(. ObjectSerialization(reason: "Response collection could not be serialized due to nil response")) + } + case .Failure(let error): + return .Failure(.JSONSerialization(error: error)) + } + } + + return response(responseSerializer: responseSerializer, completionHandler: completionHandler) + } +} +``` + +```swift +final class User: ResponseObjectSerializable, ResponseCollectionSerializable { + let username: String + let name: String + + init?(response: NSHTTPURLResponse, representation: AnyObject) { + self.username = response.URL!.lastPathComponent! + self.name = representation.valueForKeyPath("name") as! String + } +} +``` + +```swift +Alamofire.request(.GET, "http://example.com/users") + .responseCollection { (response: Response<[User], BackendError>) in + debugPrint(response) + } +``` + +### URLStringConvertible + +Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests. `NSString`, `NSURL`, `NSURLComponents`, and `NSURLRequest` conform to `URLStringConvertible` by default, allowing any of them to be passed as `URLString` parameters to the `request`, `upload`, and `download` methods: + +```swift +let string = NSString(string: "https://httpbin.org/post") +Alamofire.request(.POST, string) + +let URL = NSURL(string: string)! +Alamofire.request(.POST, URL) + +let URLRequest = NSURLRequest(URL: URL) +Alamofire.request(.POST, URLRequest) // overrides `HTTPMethod` of `URLRequest` + +let URLComponents = NSURLComponents(URL: URL, resolvingAgainstBaseURL: true) +Alamofire.request(.POST, URLComponents) +``` + +Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLStringConvertible` as a convenient way to map domain-specific models to server resources. + +#### Type-Safe Routing + +```swift +extension User: URLStringConvertible { + static let baseURLString = "http://example.com" + + var URLString: String { + return User.baseURLString + "/users/\(username)/" + } +} +``` + +```swift +let user = User(username: "mattt") +Alamofire.request(.GET, user) // http://example.com/users/mattt +``` + +### URLRequestConvertible + +Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. `NSURLRequest` conforms to `URLRequestConvertible` by default, allowing it to be passed into `request`, `upload`, and `download` methods directly (this is the recommended way to specify custom HTTP body for individual requests): + +```swift +let URL = NSURL(string: "https://httpbin.org/post")! +let mutableURLRequest = NSMutableURLRequest(URL: URL) +mutableURLRequest.HTTPMethod = "POST" + +let parameters = ["foo": "bar"] + +do { + mutableURLRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions()) +} catch { + // No-op +} + +mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + +Alamofire.request(mutableURLRequest) +``` + +Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLRequestConvertible` as a way to ensure consistency of requested endpoints. Such an approach can be used to abstract away server-side inconsistencies and provide type-safe routing, as well as manage authentication credentials and other state. + +#### API Parameter Abstraction + +```swift +enum Router: URLRequestConvertible { + static let baseURLString = "http://example.com" + static let perPage = 50 + + case Search(query: String, page: Int) + + // MARK: URLRequestConvertible + + var URLRequest: NSMutableURLRequest { + let result: (path: String, parameters: [String: AnyObject]) = { + switch self { + case .Search(let query, let page) where page > 0: + return ("/search", ["q": query, "offset": Router.perPage * page]) + case .Search(let query, _): + return ("/search", ["q": query]) + } + }() + + let URL = NSURL(string: Router.baseURLString)! + let URLRequest = NSURLRequest(URL: URL.URLByAppendingPathComponent(result.path)) + let encoding = Alamofire.ParameterEncoding.URL + + return encoding.encode(URLRequest, parameters: result.parameters).0 + } +} +``` + +```swift +Alamofire.request(Router.Search(query: "foo bar", page: 1)) // ?q=foo%20bar&offset=50 +``` + +#### CRUD & Authorization + +```swift +enum Router: URLRequestConvertible { + static let baseURLString = "http://example.com" + static var OAuthToken: String? + + case CreateUser([String: AnyObject]) + case ReadUser(String) + case UpdateUser(String, [String: AnyObject]) + case DestroyUser(String) + + var method: Alamofire.Method { + switch self { + case .CreateUser: + return .POST + case .ReadUser: + return .GET + case .UpdateUser: + return .PUT + case .DestroyUser: + return .DELETE + } + } + + var path: String { + switch self { + case .CreateUser: + return "/users" + case .ReadUser(let username): + return "/users/\(username)" + case .UpdateUser(let username, _): + return "/users/\(username)" + case .DestroyUser(let username): + return "/users/\(username)" + } + } + + // MARK: URLRequestConvertible + + var URLRequest: NSMutableURLRequest { + let URL = NSURL(string: Router.baseURLString)! + let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path)) + mutableURLRequest.HTTPMethod = method.rawValue + + if let token = Router.OAuthToken { + mutableURLRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") + } + + switch self { + case .CreateUser(let parameters): + return Alamofire.ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0 + case .UpdateUser(_, let parameters): + return Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: parameters).0 + default: + return mutableURLRequest + } + } +} +``` + +```swift +Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt +``` + +### SessionDelegate + +By default, an Alamofire `Manager` instance creates an internal `SessionDelegate` object to handle all the various types of delegate callbacks that are generated by the underlying `NSURLSession`. The implementations of each delegate method handle the most common use cases for these types of calls abstracting the complexity away from the top-level APIs. However, advanced users may find the need to override the default functionality for various reasons. + +#### Override Closures + +The first way to customize the `SessionDelegate` behavior is through the use of the override closures. Each closure gives you the ability to override the implementation of the matching `SessionDelegate` API, yet still use the default implementation for all other APIs. This makes it easy to customize subsets of the delegate functionality. Here are a few examples of some of the override closures available: + +```swift +/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. +public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + +/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. +public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? + +/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. +public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? + +/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. +public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? +``` + +The following is a short example of how to use the `taskWillPerformHTTPRedirection` to avoid following redirects to any `apple.com` domains. + +```swift +let delegate: Alamofire.Manager.SessionDelegate = manager.delegate + +delegate.taskWillPerformHTTPRedirection = { session, task, response, request in + var finalRequest = request + + if let originalRequest = task.originalRequest where originalRequest.URLString.containsString("apple.com") { + finalRequest = originalRequest + } + + return finalRequest +} +``` + +#### Subclassing + +Another way to override the default implementation of the `SessionDelegate` is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here's a quick example of subclassing the `SessionDelegate` and logging a message when a redirect occurs. + +```swift +class LoggingSessionDelegate: Manager.SessionDelegate { + override func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + willPerformHTTPRedirection response: NSHTTPURLResponse, + newRequest request: NSURLRequest, + completionHandler: NSURLRequest? -> Void) + { + print("URLSession will perform HTTP redirection to request: \(request)") + + super.URLSession( + session, + task: task, + willPerformHTTPRedirection: response, + newRequest: request, + completionHandler: completionHandler + ) + } +} +``` + +Generally, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort. + +> It is important to keep in mind that the `subdelegates` are initialized and destroyed in the default implementation. Be careful when subclassing to not introduce memory leaks. + +### Security + +Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`. + +#### ServerTrustPolicy + +The `ServerTrustPolicy` enumeration evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. + +```swift +let serverTrustPolicy = ServerTrustPolicy.PinCertificates( + certificates: ServerTrustPolicy.certificatesInBundle(), + validateCertificateChain: true, + validateHost: true +) +``` + +There are many different cases of server trust evaluation giving you complete control over the validation process: + +* `PerformDefaultEvaluation`: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge. +* `PinCertificates`: Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned certificates match one of the server certificates. +* `PinPublicKeys`: Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned public keys match one of the server certificate public keys. +* `DisableEvaluation`: Disables all evaluation which in turn will always consider any server trust as valid. +* `CustomEvaluation`: Uses the associated closure to evaluate the validity of the server trust thus giving you complete control over the validation process. Use with caution. + +#### Server Trust Policy Manager + +The `ServerTrustPolicyManager` is responsible for storing an internal mapping of server trust policies to a particular host. This allows Alamofire to evaluate each host against a different server trust policy. + +```swift +let serverTrustPolicies: [String: ServerTrustPolicy] = [ + "test.example.com": .PinCertificates( + certificates: ServerTrustPolicy.certificatesInBundle(), + validateCertificateChain: true, + validateHost: true + ), + "insecure.expired-apis.com": .DisableEvaluation +] + +let manager = Manager( + serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies) +) +``` + +> Make sure to keep a reference to the new `Manager` instance, otherwise your requests will all get cancelled when your `manager` is deallocated. + +These server trust policies will result in the following behavior: + +* `test.example.com` will always use certificate pinning with certificate chain and host validation enabled thus requiring the following criteria to be met to allow the TLS handshake to succeed: + * Certificate chain MUST be valid. + * Certificate chain MUST include one of the pinned certificates. + * Challenge host MUST match the host in the certificate chain's leaf certificate. +* `insecure.expired-apis.com` will never evaluate the certificate chain and will always allow the TLS handshake to succeed. +* All other hosts will use the default evaluation provided by Apple. + +##### Subclassing Server Trust Policy Manager + +If you find yourself needing more flexible server trust policy matching behavior (i.e. wildcarded domains), then subclass the `ServerTrustPolicyManager` and override the `serverTrustPolicyForHost` method with your own custom implementation. + +```swift +class CustomServerTrustPolicyManager: ServerTrustPolicyManager { + override func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? { + var policy: ServerTrustPolicy? + + // Implement your custom domain matching behavior... + + return policy + } +} +``` + +#### Validating the Host + +The `.PerformDefaultEvaluation`, `.PinCertificates` and `.PinPublicKeys` server trust policies all take a `validateHost` parameter. Setting the value to `true` will cause the server trust evaluation to verify that hostname in the certificate matches the hostname of the challenge. If they do not match, evaluation will fail. A `validateHost` value of `false` will still evaluate the full certificate chain, but will not validate the hostname of the leaf certificate. + +> It is recommended that `validateHost` always be set to `true` in production environments. + +#### Validating the Certificate Chain + +Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certificates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. + +There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server. + +> It is recommended that `validateCertificateChain` always be set to `true` in production environments. + +#### App Transport Security + +With the addition of App Transport Security (ATS) in iOS 9, it is possible that using a custom `ServerTrustPolicyManager` with several `ServerTrustPolicy` objects will have no effect. If you continuously see `CFNetwork SSLHandshake failed (-9806)` errors, you have probably run into this problem. Apple's ATS system overrides the entire challenge system unless you configure the ATS settings in your app's plist to disable enough of it to allow your app to evaluate the server trust. + +If you run into this problem (high probability with self-signed certificates), you can work around this issue by adding the following to your `Info.plist`. + +```xml + + NSAppTransportSecurity + + NSExceptionDomains + + example.com + + NSExceptionAllowsInsecureHTTPLoads + + NSExceptionRequiresForwardSecrecy + + NSIncludesSubdomains + + + NSTemporaryExceptionMinimumTLSVersion + TLSv1.2 + + + + +``` + +Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends on whether your TLS connection is using an allowed cipher suite. In certain cases, it will need to be set to `NO`. The `NSExceptionAllowsInsecureHTTPLoads` MUST be set to `YES` in order to allow the `SessionDelegate` to receive challenge callbacks. Once the challenge callbacks are being called, the `ServerTrustPolicyManager` will take over the server trust evaluation. You may also need to specify the `NSTemporaryExceptionMinimumTLSVersion` if you're trying to connect to a host that only supports TLS versions less than `1.2`. + +> It is recommended to always use valid certificates in production environments. + +### Network Reachability + +The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces. + +```swift +let manager = NetworkReachabilityManager(host: "www.apple.com") + +manager?.listener = { status in + print("Network Status Changed: \(status)") +} + +manager?.startListening() +``` + +> Make sure to remember to retain the `manager` in the above example, or no status changes will be reported. + +There are some important things to remember when using network reachability to determine what to do next. + +* **Do NOT** use Reachability to determine if a network request should be sent. + * You should **ALWAYS** send it. +* When Reachability is restored, use the event to retry failed network requests. + * Even though the network requests may still fail, this is a good moment to retry them. +* The network reachability status can be useful for determining why a network request may have failed. + * If a network request fails, it is more useful to tell the user that the network request failed due to being offline rather than a more technical error, such as "request timed out." + +> It is recommended to check out [WWDC 2012 Session 706, "Networking Best Practices"](https://developer.apple.com/videos/play/wwdc2012-706/) for more info. + +--- + +## Open Rdars + +The following rdars have some affect on the current implementation of Alamofire. + +* [rdar://21349340](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case +* [rdar://26761490](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage + +## FAQ + +### What's the origin of the name Alamofire? + +Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. + +--- + +## Credits + +Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. + +### Security Disclosure + +If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## Donations + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially register as a federal non-profit organization. Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. Donating to the ASF will enable us to: + +* Pay our legal fees to register as a federal non-profit organization +* Pay our yearly legal fees to keep the non-profit in good status +* Pay for our mail servers to help us stay on top of all questions and security issues +* Potentially fund test servers to make it easier for us to test the edge cases +* Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiam around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. + +Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com ! + +## License + +Alamofire is released under the MIT license. See LICENSE for details. diff --git a/Pods/Alamofire/Source/Alamofire.swift b/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 0000000..cb4b36a --- /dev/null +++ b/Pods/Alamofire/Source/Alamofire.swift @@ -0,0 +1,370 @@ +// +// Alamofire.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +// MARK: - URLStringConvertible + +/** + Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to + construct URL requests. +*/ +public protocol URLStringConvertible { + /** + A URL that conforms to RFC 2396. + + Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808. + + See https://tools.ietf.org/html/rfc2396 + See https://tools.ietf.org/html/rfc1738 + See https://tools.ietf.org/html/rfc1808 + */ + var URLString: String { get } +} + +extension String: URLStringConvertible { + public var URLString: String { + return self + } +} + +extension NSURL: URLStringConvertible { + public var URLString: String { + return absoluteString + } +} + +extension NSURLComponents: URLStringConvertible { + public var URLString: String { + return URL!.URLString + } +} + +extension NSURLRequest: URLStringConvertible { + public var URLString: String { + return URL!.URLString + } +} + +// MARK: - URLRequestConvertible + +/** + Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. +*/ +public protocol URLRequestConvertible { + /// The URL request. + var URLRequest: NSMutableURLRequest { get } +} + +extension NSURLRequest: URLRequestConvertible { + public var URLRequest: NSMutableURLRequest { + return self.mutableCopy() as! NSMutableURLRequest + } +} + +// MARK: - Convenience + +func URLRequest( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil) + -> NSMutableURLRequest +{ + let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!) + mutableURLRequest.HTTPMethod = method.rawValue + + if let headers = headers { + for (headerField, headerValue) in headers { + mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField) + } + } + + return mutableURLRequest +} + +// MARK: - Request Methods + +/** + Creates a request using the shared manager instance for the specified method, URL string, parameters, and + parameter encoding. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter parameters: The parameters. `nil` by default. + - parameter encoding: The parameter encoding. `.URL` by default. + - parameter headers: The HTTP headers. `nil` by default. + + - returns: The created request. +*/ +public func request( + method: Method, + _ URLString: URLStringConvertible, + parameters: [String: AnyObject]? = nil, + encoding: ParameterEncoding = .URL, + headers: [String: String]? = nil) + -> Request +{ + return Manager.sharedInstance.request( + method, + URLString, + parameters: parameters, + encoding: encoding, + headers: headers + ) +} + +/** + Creates a request using the shared manager instance for the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request + + - returns: The created request. +*/ +public func request(URLRequest: URLRequestConvertible) -> Request { + return Manager.sharedInstance.request(URLRequest.URLRequest) +} + +// MARK: - Upload Methods + +// MARK: File + +/** + Creates an upload request using the shared manager instance for the specified method, URL string, and file. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter file: The file to upload. + + - returns: The created upload request. +*/ +public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + file: NSURL) + -> Request +{ + return Manager.sharedInstance.upload(method, URLString, headers: headers, file: file) +} + +/** + Creates an upload request using the shared manager instance for the specified URL request and file. + + - parameter URLRequest: The URL request. + - parameter file: The file to upload. + + - returns: The created upload request. +*/ +public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { + return Manager.sharedInstance.upload(URLRequest, file: file) +} + +// MARK: Data + +/** + Creates an upload request using the shared manager instance for the specified method, URL string, and data. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter data: The data to upload. + + - returns: The created upload request. +*/ +public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + data: NSData) + -> Request +{ + return Manager.sharedInstance.upload(method, URLString, headers: headers, data: data) +} + +/** + Creates an upload request using the shared manager instance for the specified URL request and data. + + - parameter URLRequest: The URL request. + - parameter data: The data to upload. + + - returns: The created upload request. +*/ +public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { + return Manager.sharedInstance.upload(URLRequest, data: data) +} + +// MARK: Stream + +/** + Creates an upload request using the shared manager instance for the specified method, URL string, and stream. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter stream: The stream to upload. + + - returns: The created upload request. +*/ +public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + stream: NSInputStream) + -> Request +{ + return Manager.sharedInstance.upload(method, URLString, headers: headers, stream: stream) +} + +/** + Creates an upload request using the shared manager instance for the specified URL request and stream. + + - parameter URLRequest: The URL request. + - parameter stream: The stream to upload. + + - returns: The created upload request. +*/ +public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { + return Manager.sharedInstance.upload(URLRequest, stream: stream) +} + +// MARK: MultipartFormData + +/** + Creates an upload request using the shared manager instance for the specified method and URL string. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + `MultipartFormDataEncodingMemoryThreshold` by default. + - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +*/ +public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + multipartFormData: MultipartFormData -> Void, + encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) +{ + return Manager.sharedInstance.upload( + method, + URLString, + headers: headers, + multipartFormData: multipartFormData, + encodingMemoryThreshold: encodingMemoryThreshold, + encodingCompletion: encodingCompletion + ) +} + +/** + Creates an upload request using the shared manager instance for the specified method and URL string. + + - parameter URLRequest: The URL request. + - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + `MultipartFormDataEncodingMemoryThreshold` by default. + - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +*/ +public func upload( + URLRequest: URLRequestConvertible, + multipartFormData: MultipartFormData -> Void, + encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) +{ + return Manager.sharedInstance.upload( + URLRequest, + multipartFormData: multipartFormData, + encodingMemoryThreshold: encodingMemoryThreshold, + encodingCompletion: encodingCompletion + ) +} + +// MARK: - Download Methods + +// MARK: URL Request + +/** + Creates a download request using the shared manager instance for the specified method and URL string. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter parameters: The parameters. `nil` by default. + - parameter encoding: The parameter encoding. `.URL` by default. + - parameter headers: The HTTP headers. `nil` by default. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. +*/ +public func download( + method: Method, + _ URLString: URLStringConvertible, + parameters: [String: AnyObject]? = nil, + encoding: ParameterEncoding = .URL, + headers: [String: String]? = nil, + destination: Request.DownloadFileDestination) + -> Request +{ + return Manager.sharedInstance.download( + method, + URLString, + parameters: parameters, + encoding: encoding, + headers: headers, + destination: destination + ) +} + +/** + Creates a download request using the shared manager instance for the specified URL request. + + - parameter URLRequest: The URL request. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. +*/ +public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request { + return Manager.sharedInstance.download(URLRequest, destination: destination) +} + +// MARK: Resume Data + +/** + Creates a request using the shared manager instance for downloading from the resume data produced from a + previous request cancellation. + + - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` + when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional + information. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. +*/ +public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request { + return Manager.sharedInstance.download(data, destination: destination) +} diff --git a/Pods/Alamofire/Source/Download.swift b/Pods/Alamofire/Source/Download.swift new file mode 100644 index 0000000..97b146f --- /dev/null +++ b/Pods/Alamofire/Source/Download.swift @@ -0,0 +1,248 @@ +// +// Download.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Manager { + private enum Downloadable { + case Request(NSURLRequest) + case ResumeData(NSData) + } + + private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request { + var downloadTask: NSURLSessionDownloadTask! + + switch downloadable { + case .Request(let request): + dispatch_sync(queue) { + downloadTask = self.session.downloadTaskWithRequest(request) + } + case .ResumeData(let resumeData): + dispatch_sync(queue) { + downloadTask = self.session.downloadTaskWithResumeData(resumeData) + } + } + + let request = Request(session: session, task: downloadTask) + + if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate { + downloadDelegate.downloadTaskDidFinishDownloadingToURL = { session, downloadTask, URL in + return destination(URL, downloadTask.response as! NSHTTPURLResponse) + } + } + + delegate[request.delegate.task] = request.delegate + + if startRequestsImmediately { + request.resume() + } + + return request + } + + // MARK: Request + + /** + Creates a download request for the specified method, URL string, parameters, parameter encoding, headers + and destination. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter parameters: The parameters. `nil` by default. + - parameter encoding: The parameter encoding. `.URL` by default. + - parameter headers: The HTTP headers. `nil` by default. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. + */ + public func download( + method: Method, + _ URLString: URLStringConvertible, + parameters: [String: AnyObject]? = nil, + encoding: ParameterEncoding = .URL, + headers: [String: String]? = nil, + destination: Request.DownloadFileDestination) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0 + + return download(encodedURLRequest, destination: destination) + } + + /** + Creates a request for downloading from the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. + */ + public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request { + return download(.Request(URLRequest.URLRequest), destination: destination) + } + + // MARK: Resume Data + + /** + Creates a request for downloading from the resume data produced from a previous request cancellation. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` + when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for + additional information. + - parameter destination: The closure used to determine the destination of the downloaded file. + + - returns: The created download request. + */ + public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request { + return download(.ResumeData(resumeData), destination: destination) + } +} + +// MARK: - + +extension Request { + /** + A closure executed once a request has successfully completed in order to determine where to move the temporary + file written to during the download process. The closure takes two arguments: the temporary file URL and the URL + response, and returns a single argument: the file URL where the temporary file should be moved. + */ + public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> NSURL + + /** + Creates a download file destination closure which uses the default file manager to move the temporary file to a + file URL in the first available directory with the specified search path directory and search path domain mask. + + - parameter directory: The search path directory. `.DocumentDirectory` by default. + - parameter domain: The search path domain mask. `.UserDomainMask` by default. + + - returns: A download file destination closure. + */ + public class func suggestedDownloadDestination( + directory directory: NSSearchPathDirectory = .DocumentDirectory, + domain: NSSearchPathDomainMask = .UserDomainMask) + -> DownloadFileDestination + { + return { temporaryURL, response -> NSURL in + let directoryURLs = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain) + + if !directoryURLs.isEmpty { + return directoryURLs[0].URLByAppendingPathComponent(response.suggestedFilename!) + } + + return temporaryURL + } + } + + /// The resume data of the underlying download task if available after a failure. + public var resumeData: NSData? { + var data: NSData? + + if let delegate = delegate as? DownloadTaskDelegate { + data = delegate.resumeData + } + + return data + } + + // MARK: - DownloadTaskDelegate + + class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate { + var downloadTask: NSURLSessionDownloadTask? { return task as? NSURLSessionDownloadTask } + var downloadProgress: ((Int64, Int64, Int64) -> Void)? + + var resumeData: NSData? + override var data: NSData? { return resumeData } + + // MARK: - NSURLSessionDownloadDelegate + + // MARK: Override Closures + + var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> NSURL)? + var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: Delegate Methods + + func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didFinishDownloadingToURL location: NSURL) + { + if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { + do { + let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) + try NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination) + } catch { + self.error = error as NSError + } + } + } + + func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData( + session, + downloadTask, + bytesWritten, + totalBytesWritten, + totalBytesExpectedToWrite + ) + } else { + progress.totalUnitCount = totalBytesExpectedToWrite + progress.completedUnitCount = totalBytesWritten + + downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } + } + + func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else { + progress.totalUnitCount = expectedTotalBytes + progress.completedUnitCount = fileOffset + } + } + } +} diff --git a/Pods/Alamofire/Source/Error.swift b/Pods/Alamofire/Source/Error.swift new file mode 100644 index 0000000..467d99c --- /dev/null +++ b/Pods/Alamofire/Source/Error.swift @@ -0,0 +1,88 @@ +// +// Error.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// The `Error` struct provides a convenience for creating custom Alamofire NSErrors. +public struct Error { + /// The domain used for creating all Alamofire errors. + public static let Domain = "com.alamofire.error" + + /// The custom error codes generated by Alamofire. + public enum Code: Int { + case InputStreamReadFailed = -6000 + case OutputStreamWriteFailed = -6001 + case ContentTypeValidationFailed = -6002 + case StatusCodeValidationFailed = -6003 + case DataSerializationFailed = -6004 + case StringSerializationFailed = -6005 + case JSONSerializationFailed = -6006 + case PropertyListSerializationFailed = -6007 + } + + /// Custom keys contained within certain NSError `userInfo` dictionaries generated by Alamofire. + public struct UserInfoKeys { + /// The content type user info key for a `.ContentTypeValidationFailed` error stored as a `String` value. + public static let ContentType = "ContentType" + + /// The status code user info key for a `.StatusCodeValidationFailed` error stored as an `Int` value. + public static let StatusCode = "StatusCode" + } + + /** + Creates an `NSError` with the given error code and failure reason. + + - parameter code: The error code. + - parameter failureReason: The failure reason. + + - returns: An `NSError` with the given error code and failure reason. + */ + @available(*, deprecated=3.4.0) + public static func errorWithCode(code: Code, failureReason: String) -> NSError { + return errorWithCode(code.rawValue, failureReason: failureReason) + } + + /** + Creates an `NSError` with the given error code and failure reason. + + - parameter code: The error code. + - parameter failureReason: The failure reason. + + - returns: An `NSError` with the given error code and failure reason. + */ + @available(*, deprecated=3.4.0) + public static func errorWithCode(code: Int, failureReason: String) -> NSError { + let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] + return NSError(domain: Domain, code: code, userInfo: userInfo) + } + + static func error(domain domain: String = Error.Domain, code: Code, failureReason: String) -> NSError { + return error(domain: domain, code: code.rawValue, failureReason: failureReason) + } + + static func error(domain domain: String = Error.Domain, code: Int, failureReason: String) -> NSError { + let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] + return NSError(domain: domain, code: code, userInfo: userInfo) + } +} diff --git a/Pods/Alamofire/Source/Manager.swift b/Pods/Alamofire/Source/Manager.swift new file mode 100644 index 0000000..691d31f --- /dev/null +++ b/Pods/Alamofire/Source/Manager.swift @@ -0,0 +1,778 @@ +// +// Manager.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/** + Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. +*/ +public class Manager { + + // MARK: - Properties + + /** + A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly + for any ad hoc requests. + */ + public static let sharedInstance: Manager = { + let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() + configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders + + return Manager(configuration: configuration) + }() + + /** + Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. + */ + public static let defaultHTTPHeaders: [String: String] = { + // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 + let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" + + // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 + let acceptLanguage = NSLocale.preferredLanguages().prefix(6).enumerate().map { index, languageCode in + let quality = 1.0 - (Double(index) * 0.1) + return "\(languageCode);q=\(quality)" + }.joinWithSeparator(", ") + + // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 + let userAgent: String = { + if let info = NSBundle.mainBundle().infoDictionary { + let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" + let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" + let version = info[kCFBundleVersionKey as String] as? String ?? "Unknown" + + let osNameVersion: String = { + let versionString: String + + if #available(OSX 10.10, *) { + let version = NSProcessInfo.processInfo().operatingSystemVersion + versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + } else { + versionString = "10.9" + } + + let osName: String = { + #if os(iOS) + return "iOS" + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(OSX) + return "OS X" + #elseif os(Linux) + return "Linux" + #else + return "Unknown" + #endif + }() + + return "\(osName) \(versionString)" + }() + + return "\(executable)/\(bundle) (\(version); \(osNameVersion))" + } + + return "Alamofire" + }() + + return [ + "Accept-Encoding": acceptEncoding, + "Accept-Language": acceptLanguage, + "User-Agent": userAgent + ] + }() + + let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL) + + /// The underlying session. + public let session: NSURLSession + + /// The session delegate handling all the task and session delegate callbacks. + public let delegate: SessionDelegate + + /// Whether to start requests immediately after being constructed. `true` by default. + public var startRequestsImmediately: Bool = true + + /** + The background completion handler closure provided by the UIApplicationDelegate + `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background + completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation + will automatically call the handler. + + If you need to handle your own events before the handler is called, then you need to override the + SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. + + `nil` by default. + */ + public var backgroundCompletionHandler: (() -> Void)? + + // MARK: - Lifecycle + + /** + Initializes the `Manager` instance with the specified configuration, delegate and server trust policy. + + - parameter configuration: The configuration used to construct the managed session. + `NSURLSessionConfiguration.defaultSessionConfiguration()` by default. + - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by + default. + - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust + challenges. `nil` by default. + + - returns: The new `Manager` instance. + */ + public init( + configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(), + delegate: SessionDelegate = SessionDelegate(), + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + self.delegate = delegate + self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + /** + Initializes the `Manager` instance with the specified session, delegate and server trust policy. + + - parameter session: The URL session. + - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. + - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust + challenges. `nil` by default. + + - returns: The new `Manager` instance if the URL session's delegate matches the delegate parameter. + */ + public init?( + session: NSURLSession, + delegate: SessionDelegate, + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + guard delegate === session.delegate else { return nil } + + self.delegate = delegate + self.session = session + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + private func commonInit(serverTrustPolicyManager serverTrustPolicyManager: ServerTrustPolicyManager?) { + session.serverTrustPolicyManager = serverTrustPolicyManager + + delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in + guard let strongSelf = self else { return } + dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() } + } + } + + deinit { + session.invalidateAndCancel() + } + + // MARK: - Request + + /** + Creates a request for the specified method, URL string, parameters, parameter encoding and headers. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter parameters: The parameters. `nil` by default. + - parameter encoding: The parameter encoding. `.URL` by default. + - parameter headers: The HTTP headers. `nil` by default. + + - returns: The created request. + */ + public func request( + method: Method, + _ URLString: URLStringConvertible, + parameters: [String: AnyObject]? = nil, + encoding: ParameterEncoding = .URL, + headers: [String: String]? = nil) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0 + return request(encodedURLRequest) + } + + /** + Creates a request for the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request + + - returns: The created request. + */ + public func request(URLRequest: URLRequestConvertible) -> Request { + var dataTask: NSURLSessionDataTask! + dispatch_sync(queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) } + + let request = Request(session: session, task: dataTask) + delegate[request.delegate.task] = request.delegate + + if startRequestsImmediately { + request.resume() + } + + return request + } + + // MARK: - SessionDelegate + + /** + Responsible for handling all delegate callbacks for the underlying session. + */ + public class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { + private var subdelegates: [Int: Request.TaskDelegate] = [:] + private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) + + /// Access the task delegate for the specified task in a thread-safe manner. + public subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { + get { + var subdelegate: Request.TaskDelegate? + dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] } + + return subdelegate + } + set { + dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } + } + } + + /** + Initializes the `SessionDelegate` instance. + + - returns: The new `SessionDelegate` instance. + */ + public override init() { + super.init() + } + + // MARK: - NSURLSessionDelegate + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`. + public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)? + + /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. + public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + + /// Overrides all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`. + public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. + public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? + + // MARK: Delegate Methods + + /** + Tells the delegate that the session has been invalidated. + + - parameter session: The session object that was invalidated. + - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. + */ + public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) { + sessionDidBecomeInvalidWithError?(session, error) + } + + /** + Requests credentials from the delegate in response to a session-level authentication request from the remote server. + + - parameter session: The session containing the task that requested authentication. + - parameter challenge: An object that contains the request for authentication. + - parameter completionHandler: A handler that your delegate method must call providing the disposition and credential. + */ + public func URLSession( + session: NSURLSession, + didReceiveChallenge challenge: NSURLAuthenticationChallenge, + completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) + { + guard sessionDidReceiveChallengeWithCompletion == nil else { + sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) + return + } + + var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling + var credential: NSURLCredential? + + if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { + (disposition, credential) = sessionDidReceiveChallenge(session, challenge) + } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + let host = challenge.protectionSpace.host + + if let + serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host), + serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) { + disposition = .UseCredential + credential = NSURLCredential(forTrust: serverTrust) + } else { + disposition = .CancelAuthenticationChallenge + } + } + } + + completionHandler(disposition, credential) + } + + /** + Tells the delegate that all messages enqueued for a session have been delivered. + + - parameter session: The session that no longer has any outstanding requests. + */ + public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) { + sessionDidFinishEventsForBackgroundURLSession?(session) + } + + // MARK: - NSURLSessionTaskDelegate + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. + public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? + + /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and + /// requires the caller to call the `completionHandler`. + public var taskWillPerformHTTPRedirectionWithCompletion: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest, NSURLRequest? -> Void) -> Void)? + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`. + public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + + /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and + /// requires the caller to call the `completionHandler`. + public var taskDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`. + public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)? + + /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and + /// requires the caller to call the `completionHandler`. + public var taskNeedNewBodyStreamWithCompletion: ((NSURLSession, NSURLSessionTask, NSInputStream? -> Void) -> Void)? + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. + public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`. + public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? + + // MARK: Delegate Methods + + /** + Tells the delegate that the remote server requested an HTTP redirect. + + - parameter session: The session containing the task whose request resulted in a redirect. + - parameter task: The task whose request resulted in a redirect. + - parameter response: An object containing the server’s response to the original request. + - parameter request: A URL request object filled out with the new location. + - parameter completionHandler: A closure that your handler should call with either the value of the request + parameter, a modified URL request object, or NULL to refuse the redirect and + return the body of the redirect response. + */ + public func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + willPerformHTTPRedirection response: NSHTTPURLResponse, + newRequest request: NSURLRequest, + completionHandler: NSURLRequest? -> Void) + { + guard taskWillPerformHTTPRedirectionWithCompletion == nil else { + taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) + return + } + + var redirectRequest: NSURLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + /** + Requests credentials from the delegate in response to an authentication request from the remote server. + + - parameter session: The session containing the task whose request requires authentication. + - parameter task: The task whose request requires authentication. + - parameter challenge: An object that contains the request for authentication. + - parameter completionHandler: A handler that your delegate method must call providing the disposition and credential. + */ + public func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + didReceiveChallenge challenge: NSURLAuthenticationChallenge, + completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) + { + guard taskDidReceiveChallengeWithCompletion == nil else { + taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) + return + } + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + let result = taskDidReceiveChallenge(session, task, challenge) + completionHandler(result.0, result.1) + } else if let delegate = self[task] { + delegate.URLSession( + session, + task: task, + didReceiveChallenge: challenge, + completionHandler: completionHandler + ) + } else { + URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler) + } + } + + /** + Tells the delegate when a task requires a new request body stream to send to the remote server. + + - parameter session: The session containing the task that needs a new body stream. + - parameter task: The task that needs a new body stream. + - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. + */ + public func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + needNewBodyStream completionHandler: NSInputStream? -> Void) + { + guard taskNeedNewBodyStreamWithCompletion == nil else { + taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) + return + } + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + completionHandler(taskNeedNewBodyStream(session, task)) + } else if let delegate = self[task] { + delegate.URLSession(session, task: task, needNewBodyStream: completionHandler) + } + } + + /** + Periodically informs the delegate of the progress of sending body content to the server. + + - parameter session: The session containing the data task. + - parameter task: The data task. + - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. + - parameter totalBytesSent: The total number of bytes sent so far. + - parameter totalBytesExpectedToSend: The expected length of the body data. + */ + public func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else if let delegate = self[task] as? Request.UploadTaskDelegate { + delegate.URLSession( + session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend + ) + } + } + + /** + Tells the delegate that the task finished transferring data. + + - parameter session: The session containing the task whose request finished transferring data. + - parameter task: The task whose request finished transferring data. + - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. + */ + public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { + if let taskDidComplete = taskDidComplete { + taskDidComplete(session, task, error) + } else if let delegate = self[task] { + delegate.URLSession(session, task: task, didCompleteWithError: error) + } + + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task) + + self[task] = nil + } + + // MARK: - NSURLSessionDataDelegate + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`. + public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? + + /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and + /// requires caller to call the `completionHandler`. + public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)? + + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`. + public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? + + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`. + public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? + + /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. + public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? + + /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and + /// requires caller to call the `completionHandler`. + public var dataTaskWillCacheResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse, NSCachedURLResponse? -> Void) -> Void)? + + // MARK: Delegate Methods + + /** + Tells the delegate that the data task received the initial reply (headers) from the server. + + - parameter session: The session containing the data task that received an initial reply. + - parameter dataTask: The data task that received an initial reply. + - parameter response: A URL response object populated with headers. + - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a + constant to indicate whether the transfer should continue as a data task or + should become a download task. + */ + public func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + didReceiveResponse response: NSURLResponse, + completionHandler: NSURLSessionResponseDisposition -> Void) + { + guard dataTaskDidReceiveResponseWithCompletion == nil else { + dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) + return + } + + var disposition: NSURLSessionResponseDisposition = .Allow + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + /** + Tells the delegate that the data task was changed to a download task. + + - parameter session: The session containing the task that was replaced by a download task. + - parameter dataTask: The data task that was replaced by a download task. + - parameter downloadTask: The new download task that replaced the data task. + */ + public func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) + { + if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { + dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) + } else { + let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask) + self[downloadTask] = downloadDelegate + } + } + + /** + Tells the delegate that the data task has received some of the expected data. + + - parameter session: The session containing the data task that provided data. + - parameter dataTask: The data task that provided data. + - parameter data: A data object containing the transferred data. + */ + public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { + delegate.URLSession(session, dataTask: dataTask, didReceiveData: data) + } + } + + /** + Asks the delegate whether the data (or upload) task should store the response in the cache. + + - parameter session: The session containing the data (or upload) task. + - parameter dataTask: The data (or upload) task. + - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current + caching policy and the values of certain received headers, such as the Pragma + and Cache-Control headers. + - parameter completionHandler: A block that your handler must call, providing either the original proposed + response, a modified version of that response, or NULL to prevent caching the + response. If your delegate implements this method, it must call this completion + handler; otherwise, your app leaks memory. + */ + public func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + willCacheResponse proposedResponse: NSCachedURLResponse, + completionHandler: NSCachedURLResponse? -> Void) + { + guard dataTaskWillCacheResponseWithCompletion == nil else { + dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) + return + } + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) + } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { + delegate.URLSession( + session, + dataTask: dataTask, + willCacheResponse: proposedResponse, + completionHandler: completionHandler + ) + } else { + completionHandler(proposedResponse) + } + } + + // MARK: - NSURLSessionDownloadDelegate + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`. + public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)? + + /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`. + public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. + public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: Delegate Methods + + /** + Tells the delegate that a download task has finished downloading. + + - parameter session: The session containing the download task that finished. + - parameter downloadTask: The download task that finished. + - parameter location: A file URL for the temporary file. Because the file is temporary, you must either + open the file for reading or move it to a permanent location in your app’s sandbox + container directory before returning from this delegate method. + */ + public func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didFinishDownloadingToURL location: NSURL) + { + if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { + downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) + } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { + delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location) + } + } + + /** + Periodically informs the delegate about the download’s progress. + + - parameter session: The session containing the download task. + - parameter downloadTask: The download task. + - parameter bytesWritten: The number of bytes transferred since the last time this delegate + method was called. + - parameter totalBytesWritten: The total number of bytes transferred so far. + - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length + header. If this header was not provided, the value is + `NSURLSessionTransferSizeUnknown`. + */ + public func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { + delegate.URLSession( + session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite + ) + } + } + + /** + Tells the delegate that the download task has resumed downloading. + + - parameter session: The session containing the download task that finished. + - parameter downloadTask: The download task that resumed. See explanation in the discussion. + - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the + existing content, then this value is zero. Otherwise, this value is an + integer representing the number of bytes on disk that do not need to be + retrieved again. + - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. + If this header was not provided, the value is NSURLSessionTransferSizeUnknown. + */ + public func URLSession( + session: NSURLSession, + downloadTask: NSURLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { + delegate.URLSession( + session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes + ) + } + } + + // MARK: - NSURLSessionStreamDelegate + + var _streamTaskReadClosed: Any? + var _streamTaskWriteClosed: Any? + var _streamTaskBetterRouteDiscovered: Any? + var _streamTaskDidBecomeInputStream: Any? + + // MARK: - NSObject + + public override func respondsToSelector(selector: Selector) -> Bool { + #if !os(OSX) + if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) { + return sessionDidFinishEventsForBackgroundURLSession != nil + } + #endif + + switch selector { + case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)): + return sessionDidBecomeInvalidWithError != nil + case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)): + return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) + case #selector(NSURLSessionTaskDelegate.URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): + return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) + case #selector(NSURLSessionDataDelegate.URLSession(_:dataTask:didReceiveResponse:completionHandler:)): + return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) + default: + return self.dynamicType.instancesRespondToSelector(selector) + } + } + } +} diff --git a/Pods/Alamofire/Source/MultipartFormData.swift b/Pods/Alamofire/Source/MultipartFormData.swift new file mode 100644 index 0000000..b4087ec --- /dev/null +++ b/Pods/Alamofire/Source/MultipartFormData.swift @@ -0,0 +1,659 @@ +// +// MultipartFormData.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +#if os(iOS) || os(watchOS) || os(tvOS) +import MobileCoreServices +#elseif os(OSX) +import CoreServices +#endif + +/** + Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode + multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead + to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the + data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for + larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. + + For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well + and the w3 form documentation. + + - https://www.ietf.org/rfc/rfc2388.txt + - https://www.ietf.org/rfc/rfc2045.txt + - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 +*/ +public class MultipartFormData { + + // MARK: - Helper Types + + struct EncodingCharacters { + static let CRLF = "\r\n" + } + + struct BoundaryGenerator { + enum BoundaryType { + case Initial, Encapsulated, Final + } + + static func randomBoundary() -> String { + return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random()) + } + + static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData { + let boundaryText: String + + switch boundaryType { + case .Initial: + boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)" + case .Encapsulated: + boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)" + case .Final: + boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)" + } + + return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! + } + } + + class BodyPart { + let headers: [String: String] + let bodyStream: NSInputStream + let bodyContentLength: UInt64 + var hasInitialBoundary = false + var hasFinalBoundary = false + + init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) { + self.headers = headers + self.bodyStream = bodyStream + self.bodyContentLength = bodyContentLength + } + } + + // MARK: - Properties + + /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. + public var contentType: String { return "multipart/form-data; boundary=\(boundary)" } + + /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. + public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } + + /// The boundary used to separate the body parts in the encoded form data. + public let boundary: String + + private var bodyParts: [BodyPart] + private var bodyPartError: NSError? + private let streamBufferSize: Int + + // MARK: - Lifecycle + + /** + Creates a multipart form data object. + + - returns: The multipart form data object. + */ + public init() { + self.boundary = BoundaryGenerator.randomBoundary() + self.bodyParts = [] + + /** + * The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more + * information, please refer to the following article: + * - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html + */ + + self.streamBufferSize = 1024 + } + + // MARK: - Body Parts + + /** + Creates a body part from the data and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}` (HTTP Header) + - Encoded data + - Multipart form boundary + + - parameter data: The data to encode into the multipart form data. + - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + */ + public func appendBodyPart(data data: NSData, name: String) { + let headers = contentHeaders(name: name) + let stream = NSInputStream(data: data) + let length = UInt64(data.length) + + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part from the data and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}` (HTTP Header) + - `Content-Type: #{generated mimeType}` (HTTP Header) + - Encoded data + - Multipart form boundary + + - parameter data: The data to encode into the multipart form data. + - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header. + */ + public func appendBodyPart(data data: NSData, name: String, mimeType: String) { + let headers = contentHeaders(name: name, mimeType: mimeType) + let stream = NSInputStream(data: data) + let length = UInt64(data.length) + + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part from the data and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + - `Content-Type: #{mimeType}` (HTTP Header) + - Encoded file data + - Multipart form boundary + + - parameter data: The data to encode into the multipart form data. + - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header. + - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header. + */ + public func appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) + let stream = NSInputStream(data: data) + let length = UInt64(data.length) + + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part from the file and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) + - `Content-Type: #{generated mimeType}` (HTTP Header) + - Encoded file data + - Multipart form boundary + + The filename in the `Content-Disposition` HTTP header is generated from the last path component of the + `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the + system associated MIME type. + + - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. + - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. + */ + public func appendBodyPart(fileURL fileURL: NSURL, name: String) { + if let + fileName = fileURL.lastPathComponent, + pathExtension = fileURL.pathExtension + { + let mimeType = mimeTypeForPathExtension(pathExtension) + appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType) + } else { + let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)" + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) + } + } + + /** + Creates a body part from the file and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) + - Content-Type: #{mimeType} (HTTP Header) + - Encoded file data + - Multipart form boundary + + - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. + - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. + - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header. + - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header. + */ + public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) + + //============================================================ + // Check 1 - is file URL? + //============================================================ + + guard fileURL.fileURL else { + let failureReason = "The file URL does not point to a file URL: \(fileURL)" + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) + return + } + + //============================================================ + // Check 2 - is file URL reachable? + //============================================================ + + var isReachable = true + + if #available(OSX 10.10, *) { + isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil) + } + + guard isReachable else { + setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)") + return + } + + //============================================================ + // Check 3 - is file URL a directory? + //============================================================ + + var isDirectory: ObjCBool = false + + guard let + path = fileURL.path + where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else + { + let failureReason = "The file URL is a directory, not a file: \(fileURL)" + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) + return + } + + //============================================================ + // Check 4 - can the file size be extracted? + //============================================================ + + var bodyContentLength: UInt64? + + do { + if let + path = fileURL.path, + fileSize = try NSFileManager.defaultManager().attributesOfItemAtPath(path)[NSFileSize] as? NSNumber + { + bodyContentLength = fileSize.unsignedLongLongValue + } + } catch { + // No-op + } + + guard let length = bodyContentLength else { + let failureReason = "Could not fetch attributes from the file URL: \(fileURL)" + setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason) + return + } + + //============================================================ + // Check 5 - can a stream be created from file URL? + //============================================================ + + guard let stream = NSInputStream(URL: fileURL) else { + let failureReason = "Failed to create an input stream from the file URL: \(fileURL)" + setBodyPartError(code: NSURLErrorCannotOpenFile, failureReason: failureReason) + return + } + + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part from the stream and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + - `Content-Type: #{mimeType}` (HTTP Header) + - Encoded stream data + - Multipart form boundary + + - parameter stream: The input stream to encode in the multipart form data. + - parameter length: The content length of the stream. + - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header. + - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header. + - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header. + */ + public func appendBodyPart( + stream stream: NSInputStream, + length: UInt64, + name: String, + fileName: String, + mimeType: String) + { + let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType) + appendBodyPart(stream: stream, length: length, headers: headers) + } + + /** + Creates a body part with the headers, stream and length and appends it to the multipart form data object. + + The body part data will be encoded using the following format: + + - HTTP headers + - Encoded stream data + - Multipart form boundary + + - parameter stream: The input stream to encode in the multipart form data. + - parameter length: The content length of the stream. + - parameter headers: The HTTP headers for the body part. + */ + public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) { + let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) + bodyParts.append(bodyPart) + } + + // MARK: - Data Encoding + + /** + Encodes all the appended body parts into a single `NSData` object. + + It is important to note that this method will load all the appended body parts into memory all at the same + time. This method should only be used when the encoded data will have a small memory footprint. For large data + cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method. + + - throws: An `NSError` if encoding encounters an error. + + - returns: The encoded `NSData` if encoding is successful. + */ + public func encode() throws -> NSData { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + let encoded = NSMutableData() + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + let encodedData = try encodeBodyPart(bodyPart) + encoded.appendData(encodedData) + } + + return encoded + } + + /** + Writes the appended body parts into the given file URL. + + This process is facilitated by reading and writing with input and output streams, respectively. Thus, + this approach is very memory efficient and should be used for large body part data. + + - parameter fileURL: The file URL to write the multipart form data into. + + - throws: An `NSError` if encoding encounters an error. + */ + public func writeEncodedDataToDisk(fileURL: NSURL) throws { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) { + let failureReason = "A file already exists at the given file URL: \(fileURL)" + throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason) + } else if !fileURL.fileURL { + let failureReason = "The URL does not point to a valid file: \(fileURL)" + throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason) + } + + let outputStream: NSOutputStream + + if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) { + outputStream = possibleOutputStream + } else { + let failureReason = "Failed to create an output stream with the given URL: \(fileURL)" + throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, failureReason: failureReason) + } + + outputStream.open() + + self.bodyParts.first?.hasInitialBoundary = true + self.bodyParts.last?.hasFinalBoundary = true + + for bodyPart in self.bodyParts { + try writeBodyPart(bodyPart, toOutputStream: outputStream) + } + + outputStream.close() + } + + // MARK: - Private - Body Part Encoding + + private func encodeBodyPart(bodyPart: BodyPart) throws -> NSData { + let encoded = NSMutableData() + + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + encoded.appendData(initialData) + + let headerData = encodeHeaderDataForBodyPart(bodyPart) + encoded.appendData(headerData) + + let bodyStreamData = try encodeBodyStreamDataForBodyPart(bodyPart) + encoded.appendData(bodyStreamData) + + if bodyPart.hasFinalBoundary { + encoded.appendData(finalBoundaryData()) + } + + return encoded + } + + private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData { + var headerText = "" + + for (key, value) in bodyPart.headers { + headerText += "\(key): \(value)\(EncodingCharacters.CRLF)" + } + headerText += EncodingCharacters.CRLF + + return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! + } + + private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData { + let inputStream = bodyPart.bodyStream + inputStream.open() + + var error: NSError? + let encoded = NSMutableData() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if inputStream.streamError != nil { + error = inputStream.streamError + break + } + + if bytesRead > 0 { + encoded.appendBytes(buffer, length: bytesRead) + } else if bytesRead < 0 { + let failureReason = "Failed to read from input stream: \(inputStream)" + error = Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason) + break + } else { + break + } + } + + inputStream.close() + + if let error = error { + throw error + } + + return encoded + } + + // MARK: - Private - Writing Body Part to Output Stream + + private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { + try writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) + try writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream) + try writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream) + try writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) + } + + private func writeInitialBoundaryDataForBodyPart( + bodyPart: BodyPart, + toOutputStream outputStream: NSOutputStream) + throws + { + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + return try writeData(initialData, toOutputStream: outputStream) + } + + private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { + let headerData = encodeHeaderDataForBodyPart(bodyPart) + return try writeData(headerData, toOutputStream: outputStream) + } + + private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws { + let inputStream = bodyPart.bodyStream + inputStream.open() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let streamError = inputStream.streamError { + throw streamError + } + + if bytesRead > 0 { + if buffer.count != bytesRead { + buffer = Array(buffer[0.. 0 { + if outputStream.hasSpaceAvailable { + let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) + + if let streamError = outputStream.streamError { + throw streamError + } + + if bytesWritten < 0 { + let failureReason = "Failed to write to output stream: \(outputStream)" + throw Error.error(domain: NSURLErrorDomain, code: .OutputStreamWriteFailed, failureReason: failureReason) + } + + bytesToWrite -= bytesWritten + + if bytesToWrite > 0 { + buffer = Array(buffer[bytesWritten.. String { + if let + id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(), + contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() + { + return contentType as String + } + + return "application/octet-stream" + } + + // MARK: - Private - Content Headers + + private func contentHeaders(name name: String) -> [String: String] { + return ["Content-Disposition": "form-data; name=\"\(name)\""] + } + + private func contentHeaders(name name: String, mimeType: String) -> [String: String] { + return [ + "Content-Disposition": "form-data; name=\"\(name)\"", + "Content-Type": "\(mimeType)" + ] + } + + private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] { + return [ + "Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"", + "Content-Type": "\(mimeType)" + ] + } + + // MARK: - Private - Boundary Encoding + + private func initialBoundaryData() -> NSData { + return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary) + } + + private func encapsulatedBoundaryData() -> NSData { + return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary) + } + + private func finalBoundaryData() -> NSData { + return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary) + } + + // MARK: - Private - Errors + + private func setBodyPartError(code code: Int, failureReason: String) { + guard bodyPartError == nil else { return } + bodyPartError = Error.error(domain: NSURLErrorDomain, code: code, failureReason: failureReason) + } +} diff --git a/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/Pods/Alamofire/Source/NetworkReachabilityManager.swift new file mode 100644 index 0000000..1e5c7b0 --- /dev/null +++ b/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -0,0 +1,244 @@ +// +// NetworkReachabilityManager.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +#if !os(watchOS) + +import Foundation +import SystemConfiguration + +/** + The `NetworkReachabilityManager` class listens for reachability changes of hosts 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 retry + network requests 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. +*/ +public class NetworkReachabilityManager { + /** + Defines the various states of network reachability. + + - Unknown: It is unknown whether the network is reachable. + - NotReachable: The network is not reachable. + - ReachableOnWWAN: The network is reachable over the WWAN connection. + - ReachableOnWiFi: The network is reachable over the WiFi connection. + */ + public enum NetworkReachabilityStatus { + case Unknown + case NotReachable + case Reachable(ConnectionType) + } + + /** + Defines the various connection types detected by reachability flags. + + - EthernetOrWiFi: The connection type is either over Ethernet or WiFi. + - WWAN: The connection type is a WWAN connection. + */ + public enum ConnectionType { + case EthernetOrWiFi + case WWAN + } + + /// A closure executed when the network reachability status changes. The closure takes a single argument: the + /// network reachability status. + public typealias Listener = NetworkReachabilityStatus -> Void + + // MARK: - Properties + + /// Whether the network is currently reachable. + public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } + + /// Whether the network is currently reachable over the WWAN interface. + public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .Reachable(.WWAN) } + + /// Whether the network is currently reachable over Ethernet or WiFi interface. + public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .Reachable(.EthernetOrWiFi) } + + /// The current network reachability status. + public var networkReachabilityStatus: NetworkReachabilityStatus { + guard let flags = self.flags else { return .Unknown } + return networkReachabilityStatusForFlags(flags) + } + + /// The dispatch queue to execute the `listener` closure on. + public var listenerQueue: dispatch_queue_t = dispatch_get_main_queue() + + /// A closure executed when the network reachability status changes. + public var listener: Listener? + + private var flags: SCNetworkReachabilityFlags? { + var flags = SCNetworkReachabilityFlags() + + if SCNetworkReachabilityGetFlags(reachability, &flags) { + return flags + } + + return nil + } + + private let reachability: SCNetworkReachability + private var previousFlags: SCNetworkReachabilityFlags + + // MARK: - Initialization + + /** + Creates a `NetworkReachabilityManager` instance with the specified host. + + - parameter host: The host used to evaluate network reachability. + + - returns: The new `NetworkReachabilityManager` instance. + */ + public convenience init?(host: String) { + guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } + self.init(reachability: reachability) + } + + /** + Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. + + Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing + status of the device, both IPv4 and IPv6. + + - returns: The new `NetworkReachabilityManager` instance. + */ + public convenience init?() { + var address = sockaddr_in() + address.sin_len = UInt8(sizeofValue(address)) + address.sin_family = sa_family_t(AF_INET) + + guard let reachability = withUnsafePointer(&address, { + SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) + }) else { return nil } + + self.init(reachability: reachability) + } + + private init(reachability: SCNetworkReachability) { + self.reachability = reachability + self.previousFlags = SCNetworkReachabilityFlags() + } + + deinit { + stopListening() + } + + // MARK: - Listening + + /** + Starts listening for changes in network reachability status. + + - returns: `true` if listening was started successfully, `false` otherwise. + */ + public func startListening() -> Bool { + var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) + context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque()) + + let callbackEnabled = SCNetworkReachabilitySetCallback( + reachability, + { (_, flags, info) in + let reachability = Unmanaged.fromOpaque(COpaquePointer(info)).takeUnretainedValue() + reachability.notifyListener(flags) + }, + &context + ) + + let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) + + dispatch_async(listenerQueue) { + self.previousFlags = SCNetworkReachabilityFlags() + self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) + } + + return callbackEnabled && queueEnabled + } + + /** + Stops listening for changes in network reachability status. + */ + public func stopListening() { + SCNetworkReachabilitySetCallback(reachability, nil, nil) + SCNetworkReachabilitySetDispatchQueue(reachability, nil) + } + + // MARK: - Internal - Listener Notification + + func notifyListener(flags: SCNetworkReachabilityFlags) { + guard previousFlags != flags else { return } + previousFlags = flags + + listener?(networkReachabilityStatusForFlags(flags)) + } + + // MARK: - Internal - Network Reachability Status + + func networkReachabilityStatusForFlags(flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { + guard flags.contains(.Reachable) else { return .NotReachable } + + var networkStatus: NetworkReachabilityStatus = .NotReachable + + if !flags.contains(.ConnectionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) } + + if flags.contains(.ConnectionOnDemand) || flags.contains(.ConnectionOnTraffic) { + if !flags.contains(.InterventionRequired) { networkStatus = .Reachable(.EthernetOrWiFi) } + } + + #if os(iOS) + if flags.contains(.IsWWAN) { networkStatus = .Reachable(.WWAN) } + #endif + + return networkStatus + } +} + +// MARK: - + +extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} + +/** + Returns whether the two network reachability status values are equal. + + - parameter lhs: The left-hand side value to compare. + - parameter rhs: The right-hand side value to compare. + + - returns: `true` if the two values are equal, `false` otherwise. +*/ +public func ==( + lhs: NetworkReachabilityManager.NetworkReachabilityStatus, + rhs: NetworkReachabilityManager.NetworkReachabilityStatus) + -> Bool +{ + switch (lhs, rhs) { + case (.Unknown, .Unknown): + return true + case (.NotReachable, .NotReachable): + return true + case let (.Reachable(lhsConnectionType), .Reachable(rhsConnectionType)): + return lhsConnectionType == rhsConnectionType + default: + return false + } +} + +#endif diff --git a/Pods/Alamofire/Source/Notifications.swift b/Pods/Alamofire/Source/Notifications.swift new file mode 100644 index 0000000..cece87a --- /dev/null +++ b/Pods/Alamofire/Source/Notifications.swift @@ -0,0 +1,47 @@ +// +// Notifications.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Contains all the `NSNotification` names posted by Alamofire with descriptions of each notification's payload. +public struct Notifications { + /// Used as a namespace for all `NSURLSessionTask` related notifications. + public struct Task { + /// Notification posted when an `NSURLSessionTask` is resumed. The notification `object` contains the resumed + /// `NSURLSessionTask`. + public static let DidResume = "com.alamofire.notifications.task.didResume" + + /// Notification posted when an `NSURLSessionTask` is suspended. The notification `object` contains the + /// suspended `NSURLSessionTask`. + public static let DidSuspend = "com.alamofire.notifications.task.didSuspend" + + /// Notification posted when an `NSURLSessionTask` is cancelled. The notification `object` contains the + /// cancelled `NSURLSessionTask`. + public static let DidCancel = "com.alamofire.notifications.task.didCancel" + + /// Notification posted when an `NSURLSessionTask` is completed. The notification `object` contains the + /// completed `NSURLSessionTask`. + public static let DidComplete = "com.alamofire.notifications.task.didComplete" + } +} diff --git a/Pods/Alamofire/Source/ParameterEncoding.swift b/Pods/Alamofire/Source/ParameterEncoding.swift new file mode 100644 index 0000000..32e63d9 --- /dev/null +++ b/Pods/Alamofire/Source/ParameterEncoding.swift @@ -0,0 +1,261 @@ +// +// ParameterEncoding.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/** + HTTP method definitions. + + See https://tools.ietf.org/html/rfc7231#section-4.3 +*/ +public enum Method: String { + case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT +} + +// MARK: ParameterEncoding + +/** + Used to specify the way in which a set of parameters are applied to a URL request. + + - `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`, + and `DELETE` requests, or set as the body for requests with any other HTTP method. The + `Content-Type` HTTP header field of an encoded request with HTTP body is set to + `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification + for how to encode collection types, the convention of appending `[]` to the key for array + values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested + dictionary values (`foo[bar]=baz`). + + - `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same + implementation as the `.URL` case, but always applies the encoded result to the URL. + + - `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is + set as the body of the request. The `Content-Type` HTTP header field of an encoded request is + set to `application/json`. + + - `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, + according to the associated format and write options values, which is set as the body of the + request. The `Content-Type` HTTP header field of an encoded request is set to + `application/x-plist`. + + - `Custom`: Uses the associated closure value to construct a new request given an existing request and + parameters. +*/ +public enum ParameterEncoding { + case URL + case URLEncodedInURL + case JSON + case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions) + case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) + + /** + Creates a URL request by encoding parameters and applying them onto an existing request. + + - parameter URLRequest: The request to have parameters applied. + - parameter parameters: The parameters to apply. + + - returns: A tuple containing the constructed request and the error that occurred during parameter encoding, + if any. + */ + public func encode( + URLRequest: URLRequestConvertible, + parameters: [String: AnyObject]?) + -> (NSMutableURLRequest, NSError?) + { + var mutableURLRequest = URLRequest.URLRequest + + guard let parameters = parameters else { return (mutableURLRequest, nil) } + + var encodingError: NSError? = nil + + switch self { + case .URL, .URLEncodedInURL: + func query(parameters: [String: AnyObject]) -> String { + var components: [(String, String)] = [] + + for key in parameters.keys.sort(<) { + let value = parameters[key]! + components += queryComponents(key, value) + } + + return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&") + } + + func encodesParametersInURL(method: Method) -> Bool { + switch self { + case .URLEncodedInURL: + return true + default: + break + } + + switch method { + case .GET, .HEAD, .DELETE: + return true + default: + return false + } + } + + if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) { + if let + URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) + where !parameters.isEmpty + { + let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) + URLComponents.percentEncodedQuery = percentEncodedQuery + mutableURLRequest.URL = URLComponents.URL + } + } else { + if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { + mutableURLRequest.setValue( + "application/x-www-form-urlencoded; charset=utf-8", + forHTTPHeaderField: "Content-Type" + ) + } + + mutableURLRequest.HTTPBody = query(parameters).dataUsingEncoding( + NSUTF8StringEncoding, + allowLossyConversion: false + ) + } + case .JSON: + do { + let options = NSJSONWritingOptions() + let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options) + + if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { + mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + mutableURLRequest.HTTPBody = data + } catch { + encodingError = error as NSError + } + case .PropertyList(let format, let options): + do { + let data = try NSPropertyListSerialization.dataWithPropertyList( + parameters, + format: format, + options: options + ) + + if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { + mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + } + + mutableURLRequest.HTTPBody = data + } catch { + encodingError = error as NSError + } + case .Custom(let closure): + (mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters) + } + + return (mutableURLRequest, encodingError) + } + + /** + Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. + + - parameter key: The key of the query component. + - parameter value: The value of the query component. + + - returns: The percent-escaped, URL encoded query string components. + */ + public func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { + var components: [(String, String)] = [] + + if let dictionary = value as? [String: AnyObject] { + for (nestedKey, value) in dictionary { + components += queryComponents("\(key)[\(nestedKey)]", value) + } + } else if let array = value as? [AnyObject] { + for value in array { + components += queryComponents("\(key)[]", value) + } + } else { + components.append((escape(key), escape("\(value)"))) + } + + return components + } + + /** + Returns a percent-escaped string following RFC 3986 for a query string key or value. + + RFC 3986 states that the following characters are "reserved" characters. + + - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + should be percent-escaped in the query string. + + - parameter string: The string to be percent-escaped. + + - returns: The percent-escaped string. + */ + public func escape(string: String) -> String { + let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 + let subDelimitersToEncode = "!$&'()*+,;=" + + let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet + allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode) + + var escaped = "" + + //========================================================================================================== + // + // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few + // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no + // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more + // info, please refer to: + // + // - https://github.com/Alamofire/Alamofire/issues/206 + // + //========================================================================================================== + + if #available(iOS 8.3, OSX 10.10, *) { + escaped = string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string + } else { + let batchSize = 50 + var index = string.startIndex + + while index != string.endIndex { + let startIndex = index + let endIndex = index.advancedBy(batchSize, limit: string.endIndex) + let range = startIndex.. Self + { + let credential = NSURLCredential(user: user, password: password, persistence: persistence) + + return authenticate(usingCredential: credential) + } + + /** + Associates a specified credential with the request. + + - parameter credential: The credential. + + - returns: The request. + */ + public func authenticate(usingCredential credential: NSURLCredential) -> Self { + delegate.credential = credential + + return self + } + + /** + Returns a base64 encoded basic authentication credential as an authorization header dictionary. + + - parameter user: The user. + - parameter password: The password. + + - returns: A dictionary with Authorization key and credential value or empty dictionary if encoding fails. + */ + public static func authorizationHeader(user user: String, password: String) -> [String: String] { + guard let data = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return [:] } + + let credential = data.base64EncodedStringWithOptions([]) + + return ["Authorization": "Basic \(credential)"] + } + + // MARK: - Progress + + /** + Sets a closure to be called periodically during the lifecycle of the request as data is written to or read + from the server. + + - For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected + to write. + - For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes + expected to read. + + - parameter closure: The code to be executed periodically during the lifecycle of the request. + + - returns: The request. + */ + public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self { + if let uploadDelegate = delegate as? UploadTaskDelegate { + uploadDelegate.uploadProgress = closure + } else if let dataDelegate = delegate as? DataTaskDelegate { + dataDelegate.dataProgress = closure + } else if let downloadDelegate = delegate as? DownloadTaskDelegate { + downloadDelegate.downloadProgress = closure + } + + return self + } + + /** + Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. + + This closure returns the bytes most recently received from the server, not including data from previous calls. + If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is + also important to note that the `response` closure will be called with nil `responseData`. + + - parameter closure: The code to be executed periodically during the lifecycle of the request. + + - returns: The request. + */ + public func stream(closure: (NSData -> Void)? = nil) -> Self { + if let dataDelegate = delegate as? DataTaskDelegate { + dataDelegate.dataStream = closure + } + + return self + } + + // MARK: - State + + /** + Resumes the request. + */ + public func resume() { + if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } + + task.resume() + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidResume, object: task) + } + + /** + Suspends the request. + */ + public func suspend() { + task.suspend() + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidSuspend, object: task) + } + + /** + Cancels the request. + */ + public func cancel() { + if let + downloadDelegate = delegate as? DownloadTaskDelegate, + downloadTask = downloadDelegate.downloadTask + { + downloadTask.cancelByProducingResumeData { data in + downloadDelegate.resumeData = data + } + } else { + task.cancel() + } + + NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidCancel, object: task) + } + + // MARK: - TaskDelegate + + /** + The task delegate is responsible for handling all delegate callbacks for the underlying task as well as + executing all operations attached to the serial operation queue upon task completion. + */ + public class TaskDelegate: NSObject { + + /// The serial operation queue used to execute all operations after the task completes. + public let queue: NSOperationQueue + + let task: NSURLSessionTask + let progress: NSProgress + + var data: NSData? { return nil } + var error: NSError? + + var initialResponseTime: CFAbsoluteTime? + var credential: NSURLCredential? + + init(task: NSURLSessionTask) { + self.task = task + self.progress = NSProgress(totalUnitCount: 0) + self.queue = { + let operationQueue = NSOperationQueue() + operationQueue.maxConcurrentOperationCount = 1 + operationQueue.suspended = true + + if #available(OSX 10.10, *) { + operationQueue.qualityOfService = NSQualityOfService.Utility + } + + return operationQueue + }() + } + + deinit { + queue.cancelAllOperations() + queue.suspended = false + } + + // MARK: - NSURLSessionTaskDelegate + + // MARK: Override Closures + + var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? + var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? + var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)? + var taskDidCompleteWithError: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? + + // MARK: Delegate Methods + + func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + willPerformHTTPRedirection response: NSHTTPURLResponse, + newRequest request: NSURLRequest, + completionHandler: ((NSURLRequest?) -> Void)) + { + var redirectRequest: NSURLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + didReceiveChallenge challenge: NSURLAuthenticationChallenge, + completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) + { + var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling + var credential: NSURLCredential? + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) + } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + let host = challenge.protectionSpace.host + + if let + serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host), + serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) { + disposition = .UseCredential + credential = NSURLCredential(forTrust: serverTrust) + } else { + disposition = .CancelAuthenticationChallenge + } + } + } else { + if challenge.previousFailureCount > 0 { + disposition = .RejectProtectionSpace + } else { + credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace) + + if credential != nil { + disposition = .UseCredential + } + } + } + + completionHandler(disposition, credential) + } + + func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) + { + var bodyStream: NSInputStream? + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + bodyStream = taskNeedNewBodyStream(session, task) + } + + completionHandler(bodyStream) + } + + func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { + if let taskDidCompleteWithError = taskDidCompleteWithError { + taskDidCompleteWithError(session, task, error) + } else { + if let error = error { + self.error = error + + if let + downloadDelegate = self as? DownloadTaskDelegate, + userInfo = error.userInfo as? [String: AnyObject], + resumeData = userInfo[NSURLSessionDownloadTaskResumeData] as? NSData + { + downloadDelegate.resumeData = resumeData + } + } + + queue.suspended = false + } + } + } + + // MARK: - DataTaskDelegate + + class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate { + var dataTask: NSURLSessionDataTask? { return task as? NSURLSessionDataTask } + + private var totalBytesReceived: Int64 = 0 + private var mutableData: NSMutableData + override var data: NSData? { + if dataStream != nil { + return nil + } else { + return mutableData + } + } + + private var expectedContentLength: Int64? + private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)? + private var dataStream: ((data: NSData) -> Void)? + + override init(task: NSURLSessionTask) { + mutableData = NSMutableData() + super.init(task: task) + } + + // MARK: - NSURLSessionDataDelegate + + // MARK: Override Closures + + var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? + var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? + var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? + var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? + + // MARK: Delegate Methods + + func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + didReceiveResponse response: NSURLResponse, + completionHandler: (NSURLSessionResponseDisposition -> Void)) + { + var disposition: NSURLSessionResponseDisposition = .Allow + + expectedContentLength = response.expectedContentLength + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) + { + dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) + } + + func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else { + if let dataStream = dataStream { + dataStream(data: data) + } else { + mutableData.appendData(data) + } + + totalBytesReceived += data.length + let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown + + progress.totalUnitCount = totalBytesExpected + progress.completedUnitCount = totalBytesReceived + + dataProgress?( + bytesReceived: Int64(data.length), + totalBytesReceived: totalBytesReceived, + totalBytesExpectedToReceive: totalBytesExpected + ) + } + } + + func URLSession( + session: NSURLSession, + dataTask: NSURLSessionDataTask, + willCacheResponse proposedResponse: NSCachedURLResponse, + completionHandler: ((NSCachedURLResponse?) -> Void)) + { + var cachedResponse: NSCachedURLResponse? = proposedResponse + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) + } + + completionHandler(cachedResponse) + } + } +} + +// MARK: - CustomStringConvertible + +extension Request: CustomStringConvertible { + + /** + The textual representation used when written to an output stream, which includes the HTTP method and URL, as + well as the response status code if a response has been received. + */ + public var description: String { + var components: [String] = [] + + if let HTTPMethod = request?.HTTPMethod { + components.append(HTTPMethod) + } + + if let URLString = request?.URL?.absoluteString { + components.append(URLString) + } + + if let response = response { + components.append("(\(response.statusCode))") + } + + return components.joinWithSeparator(" ") + } +} + +// MARK: - CustomDebugStringConvertible + +extension Request: CustomDebugStringConvertible { + func cURLRepresentation() -> String { + var components = ["$ curl -i"] + + guard let + request = self.request, + URL = request.URL, + host = URL.host + else { + return "$ curl command could not be created" + } + + if let HTTPMethod = request.HTTPMethod where HTTPMethod != "GET" { + components.append("-X \(HTTPMethod)") + } + + if let credentialStorage = self.session.configuration.URLCredentialStorage { + let protectionSpace = NSURLProtectionSpace( + host: host, + port: URL.port?.integerValue ?? 0, + protocol: URL.scheme, + realm: host, + authenticationMethod: NSURLAuthenticationMethodHTTPBasic + ) + + if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values { + for credential in credentials { + components.append("-u \(credential.user!):\(credential.password!)") + } + } else { + if let credential = delegate.credential { + components.append("-u \(credential.user!):\(credential.password!)") + } + } + } + + if session.configuration.HTTPShouldSetCookies { + if let + cookieStorage = session.configuration.HTTPCookieStorage, + cookies = cookieStorage.cookiesForURL(URL) where !cookies.isEmpty + { + let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value ?? String());" } + components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"") + } + } + + var headers: [NSObject: AnyObject] = [:] + + if let additionalHeaders = session.configuration.HTTPAdditionalHeaders { + for (field, value) in additionalHeaders where field != "Cookie" { + headers[field] = value + } + } + + if let headerFields = request.allHTTPHeaderFields { + for (field, value) in headerFields where field != "Cookie" { + headers[field] = value + } + } + + for (field, value) in headers { + components.append("-H \"\(field): \(value)\"") + } + + if let + HTTPBodyData = request.HTTPBody, + HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding) + { + var escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\\\"", withString: "\\\\\"") + escapedBody = escapedBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") + + components.append("-d \"\(escapedBody)\"") + } + + components.append("\"\(URL.absoluteString)\"") + + return components.joinWithSeparator(" \\\n\t") + } + + /// The textual representation used when written to an output stream, in the form of a cURL command. + public var debugDescription: String { + return cURLRepresentation() + } +} diff --git a/Pods/Alamofire/Source/Response.swift b/Pods/Alamofire/Source/Response.swift new file mode 100644 index 0000000..dd700bb --- /dev/null +++ b/Pods/Alamofire/Source/Response.swift @@ -0,0 +1,97 @@ +// +// Response.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Used to store all response data returned from a completed `Request`. +public struct Response { + /// The URL request sent to the server. + public let request: NSURLRequest? + + /// The server's response to the URL request. + public let response: NSHTTPURLResponse? + + /// The data returned by the server. + public let data: NSData? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the `Request`. + public let timeline: Timeline + + /** + Initializes the `Response` instance with the specified URL request, URL response, server data and response + serialization result. + + - parameter request: The URL request sent to the server. + - parameter response: The server's response to the URL request. + - parameter data: The data returned by the server. + - parameter result: The result of response serialization. + - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + + - returns: the new `Response` instance. + */ + public init( + request: NSURLRequest?, + response: NSHTTPURLResponse?, + data: NSData?, + result: Result, + timeline: Timeline = Timeline()) + { + self.request = request + self.response = response + self.data = data + self.result = result + self.timeline = timeline + } +} + +// MARK: - CustomStringConvertible + +extension Response: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + return result.debugDescription + } +} + +// MARK: - CustomDebugStringConvertible + +extension Response: CustomDebugStringConvertible { + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the server data and the response serialization result. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[Data]: \(data?.length ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") + + return output.joinWithSeparator("\n") + } +} diff --git a/Pods/Alamofire/Source/ResponseSerialization.swift b/Pods/Alamofire/Source/ResponseSerialization.swift new file mode 100644 index 0000000..5b7b61f --- /dev/null +++ b/Pods/Alamofire/Source/ResponseSerialization.swift @@ -0,0 +1,378 @@ +// +// ResponseSerialization.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +// MARK: ResponseSerializer + +/** + The type in which all response serializers must conform to in order to serialize a response. +*/ +public protocol ResponseSerializerType { + /// The type of serialized object to be created by this `ResponseSerializerType`. + associatedtype SerializedObject + + /// The type of error to be created by this `ResponseSerializer` if serialization fails. + associatedtype ErrorObject: ErrorType + + /** + A closure used by response handlers that takes a request, response, data and error and returns a result. + */ + var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result { get } +} + +// MARK: - + +/** + A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object. +*/ +public struct ResponseSerializer: ResponseSerializerType { + /// The type of serialized object to be created by this `ResponseSerializer`. + public typealias SerializedObject = Value + + /// The type of error to be created by this `ResponseSerializer` if serialization fails. + public typealias ErrorObject = Error + + /** + A closure used by response handlers that takes a request, response, data and error and returns a result. + */ + public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result + + /** + Initializes the `ResponseSerializer` instance with the given serialize response closure. + + - parameter serializeResponse: The closure used to serialize the response. + + - returns: The new generic response serializer instance. + */ + public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - Default + +extension Request { + + /** + Adds a handler to be called once the request has finished. + + - parameter queue: The queue on which the completion handler is dispatched. + - parameter completionHandler: The code to be executed once the request has finished. + + - returns: The request. + */ + public func response( + queue queue: dispatch_queue_t? = nil, + completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void) + -> Self + { + delegate.queue.addOperationWithBlock { + dispatch_async(queue ?? dispatch_get_main_queue()) { + completionHandler(self.request, self.response, self.delegate.data, self.delegate.error) + } + } + + return self + } + + /** + Adds a handler to be called once the request has finished. + + - parameter queue: The queue on which the completion handler is dispatched. + - parameter responseSerializer: The response serializer responsible for serializing the request, response, + and data. + - parameter completionHandler: The code to be executed once the request has finished. + + - returns: The request. + */ + public func response( + queue queue: dispatch_queue_t? = nil, + responseSerializer: T, + completionHandler: Response -> Void) + -> Self + { + delegate.queue.addOperationWithBlock { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.delegate.data, + self.delegate.error + ) + + let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() + let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime + + let timeline = Timeline( + requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(), + initialResponseTime: initialResponseTime, + requestCompletedTime: requestCompletedTime, + serializationCompletedTime: CFAbsoluteTimeGetCurrent() + ) + + let response = Response( + request: self.request, + response: self.response, + data: self.delegate.data, + result: result, + timeline: timeline + ) + + dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(response) } + } + + return self + } +} + +// MARK: - Data + +extension Request { + + /** + Creates a response serializer that returns the associated data as-is. + + - returns: A data response serializer. + */ + public static func dataResponseSerializer() -> ResponseSerializer { + return ResponseSerializer { _, response, data, error in + guard error == nil else { return .Failure(error!) } + + if let response = response where response.statusCode == 204 { return .Success(NSData()) } + + guard let validData = data else { + let failureReason = "Data could not be serialized. Input data was nil." + let error = Error.error(code: .DataSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + return .Success(validData) + } + } + + /** + Adds a handler to be called once the request has finished. + + - parameter completionHandler: The code to be executed once the request has finished. + + - returns: The request. + */ + public func responseData( + queue queue: dispatch_queue_t? = nil, + completionHandler: Response -> Void) + -> Self + { + return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) + } +} + +// MARK: - String + +extension Request { + + /** + Creates a response serializer that returns a string initialized from the response data with the specified + string encoding. + + - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + response, falling back to the default HTTP default character set, ISO-8859-1. + + - returns: A string response serializer. + */ + public static func stringResponseSerializer( + encoding encoding: NSStringEncoding? = nil) + -> ResponseSerializer + { + return ResponseSerializer { _, response, data, error in + guard error == nil else { return .Failure(error!) } + + if let response = response where response.statusCode == 204 { return .Success("") } + + guard let validData = data else { + let failureReason = "String could not be serialized. Input data was nil." + let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName where convertedEncoding == nil { + convertedEncoding = CFStringConvertEncodingToNSStringEncoding( + CFStringConvertIANACharSetNameToEncoding(encodingName) + ) + } + + let actualEncoding = convertedEncoding ?? NSISOLatin1StringEncoding + + if let string = String(data: validData, encoding: actualEncoding) { + return .Success(string) + } else { + let failureReason = "String could not be serialized with encoding: \(actualEncoding)" + let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + } + } + + /** + Adds a handler to be called once the request has finished. + + - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the + server response, falling back to the default HTTP default character set, + ISO-8859-1. + - parameter completionHandler: A closure to be executed once the request has finished. + + - returns: The request. + */ + public func responseString( + queue queue: dispatch_queue_t? = nil, + encoding: NSStringEncoding? = nil, + completionHandler: Response -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: Request.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +// MARK: - JSON + +extension Request { + + /** + Creates a response serializer that returns a JSON object constructed from the response data using + `NSJSONSerialization` with the specified reading options. + + - parameter options: The JSON serialization reading options. `.AllowFragments` by default. + + - returns: A JSON object response serializer. + */ + public static func JSONResponseSerializer( + options options: NSJSONReadingOptions = .AllowFragments) + -> ResponseSerializer + { + return ResponseSerializer { _, response, data, error in + guard error == nil else { return .Failure(error!) } + + if let response = response where response.statusCode == 204 { return .Success(NSNull()) } + + guard let validData = data where validData.length > 0 else { + let failureReason = "JSON could not be serialized. Input data was nil or zero length." + let error = Error.error(code: .JSONSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + do { + let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options) + return .Success(JSON) + } catch { + return .Failure(error as NSError) + } + } + } + + /** + Adds a handler to be called once the request has finished. + + - parameter options: The JSON serialization reading options. `.AllowFragments` by default. + - parameter completionHandler: A closure to be executed once the request has finished. + + - returns: The request. + */ + public func responseJSON( + queue queue: dispatch_queue_t? = nil, + options: NSJSONReadingOptions = .AllowFragments, + completionHandler: Response -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: Request.JSONResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +// MARK: - Property List + +extension Request { + + /** + Creates a response serializer that returns an object constructed from the response data using + `NSPropertyListSerialization` with the specified reading options. + + - parameter options: The property list reading options. `NSPropertyListReadOptions()` by default. + + - returns: A property list object response serializer. + */ + public static func propertyListResponseSerializer( + options options: NSPropertyListReadOptions = NSPropertyListReadOptions()) + -> ResponseSerializer + { + return ResponseSerializer { _, response, data, error in + guard error == nil else { return .Failure(error!) } + + if let response = response where response.statusCode == 204 { return .Success(NSNull()) } + + guard let validData = data where validData.length > 0 else { + let failureReason = "Property list could not be serialized. Input data was nil or zero length." + let error = Error.error(code: .PropertyListSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + do { + let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil) + return .Success(plist) + } catch { + return .Failure(error as NSError) + } + } + } + + /** + Adds a handler to be called once the request has finished. + + - parameter options: The property list reading options. `0` by default. + - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3 + arguments: the URL request, the URL response, the server data and the result + produced while creating the property list. + + - returns: The request. + */ + public func responsePropertyList( + queue queue: dispatch_queue_t? = nil, + options: NSPropertyListReadOptions = NSPropertyListReadOptions(), + completionHandler: Response -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: Request.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} diff --git a/Pods/Alamofire/Source/Result.swift b/Pods/Alamofire/Source/Result.swift new file mode 100644 index 0000000..ed1df0f --- /dev/null +++ b/Pods/Alamofire/Source/Result.swift @@ -0,0 +1,103 @@ +// +// Result.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/** + Used to represent whether a request was successful or encountered an error. + + - Success: The request and all post processing operations were successful resulting in the serialization of the + provided associated value. + - Failure: The request encountered an error resulting in a failure. The associated values are the original data + provided by the server as well as the error that caused the failure. +*/ +public enum Result { + case Success(Value) + case Failure(Error) + + /// Returns `true` if the result is a success, `false` otherwise. + public var isSuccess: Bool { + switch self { + case .Success: + return true + case .Failure: + return false + } + } + + /// Returns `true` if the result is a failure, `false` otherwise. + public var isFailure: Bool { + return !isSuccess + } + + /// Returns the associated value if the result is a success, `nil` otherwise. + public var value: Value? { + switch self { + case .Success(let value): + return value + case .Failure: + return nil + } + } + + /// Returns the associated error value if the result is a failure, `nil` otherwise. + public var error: Error? { + switch self { + case .Success: + return nil + case .Failure(let error): + return error + } + } +} + +// MARK: - CustomStringConvertible + +extension Result: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + switch self { + case .Success: + return "SUCCESS" + case .Failure: + return "FAILURE" + } + } +} + +// MARK: - CustomDebugStringConvertible + +extension Result: CustomDebugStringConvertible { + /// The debug textual representation used when written to an output stream, which includes whether the result was a + /// success or failure in addition to the value or error. + public var debugDescription: String { + switch self { + case .Success(let value): + return "SUCCESS: \(value)" + case .Failure(let error): + return "FAILURE: \(error)" + } + } +} diff --git a/Pods/Alamofire/Source/ServerTrustPolicy.swift b/Pods/Alamofire/Source/ServerTrustPolicy.swift new file mode 100644 index 0000000..44ba100 --- /dev/null +++ b/Pods/Alamofire/Source/ServerTrustPolicy.swift @@ -0,0 +1,304 @@ +// +// ServerTrustPolicy.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. +public class ServerTrustPolicyManager { + /// The dictionary of policies mapped to a particular host. + public let policies: [String: ServerTrustPolicy] + + /** + Initializes the `ServerTrustPolicyManager` instance with the given policies. + + Since different servers and web services can have different leaf certificates, intermediate and even root + certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This + allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key + pinning for host3 and disabling evaluation for host4. + + - parameter policies: A dictionary of all policies mapped to a particular host. + + - returns: The new `ServerTrustPolicyManager` instance. + */ + public init(policies: [String: ServerTrustPolicy]) { + self.policies = policies + } + + /** + Returns the `ServerTrustPolicy` for the given host if applicable. + + By default, this method will return the policy that perfectly matches the given host. Subclasses could override + this method and implement more complex mapping implementations such as wildcards. + + - parameter host: The host to use when searching for a matching policy. + + - returns: The server trust policy for the given host if found. + */ + public func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? { + return policies[host] + } +} + +// MARK: - + +extension NSURLSession { + private struct AssociatedKeys { + static var ManagerKey = "NSURLSession.ServerTrustPolicyManager" + } + + var serverTrustPolicyManager: ServerTrustPolicyManager? { + get { + return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager + } + set (manager) { + objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } +} + +// MARK: - ServerTrustPolicy + +/** + The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when + connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust + with a given set of criteria to determine whether the server trust is valid and the connection should be made. + + Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) 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 pinning enabled. + + - PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to + validate the host provided by the challenge. Applications are encouraged to always + validate the host in production environments to guarantee the validity of the server's + certificate chain. + + - PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is + considered valid if one of the pinned certificates match one of the server certificates. + By validating both the certificate chain and host, certificate pinning provides a very + secure form of server trust validation mitigating most, if not all, MITM attacks. + Applications are encouraged to always validate the host and require a valid certificate + chain in production environments. + + - PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered + valid if one of the pinned public keys match one of the server certificate public keys. + By validating both the certificate chain and host, public key pinning provides a very + secure form of server trust validation mitigating most, if not all, MITM attacks. + Applications are encouraged to always validate the host and require a valid certificate + chain in production environments. + + - DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. + + - CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust. +*/ +public enum ServerTrustPolicy { + case PerformDefaultEvaluation(validateHost: Bool) + case PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) + case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) + case DisableEvaluation + case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool) + + // MARK: - Bundle Location + + /** + Returns all certificates within the given bundle with a `.cer` file extension. + + - parameter bundle: The bundle to search for all `.cer` files. + + - returns: All certificates within the given bundle. + */ + public static func certificatesInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecCertificate] { + var certificates: [SecCertificate] = [] + + let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in + bundle.pathsForResourcesOfType(fileExtension, inDirectory: nil) + }.flatten()) + + for path in paths { + if let + certificateData = NSData(contentsOfFile: path), + certificate = SecCertificateCreateWithData(nil, certificateData) + { + certificates.append(certificate) + } + } + + return certificates + } + + /** + Returns all public keys within the given bundle with a `.cer` file extension. + + - parameter bundle: The bundle to search for all `*.cer` files. + + - returns: All public keys within the given bundle. + */ + public static func publicKeysInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for certificate in certificatesInBundle(bundle) { + if let publicKey = publicKeyForCertificate(certificate) { + publicKeys.append(publicKey) + } + } + + return publicKeys + } + + // MARK: - Evaluation + + /** + Evaluates whether the server trust is valid for the given host. + + - parameter serverTrust: The server trust to evaluate. + - parameter host: The host of the challenge protection space. + + - returns: Whether the server trust is valid. + */ + public func evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool { + var serverTrustIsValid = false + + switch self { + case let .PerformDefaultEvaluation(validateHost): + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, [policy]) + + serverTrustIsValid = trustIsValid(serverTrust) + case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost): + if validateCertificateChain { + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, [policy]) + + SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates) + SecTrustSetAnchorCertificatesOnly(serverTrust, true) + + serverTrustIsValid = trustIsValid(serverTrust) + } else { + let serverCertificatesDataArray = certificateDataForTrust(serverTrust) + let pinnedCertificatesDataArray = certificateDataForCertificates(pinnedCertificates) + + outerLoop: for serverCertificateData in serverCertificatesDataArray { + for pinnedCertificateData in pinnedCertificatesDataArray { + if serverCertificateData.isEqualToData(pinnedCertificateData) { + serverTrustIsValid = true + break outerLoop + } + } + } + } + case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): + var certificateChainEvaluationPassed = true + + if validateCertificateChain { + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, [policy]) + + certificateChainEvaluationPassed = trustIsValid(serverTrust) + } + + if certificateChainEvaluationPassed { + outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] { + for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { + if serverPublicKey.isEqual(pinnedPublicKey) { + serverTrustIsValid = true + break outerLoop + } + } + } + } + case .DisableEvaluation: + serverTrustIsValid = true + case let .CustomEvaluation(closure): + serverTrustIsValid = closure(serverTrust: serverTrust, host: host) + } + + return serverTrustIsValid + } + + // MARK: - Private - Trust Validation + + private func trustIsValid(trust: SecTrust) -> Bool { + var isValid = false + + var result = SecTrustResultType(kSecTrustResultInvalid) + let status = SecTrustEvaluate(trust, &result) + + if status == errSecSuccess { + let unspecified = SecTrustResultType(kSecTrustResultUnspecified) + let proceed = SecTrustResultType(kSecTrustResultProceed) + + isValid = result == unspecified || result == proceed + } + + return isValid + } + + // MARK: - Private - Certificate Data + + private func certificateDataForTrust(trust: SecTrust) -> [NSData] { + var certificates: [SecCertificate] = [] + + for index in 0.. [NSData] { + return certificates.map { SecCertificateCopyData($0) as NSData } + } + + // MARK: - Private - Public Key Extraction + + private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for index in 0.. SecKey? { + var publicKey: SecKey? + + let policy = SecPolicyCreateBasicX509() + var trust: SecTrust? + let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) + + if let trust = trust where trustCreationStatus == errSecSuccess { + publicKey = SecTrustCopyPublicKey(trust) + } + + return publicKey + } +} diff --git a/Pods/Alamofire/Source/Stream.swift b/Pods/Alamofire/Source/Stream.swift new file mode 100644 index 0000000..07ebe33 --- /dev/null +++ b/Pods/Alamofire/Source/Stream.swift @@ -0,0 +1,182 @@ +// +// Stream.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +#if !os(watchOS) + +@available(iOS 9.0, OSX 10.11, tvOS 9.0, *) +extension Manager { + private enum Streamable { + case Stream(String, Int) + case NetService(NSNetService) + } + + private func stream(streamable: Streamable) -> Request { + var streamTask: NSURLSessionStreamTask! + + switch streamable { + case .Stream(let hostName, let port): + dispatch_sync(queue) { + streamTask = self.session.streamTaskWithHostName(hostName, port: port) + } + case .NetService(let netService): + dispatch_sync(queue) { + streamTask = self.session.streamTaskWithNetService(netService) + } + } + + let request = Request(session: session, task: streamTask) + + delegate[request.delegate.task] = request.delegate + + if startRequestsImmediately { + request.resume() + } + + return request + } + + /** + Creates a request for bidirectional streaming with the given hostname and port. + + - parameter hostName: The hostname of the server to connect to. + - parameter port: The port of the server to connect to. + + :returns: The created stream request. + */ + public func stream(hostName hostName: String, port: Int) -> Request { + return stream(.Stream(hostName, port)) + } + + /** + Creates a request for bidirectional streaming with the given `NSNetService`. + + - parameter netService: The net service used to identify the endpoint. + + - returns: The created stream request. + */ + public func stream(netService netService: NSNetService) -> Request { + return stream(.NetService(netService)) + } +} + +// MARK: - + +@available(iOS 9.0, OSX 10.11, tvOS 9.0, *) +extension Manager.SessionDelegate: NSURLSessionStreamDelegate { + + // MARK: Override Closures + + /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:readClosedForStreamTask:`. + public var streamTaskReadClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { + get { + return _streamTaskReadClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void + } + set { + _streamTaskReadClosed = newValue + } + } + + /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:writeClosedForStreamTask:`. + public var streamTaskWriteClosed: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { + get { + return _streamTaskWriteClosed as? (NSURLSession, NSURLSessionStreamTask) -> Void + } + set { + _streamTaskWriteClosed = newValue + } + } + + /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:betterRouteDiscoveredForStreamTask:`. + public var streamTaskBetterRouteDiscovered: ((NSURLSession, NSURLSessionStreamTask) -> Void)? { + get { + return _streamTaskBetterRouteDiscovered as? (NSURLSession, NSURLSessionStreamTask) -> Void + } + set { + _streamTaskBetterRouteDiscovered = newValue + } + } + + /// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:streamTask:didBecomeInputStream:outputStream:`. + public var streamTaskDidBecomeInputStream: ((NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void)? { + get { + return _streamTaskDidBecomeInputStream as? (NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> Void + } + set { + _streamTaskDidBecomeInputStream = newValue + } + } + + // MARK: Delegate Methods + + /** + Tells the delegate that the read side of the connection has been closed. + + - parameter session: The session. + - parameter streamTask: The stream task. + */ + public func URLSession(session: NSURLSession, readClosedForStreamTask streamTask: NSURLSessionStreamTask) { + streamTaskReadClosed?(session, streamTask) + } + + /** + Tells the delegate that the write side of the connection has been closed. + + - parameter session: The session. + - parameter streamTask: The stream task. + */ + public func URLSession(session: NSURLSession, writeClosedForStreamTask streamTask: NSURLSessionStreamTask) { + streamTaskWriteClosed?(session, streamTask) + } + + /** + Tells the delegate that the system has determined that a better route to the host is available. + + - parameter session: The session. + - parameter streamTask: The stream task. + */ + public func URLSession(session: NSURLSession, betterRouteDiscoveredForStreamTask streamTask: NSURLSessionStreamTask) { + streamTaskBetterRouteDiscovered?(session, streamTask) + } + + /** + Tells the delegate that the stream task has been completed and provides the unopened stream objects. + + - parameter session: The session. + - parameter streamTask: The stream task. + - parameter inputStream: The new input stream. + - parameter outputStream: The new output stream. + */ + public func URLSession( + session: NSURLSession, + streamTask: NSURLSessionStreamTask, + didBecomeInputStream inputStream: NSInputStream, + outputStream: NSOutputStream) + { + streamTaskDidBecomeInputStream?(session, streamTask, inputStream, outputStream) + } +} + +#endif diff --git a/Pods/Alamofire/Source/Timeline.swift b/Pods/Alamofire/Source/Timeline.swift new file mode 100644 index 0000000..9593682 --- /dev/null +++ b/Pods/Alamofire/Source/Timeline.swift @@ -0,0 +1,138 @@ +// +// Timeline.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. +public struct Timeline { + /// The time the request was initialized. + public let requestStartTime: CFAbsoluteTime + + /// The time the first bytes were received from or sent to the server. + public let initialResponseTime: CFAbsoluteTime + + /// The time when the request was completed. + public let requestCompletedTime: CFAbsoluteTime + + /// The time when the response serialization was completed. + public let serializationCompletedTime: CFAbsoluteTime + + /// The time interval in seconds from the time the request started to the initial response from the server. + public let latency: NSTimeInterval + + /// The time interval in seconds from the time the request started to the time the request completed. + public let requestDuration: NSTimeInterval + + /// The time interval in seconds from the time the request completed to the time response serialization completed. + public let serializationDuration: NSTimeInterval + + /// The time interval in seconds from the time the request started to the time response serialization completed. + public let totalDuration: NSTimeInterval + + /** + Creates a new `Timeline` instance with the specified request times. + + - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. + - parameter initialResponseTime: The time the first bytes were received from or sent to the server. + Defaults to `0.0`. + - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. + - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults + to `0.0`. + + - returns: The new `Timeline` instance. + */ + public init( + requestStartTime: CFAbsoluteTime = 0.0, + initialResponseTime: CFAbsoluteTime = 0.0, + requestCompletedTime: CFAbsoluteTime = 0.0, + serializationCompletedTime: CFAbsoluteTime = 0.0) + { + self.requestStartTime = requestStartTime + self.initialResponseTime = initialResponseTime + self.requestCompletedTime = requestCompletedTime + self.serializationCompletedTime = serializationCompletedTime + + self.latency = initialResponseTime - requestStartTime + self.requestDuration = requestCompletedTime - requestStartTime + self.serializationDuration = serializationCompletedTime - requestCompletedTime + self.totalDuration = serializationCompletedTime - requestStartTime + } +} + +// MARK: - CustomStringConvertible + +extension Timeline: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes the latency, the request + /// duration and the total duration. + public var description: String { + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joinWithSeparator(", ") + " }" + } +} + +// MARK: - CustomDebugStringConvertible + +extension Timeline: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes the request start time, the + /// initial response time, the request completed time, the serialization completed time, the latency, the request + /// duration and the total duration. + public var debugDescription: String { + let requestStartTime = String(format: "%.3f", self.requestStartTime) + let initialResponseTime = String(format: "%.3f", self.initialResponseTime) + let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) + let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Request Start Time\": " + requestStartTime, + "\"Initial Response Time\": " + initialResponseTime, + "\"Request Completed Time\": " + requestCompletedTime, + "\"Serialization Completed Time\": " + serializationCompletedTime, + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joinWithSeparator(", ") + " }" + } +} diff --git a/Pods/Alamofire/Source/Upload.swift b/Pods/Alamofire/Source/Upload.swift new file mode 100644 index 0000000..7b31ba5 --- /dev/null +++ b/Pods/Alamofire/Source/Upload.swift @@ -0,0 +1,376 @@ +// +// Upload.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Manager { + private enum Uploadable { + case Data(NSURLRequest, NSData) + case File(NSURLRequest, NSURL) + case Stream(NSURLRequest, NSInputStream) + } + + private func upload(uploadable: Uploadable) -> Request { + var uploadTask: NSURLSessionUploadTask! + var HTTPBodyStream: NSInputStream? + + switch uploadable { + case .Data(let request, let data): + dispatch_sync(queue) { + uploadTask = self.session.uploadTaskWithRequest(request, fromData: data) + } + case .File(let request, let fileURL): + dispatch_sync(queue) { + uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL) + } + case .Stream(let request, let stream): + dispatch_sync(queue) { + uploadTask = self.session.uploadTaskWithStreamedRequest(request) + } + + HTTPBodyStream = stream + } + + let request = Request(session: session, task: uploadTask) + + if HTTPBodyStream != nil { + request.delegate.taskNeedNewBodyStream = { _, _ in + return HTTPBodyStream + } + } + + delegate[request.delegate.task] = request.delegate + + if startRequestsImmediately { + request.resume() + } + + return request + } + + // MARK: File + + /** + Creates a request for uploading a file to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request + - parameter file: The file to upload + + - returns: The created upload request. + */ + public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { + return upload(.File(URLRequest.URLRequest, file)) + } + + /** + Creates a request for uploading a file to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter file: The file to upload + + - returns: The created upload request. + */ + public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + file: NSURL) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + return upload(mutableURLRequest, file: file) + } + + // MARK: Data + + /** + Creates a request for uploading data to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request. + - parameter data: The data to upload. + + - returns: The created upload request. + */ + public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { + return upload(.Data(URLRequest.URLRequest, data)) + } + + /** + Creates a request for uploading data to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter data: The data to upload + + - returns: The created upload request. + */ + public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + data: NSData) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + + return upload(mutableURLRequest, data: data) + } + + // MARK: Stream + + /** + Creates a request for uploading a stream to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request. + - parameter stream: The stream to upload. + + - returns: The created upload request. + */ + public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { + return upload(.Stream(URLRequest.URLRequest, stream)) + } + + /** + Creates a request for uploading a stream to the specified URL request. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter stream: The stream to upload. + + - returns: The created upload request. + */ + public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + stream: NSInputStream) + -> Request + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + + return upload(mutableURLRequest, stream: stream) + } + + // MARK: MultipartFormData + + /// Default memory threshold used when encoding `MultipartFormData`. + public static let MultipartFormDataEncodingMemoryThreshold: UInt64 = 10 * 1024 * 1024 + + /** + Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as + associated values. + + - Success: Represents a successful `MultipartFormData` encoding and contains the new `Request` along with + streaming information. + - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding + error. + */ + public enum MultipartFormDataEncodingResult { + case Success(request: Request, streamingFromDisk: Bool, streamFileURL: NSURL?) + case Failure(ErrorType) + } + + /** + Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. + + It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative + payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + used for larger payloads such as video content. + + The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + technique was used. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter method: The HTTP method. + - parameter URLString: The URL string. + - parameter headers: The HTTP headers. `nil` by default. + - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + `MultipartFormDataEncodingMemoryThreshold` by default. + - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + */ + public func upload( + method: Method, + _ URLString: URLStringConvertible, + headers: [String: String]? = nil, + multipartFormData: MultipartFormData -> Void, + encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: (MultipartFormDataEncodingResult -> Void)?) + { + let mutableURLRequest = URLRequest(method, URLString, headers: headers) + + return upload( + mutableURLRequest, + multipartFormData: multipartFormData, + encodingMemoryThreshold: encodingMemoryThreshold, + encodingCompletion: encodingCompletion + ) + } + + /** + Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. + + It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative + payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + used for larger payloads such as video content. + + The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + technique was used. + + If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + + - parameter URLRequest: The URL request. + - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + `MultipartFormDataEncodingMemoryThreshold` by default. + - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + */ + public func upload( + URLRequest: URLRequestConvertible, + multipartFormData: MultipartFormData -> Void, + encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: (MultipartFormDataEncodingResult -> Void)?) + { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { + let formData = MultipartFormData() + multipartFormData(formData) + + let URLRequestWithContentType = URLRequest.URLRequest + URLRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") + + let isBackgroundSession = self.session.configuration.identifier != nil + + if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { + do { + let data = try formData.encode() + let encodingResult = MultipartFormDataEncodingResult.Success( + request: self.upload(URLRequestWithContentType, data: data), + streamingFromDisk: false, + streamFileURL: nil + ) + + dispatch_async(dispatch_get_main_queue()) { + encodingCompletion?(encodingResult) + } + } catch { + dispatch_async(dispatch_get_main_queue()) { + encodingCompletion?(.Failure(error as NSError)) + } + } + } else { + let fileManager = NSFileManager.defaultManager() + let tempDirectoryURL = NSURL(fileURLWithPath: NSTemporaryDirectory()) + let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("com.alamofire.manager/multipart.form.data") + let fileName = NSUUID().UUIDString + let fileURL = directoryURL.URLByAppendingPathComponent(fileName) + + do { + try fileManager.createDirectoryAtURL(directoryURL, withIntermediateDirectories: true, attributes: nil) + try formData.writeEncodedDataToDisk(fileURL) + + dispatch_async(dispatch_get_main_queue()) { + let encodingResult = MultipartFormDataEncodingResult.Success( + request: self.upload(URLRequestWithContentType, file: fileURL), + streamingFromDisk: true, + streamFileURL: fileURL + ) + encodingCompletion?(encodingResult) + } + } catch { + dispatch_async(dispatch_get_main_queue()) { + encodingCompletion?(.Failure(error as NSError)) + } + } + } + } + } +} + +// MARK: - + +extension Request { + + // MARK: - UploadTaskDelegate + + class UploadTaskDelegate: DataTaskDelegate { + var uploadTask: NSURLSessionUploadTask? { return task as? NSURLSessionUploadTask } + var uploadProgress: ((Int64, Int64, Int64) -> Void)! + + // MARK: - NSURLSessionTaskDelegate + + // MARK: Override Closures + + var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? + + // MARK: Delegate Methods + + func URLSession( + session: NSURLSession, + task: NSURLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else { + progress.totalUnitCount = totalBytesExpectedToSend + progress.completedUnitCount = totalBytesSent + + uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend) + } + } + } +} diff --git a/Pods/Alamofire/Source/Validation.swift b/Pods/Alamofire/Source/Validation.swift new file mode 100644 index 0000000..e90db2d --- /dev/null +++ b/Pods/Alamofire/Source/Validation.swift @@ -0,0 +1,214 @@ +// +// Validation.swift +// +// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +import Foundation + +extension Request { + + /** + Used to represent whether validation was successful or encountered an error resulting in a failure. + + - Success: The validation was successful. + - Failure: The validation failed encountering the provided error. + */ + public enum ValidationResult { + case Success + case Failure(NSError) + } + + /** + A closure used to validate a request that takes a URL request and URL response, and returns whether the + request was valid. + */ + public typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult + + /** + Validates the request, using the specified closure. + + If validation fails, subsequent calls to response handlers will have an associated error. + + - parameter validation: A closure to validate the request. + + - returns: The request. + */ + public func validate(validation: Validation) -> Self { + delegate.queue.addOperationWithBlock { + if let + response = self.response where self.delegate.error == nil, + case let .Failure(error) = validation(self.request, response) + { + self.delegate.error = error + } + } + + return self + } + + // MARK: - Status Code + + /** + Validates that the response has a status code in the specified range. + + If validation fails, subsequent calls to response handlers will have an associated error. + + - parameter range: The range of acceptable status codes. + + - returns: The request. + */ + public func validate(statusCode acceptableStatusCode: S) -> Self { + return validate { _, response in + if acceptableStatusCode.contains(response.statusCode) { + return .Success + } else { + let failureReason = "Response status code was unacceptable: \(response.statusCode)" + + let error = NSError( + domain: Error.Domain, + code: Error.Code.StatusCodeValidationFailed.rawValue, + userInfo: [ + NSLocalizedFailureReasonErrorKey: failureReason, + Error.UserInfoKeys.StatusCode: response.statusCode + ] + ) + + return .Failure(error) + } + } + } + + // MARK: - Content-Type + + private struct MIMEType { + let type: String + let subtype: String + + init?(_ string: String) { + let components: [String] = { + let stripped = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) + let split = stripped.substringToIndex(stripped.rangeOfString(";")?.startIndex ?? stripped.endIndex) + return split.componentsSeparatedByString("/") + }() + + if let + type = components.first, + subtype = components.last + { + self.type = type + self.subtype = subtype + } else { + return nil + } + } + + func matches(MIME: MIMEType) -> Bool { + switch (type, subtype) { + case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"): + return true + default: + return false + } + } + } + + /** + Validates that the response has a content type in the specified array. + + If validation fails, subsequent calls to response handlers will have an associated error. + + - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + + - returns: The request. + */ + public func validate(contentType acceptableContentTypes: S) -> Self { + return validate { _, response in + guard let validData = self.delegate.data where validData.length > 0 else { return .Success } + + if let + responseContentType = response.MIMEType, + responseMIMEType = MIMEType(responseContentType) + { + for contentType in acceptableContentTypes { + if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) { + return .Success + } + } + } else { + for contentType in acceptableContentTypes { + if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" { + return .Success + } + } + } + + let contentType: String + let failureReason: String + + if let responseContentType = response.MIMEType { + contentType = responseContentType + + failureReason = ( + "Response content type \"\(responseContentType)\" does not match any acceptable " + + "content types: \(acceptableContentTypes)" + ) + } else { + contentType = "" + failureReason = "Response content type was missing and acceptable content type does not match \"*/*\"" + } + + let error = NSError( + domain: Error.Domain, + code: Error.Code.ContentTypeValidationFailed.rawValue, + userInfo: [ + NSLocalizedFailureReasonErrorKey: failureReason, + Error.UserInfoKeys.ContentType: contentType + ] + ) + + return .Failure(error) + } + } + + // MARK: - Automatic + + /** + Validates that the response has a status code in the default acceptable range of 200...299, and that the content + type matches any specified in the Accept HTTP header field. + + If validation fails, subsequent calls to response handlers will have an associated error. + + - returns: The request. + */ + public func validate() -> Self { + let acceptableStatusCodes: Range = 200..<300 + let acceptableContentTypes: [String] = { + if let accept = request?.valueForHTTPHeaderField("Accept") { + return accept.componentsSeparatedByString(",") + } + + return ["*/*"] + }() + + return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes) + } +} diff --git a/Pods/Freddy/LICENSE b/Pods/Freddy/LICENSE new file mode 100644 index 0000000..dd38e02 --- /dev/null +++ b/Pods/Freddy/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Big Nerd Ranch Inc + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Pods/Freddy/README.md b/Pods/Freddy/README.md new file mode 100644 index 0000000..707353f --- /dev/null +++ b/Pods/Freddy/README.md @@ -0,0 +1,284 @@ +## Why Freddy? + +Parsing JSON elegantly and safely can be hard, but Freddy is here to help. Freddy is a reusable framework for parsing JSON in Swift. It has three principal benefits. + +First, Freddy provides a type safe solution to parsing JSON in Swift. This means that the compiler helps you work with sending and receiving JSON in a way that helps to prevent runtime crashes. + +Second, Freddy provides an idiomatic solution to JSON parsing that takes advantage of Swift's generics, enumerations, and functional features. This is all provided without the pain of having to memorize our documentation to understand our magical custom operators. Freddy does not have any of those. If you feel comfortable writing Swift (using extensions, protocols, initializers, etc.), then you will not only understand how Freddy is organized, but you will also feel comfortable using Freddy. + +Third, Freddy provides great error information for mistakes that commonly occur while parsing JSON. If you subscript the JSON object with a key that is not present, you get an informative error. If your desired index is out of bounds, you get an informative error. If you try to convert a JSON value to the wrong type, you get a good error here too. + +So, Freddy vs. JSON, who wins? We think it is Freddy. + +## Usage + +This section describes Freddy's basic usage. You can find more examples on parsing data, dealing with errors, serializing `JSON` instances into `NSData`, and more in the [Wiki](https://github.com/bignerdranch/Freddy/wiki). You can read the [documentation to see the full API](http://bignerdranch.github.io/Freddy/index.html). + +### Deserialization: Parsing Raw Data +#### Basic Usage +Consider some example JSON data: + +```json +{ + "success": true, + "people": [ + { + "name": "Matt Mathias", + "age": 32, + "spouse": true + }, + { + "name": "Sergeant Pepper", + "age": 25, + "spouse": false + } + ], + "jobs": [ + "teacher", + "judge" + ], + "states": { + "Georgia": [ + 30301, + 30302, + 30303 + ], + "Wisconsin": [ + 53000, + 53001 + ] + } +} +``` +Here is a quick example on how to parse this data using Freddy: + +```swift +let data = getSomeData() +do { + let json = try JSON(data: data) + let success = try json.bool("success") + // do something with `success` +} catch { + // do something with the error +} +``` + +After we load in the data, we create an instance of `JSON`, the workhorse of this framework. This allows us to access the values from the JSON data. We `try` because the `data` may be malformed and the parsing could generate an error. Next, we access the `"success"` key by calling the `bool(_:)` method on `JSON`. We `try` here as well because accessing the `json` for the key `"success"` could fail - e.g., if we had passed an unknown key. This method takes two parameters, both of which are used to define a path into the `JSON` instance to find a Boolean value of interest. If a `Bool` is found at the path described by `"success"`, then `bool(_:)` returns a `Bool`. If the path does not lead to a `Bool`, then an appropriate error is thrown. + +#### Use Paths to Access Nested Data with Subscripting +With Freddy, it is possible to use a path to access elements deeper in the json structure. For example: + +```swift +let data = getSomeData() +do { + let json = try JSON(data: data) + let georgiaZipCodes = try json.array("states","Georgia") + let firstPersonName = try json.string("people",0,"name") +} catch { + // do something with the error +} +``` + +In the code `json.array("states","Georgia")`, the keys `"states"` and `"Georgia"` describe a path to the Georgia zip codes within `json`. +`Freddy`'s parlance calls this process "subscripting" the JSON. +What is typed between the parentheses of, for example, `array(_:)` is a comma-separated list of keys and indices that describe the path to a value of interest. + +There can be any number of subscripts, and each subscript can be either a `String` indicating a named element in the JSON, or an `Int` that represents an element in an array. If there is something invalid in the path such as an index that doesn't exist in the JSON, an error will be thrown. + +[More on Subscripting](https://github.com/bignerdranch/Freddy/wiki/Subscripting) + +#### JSONDecodable: Deserializing Models Directly +Now, let's look an example that parses the data into a model class: + +```swift +let data = getSomeData() +do { + let json = try JSON(data: data) + let people = try json.array("people").map(Person.init) + // do something with `people` +} catch { + // do something with the error +} +``` + +Here, we are instead loading the values from the key `"people"` as an array using the method `array(_:)`. This method works a lot like the `bool(_:)` method you saw above. It uses the path provided to the method to find an array. If the path is good, the method will return an `Array` of `JSON`. If the path is bad, then an appropriate error is thrown. + +We can then call `map` on that `JSON` array. Since the `Person` type conforms to `JSONDecodable`, we can pass in the `Person` type's initializer. This call applies an initializer that takes an instance of `JSON` to each element in the array, producing an array of `Person` instances. + +Here is what `JSONDecodable` looks like: + +```swift +public protocol JSONDecodable { + init(json: JSON) throws +} +``` + +It is fairly simple protocol. All it requires is that conforming types implement an initializer that takes an instance of `JSON` as its sole parameter. + +To tie it all together, here is what the `Person` type looks like: + +```swift +public struct Person { + public let name: String + public let age: Int + public let spouse: Bool +} + +extension Person: JSONDecodable { + public init(json value: JSON) throws { + name = try value.string("name") + age = try value.int("age") + spouse = try value.bool("spouse") + } +} +``` + +`Person` just has a few properties. It conforms to `JSONDecodable` via an extension. In the extension, we implement a `throws`ing initializer that takes an instance of `JSON` as its sole parameter. In the implementation, we `try` three functions: 1) `string(_:)`, 2) `int(_:)`, and 3) `bool(_:)`. Each of these works as you have seen before. The methods take in a path, which is used to find a value of a specific type within the `JSON` instance passed to the initializer. Since these paths could be bad, or the requested type may not match what is actually inside of the `JSON`, these methods may potentially throw an error. + + +### Serialization +Freddy's serialization support centers around the `JSON.serialize()` method. + +#### Basic Usage +The `JSON` enumeration supports conversion to `NSData` directly: + +```swift +let someJSON: JSON = … +let data: NSData = try someJSON.serialize() +``` + +#### JSONEncodable: Serializing Other Objects +Most of your objects aren't `Freddy.JSON` objects, though. +You can serialize them to `NSData` by first converting them to a +`Freddy.JSON` via `JSONEncodable.toJSON()`, the sole method of the +`JSONEncodable` protocol, and then using `serialize()` to convert +the `Freddy.JSON` to `NSData`: + +```swift +let myObject: JSONEncodable = … + +// Object -> JSON -> NSData: +let objectAsJSON: JSON = myObject.toJSON() +let data: NSData = try objectAsJSON.serialize() + +// More concisely: +let dataOneLiner = try object.toJSON().serialize() +``` + +Freddy provides definitions for common Swift datatypes already. +To make your own datatypes serializable, conform them to `JSONEncodable` +and implement that protocol's `toJSON()` method: + +```swift +extension Person: JSONEncodable { + public func toJSON() -> JSON { + return .Dictionary([ + "name": .String(name), + "age": .Int(age), + "spouse": .Bool(spouse)]) + } +} +``` + + + +## Getting Started + +Freddy requires iOS 7.0, Mac OS X 10.9, watchOS 2.0, or tvOS 9.0. Linux is not yet supported. + +Dynamic frameworks on iOS require a minimum deployment target of iOS 8.0. For a project targeting iOS 7, see ["Submodules"](https://github.com/bignerdranch/Freddy#submodules). + +You have a few different options to install Freddy. + +### [Carthage](https://github.com/Carthage/Carthage) + +Add us to your `Cartfile`: + +``` +github "bignerdranch/Freddy" ~> 2.1 +``` + +After running `carthage bootstrap`, add `Freddy.framework` to the "Linked Frameworks and Libraries" panel of your application target. [Read more](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application). + +### [CocoaPods](https://cocoapods.org) + +Add us to your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '8.0' +use_frameworks! + +pod 'Freddy' +``` + +Then run `pod install`. + +### Submodules + +1. `git submodule add https://github.com/bignerdranch/Freddy.git Vendor/Freddy` +2. Drag `Freddy.xcodeproj` into your Xcode project. +3. Add `Freddy.framework` to the "Linked Frameworks and Libraries" panel of your application target. + +[Carthage](https://github.com/bignerdranch/Freddy#carthage) can be used to check out dependencies and maintain Git submodule state as well. + +### Swift Package Manager + +Add us to your `Package.swift`: + +``` +import PackageDescription + +let package = Package( + name: "My Nerdy App", + dependencies: [ + .Package(url: "https://github.com/bignerdranch/Freddy.git", majorVersion: 2), + ] +) +``` + +### iOS 7 + +If you would like to use Freddy with iOS 7, then you will need to copy Freddy's source files into your project. +Embedded frameworks are only supported in iOS 8+. +You can add Freddy as a submodule (see above), and then make sure to add the source files to your project. + +## Setting Breakpoint Errors + +It can be helpful to set breakpoints for errors when you start working with a new set of JSON. +This allows you to explore the structure of the JSON when you break. +In particular, you will likely want to set a breakpoint for `Freddy`'s `JSON.Error` so that you can inspect what went wrong. + +Here is how you can set this sort of breakpoint: + +1) Go to the Breakpoint navigator + +2) Click the "+" button in the bottom left corner + +![Breakpoint navigator](https://github.com/bignerdranch/Freddy/raw/master/README_Images/projectNav_addBreakpoint.png) + +3) Select "Add Swift Error Breakpoint" + +![Add Error Breakpoint](https://github.com/bignerdranch/Freddy/raw/master/README_Images/addErrorBreakpoint.png) + +Now you have a breakpoint that will only trigger when a Swift error is generated. +But your program will break whenever *any* Swift error is thrown. +What if you only want to break for `Freddy`'s `JSON.Error` error? + +You can edit the breakpoint to add a filter: + +1) Right-click your new error breakpoint + +2) Select Edit Breakpoint... + +![Edit Breakpoint](https://github.com/bignerdranch/Freddy/raw/master/README_Images/editBreakpoint.png) + +3) A window will appear with a text box for "Type" + +4) Enter `JSON.Error` + +![Error Type](https://github.com/bignerdranch/Freddy/raw/master/README_Images/addType.png) + +And that is pretty much it! You now have an error breakpoint that will only trigger when errors of type `JSON.Error` are thrown. +Take a look at the framework's tests for further examples of usage. +The Wiki also have a lot of very useful information. diff --git a/Pods/Freddy/Sources/Freddy.h b/Pods/Freddy/Sources/Freddy.h new file mode 100644 index 0000000..8e35cc2 --- /dev/null +++ b/Pods/Freddy/Sources/Freddy.h @@ -0,0 +1,13 @@ +// +// Freddy.h +// Freddy +// +// Created by Matthew D. Mathias on 3/25/15. +// Copyright © 2015 Big Nerd Ranch. Licensed under MIT. +// + +//! Project version number for Freddy. +extern double FreddyVersionNumber; + +//! Project version string for Freddy. +extern const unsigned char FreddyVersionString[]; diff --git a/Pods/Freddy/Sources/JSON.swift b/Pods/Freddy/Sources/JSON.swift new file mode 100644 index 0000000..c8adae8 --- /dev/null +++ b/Pods/Freddy/Sources/JSON.swift @@ -0,0 +1,95 @@ +// +// JSON.swift +// Freddy +// +// Created by Matthew D. Mathias on 3/17/15. +// Copyright © 2015 Big Nerd Ranch. Licensed under MIT. +// + +/// An enum to describe the structure of JSON. +public enum JSON { + /// A case for denoting an array with an associated value of `[JSON]` + case Array([JSON]) + /// A case for denoting a dictionary with an associated value of `[Swift.String: JSON]` + case Dictionary([Swift.String: JSON]) + /// A case for denoting a double with an associated value of `Swift.Double`. + case Double(Swift.Double) + /// A case for denoting an integer with an associated value of `Swift.Int`. + case Int(Swift.Int) + /// A case for denoting a string with an associated value of `Swift.String`. + case String(Swift.String) + /// A case for denoting a boolean with an associated value of `Swift.Bool`. + case Bool(Swift.Bool) + /// A case for denoting null. + case Null +} + +// MARK: - Errors + +extension JSON { + + /// An enum to encapsulate errors that may arise in working with `JSON`. + public enum Error: ErrorType { + /// The `index` is out of bounds for a JSON array + case IndexOutOfBounds(index: Swift.Int) + + /// The `key` was not found in the JSON dictionary + case KeyNotFound(key: Swift.String) + + /// The JSON is not subscriptable with `type` + case UnexpectedSubscript(type: JSONPathType.Type) + + /// Unexpected JSON `value` was found that is not convertible `to` type + case ValueNotConvertible(value: JSON, to: Any.Type) + } + +} + +// MARK: - Test Equality + +/// Return `true` if `lhs` is equal to `rhs`. +public func ==(lhs: JSON, rhs: JSON) -> Bool { + switch (lhs, rhs) { + case (.Array(let arrL), .Array(let arrR)): + return arrL == arrR + case (.Dictionary(let dictL), .Dictionary(let dictR)): + return dictL == dictR + case (.String(let strL), .String(let strR)): + return strL == strR + case (.Double(let dubL), .Double(let dubR)): + return dubL == dubR + case (.Double(let dubL), .Int(let intR)): + return dubL == Double(intR) + case (.Int(let intL), .Int(let intR)): + return intL == intR + case (.Int(let intL), .Double(let dubR)): + return Double(intL) == dubR + case (.Bool(let bL), .Bool(let bR)): + return bL == bR + case (.Null, .Null): + return true + default: + return false + } +} + +extension JSON: Equatable {} + +// MARK: - Printing + +extension JSON: CustomStringConvertible { + + /// A textual representation of `self`. + public var description: Swift.String { + switch self { + case .Array(let arr): return Swift.String(arr) + case .Dictionary(let dict): return Swift.String(dict) + case .String(let string): return string + case .Double(let double): return Swift.String(double) + case .Int(let int): return Swift.String(int) + case .Bool(let bool): return Swift.String(bool) + case .Null: return "null" + } + } + +} diff --git a/Pods/Freddy/Sources/JSONDecodable.swift b/Pods/Freddy/Sources/JSONDecodable.swift new file mode 100644 index 0000000..ff508c9 --- /dev/null +++ b/Pods/Freddy/Sources/JSONDecodable.swift @@ -0,0 +1,151 @@ +// +// JSONDecodable.swift +// Freddy +// +// Created by Matthew D. Mathias on 3/24/15. +// Copyright © 2015 Big Nerd Ranch. Licensed under MIT. +// + +/// A protocol to provide functionality for creating a model object with a `JSON` +/// value. +public protocol JSONDecodable { + + /// Creates an instance of the model with a `JSON` instance. + /// - parameter json: An instance of a `JSON` value from which to + /// construct an instance of the implementing type. + /// - throws: Any `JSON.Error` for errors derived from inspecting the + /// `JSON` value, or any other error involved in decoding. + init(json: JSON) throws + +} + +extension Double: JSONDecodable { + + /// An initializer to create an instance of `Double` from a `JSON` value. + /// - parameter json: An instance of `JSON`. + /// - throws: The initializer will throw an instance of `JSON.Error` if + /// an instance of `Double` cannot be created from the `JSON` value that was + /// passed to this initializer. + public init(json: JSON) throws { + switch json { + case let .Double(double): + self = double + case let .Int(int): + self = Swift.Double(int) + default: + throw JSON.Error.ValueNotConvertible(value: json, to: Swift.Double) + } + } + +} + +extension Int: JSONDecodable { + + /// An initializer to create an instance of `Int` from a `JSON` value. + /// - parameter json: An instance of `JSON`. + /// - throws: The initializer will throw an instance of `JSON.Error` if + /// an instance of `Int` cannot be created from the `JSON` value that was + /// passed to this initializer. + public init(json: JSON) throws { + switch json { + case let .Double(double) where double <= Double(Swift.Int.max): + self = Swift.Int(double) + case let .Int(int): + self = int + default: + throw JSON.Error.ValueNotConvertible(value: json, to: Swift.Int) + } + } + +} + +extension String: JSONDecodable { + + /// An initializer to create an instance of `String` from a `JSON` value. + /// - parameter json: An instance of `JSON`. + /// - throws: The initializer will throw an instance of `JSON.Error` if + /// an instance of `String` cannot be created from the `JSON` value that was + /// passed to this initializer. + public init(json: JSON) throws { + guard case let .String(string) = json else { + throw JSON.Error.ValueNotConvertible(value: json, to: Swift.String) + } + self = string + } + +} + +extension Bool: JSONDecodable { + + /// An initializer to create an instance of `Bool` from a `JSON` value. + /// - parameter json: An instance of `JSON`. + /// - throws: The initializer will throw an instance of `JSON.Error` if + /// an instance of `Bool` cannot be created from the `JSON` value that was + /// passed to this initializer. + public init(json: JSON) throws { + guard case let .Bool(bool) = json else { + throw JSON.Error.ValueNotConvertible(value: json, to: Swift.Bool) + } + self = bool + } + +} + +extension RawRepresentable where RawValue: JSONDecodable { + + /// An initializer to create an instance of `RawRepresentable` from a `JSON` value. + /// - parameter json: An instance of `JSON`. + /// - throws: The initializer will throw an instance of `JSON.Error` if + /// an instance of `RawRepresentable` cannot be created from the `JSON` value that was + /// passed to this initializer. + public init(json: JSON) throws { + let raw = try json.decode(type: RawValue.self) + guard let value = Self(rawValue: raw) else { + throw JSON.Error.ValueNotConvertible(value: json, to: Self.self) + } + self = value + } +} + +internal extension JSON { + + /// Retrieves a `[JSON]` from the JSON. + /// - returns: An `Array` of `JSON` elements + /// - throws: Any of the `JSON.Error` cases thrown by `decode(type:)`. + /// - seealso: `JSON.decode(_:type:)` + static func getArray(json: JSON) throws -> [JSON] { + // Ideally should be expressed as a conditional protocol implementation on Swift.Array. + guard case let .Array(array) = json else { + throw Error.ValueNotConvertible(value: json, to: Swift.Array) + } + return array + } + + /// Retrieves a `[String: JSON]` from the JSON. + /// - returns: An `Dictionary` of `String` mapping to `JSON` elements + /// - throws: Any of the `JSON.Error` cases thrown by `decode(type:)`. + /// - seealso: `JSON.decode(_:type:)` + static func getDictionary(json: JSON) throws -> [Swift.String: JSON] { + // Ideally should be expressed as a conditional protocol implementation on Swift.Dictionary. + guard case let .Dictionary(dictionary) = json else { + throw Error.ValueNotConvertible(value: json, to: Swift.Dictionary) + } + return dictionary + } + + /// Attempts to decode many values from a descendant JSON array at a path + /// into JSON. + /// - parameter type: If the context this method is called from does not + /// make the return type clear, pass a type implementing `JSONDecodable` + /// to disambiguate the type to decode with. + /// - returns: An `Array` of decoded elements + /// - throws: Any of the `JSON.Error` cases thrown by `decode(type:)`, as + /// well as any error that arises from decoding the contained values. + /// - seealso: `JSON.decode(_:type:)` + static func getArrayOf(json: JSON) throws -> [Decoded] { + // Ideally should be expressed as a conditional protocol implementation on Swift.Dictionary. + // This implementation also doesn't do the `type = Type.self` trick. + return try getArray(json).map(Decoded.init) + } + +} diff --git a/Pods/Freddy/Sources/JSONEncodable.swift b/Pods/Freddy/Sources/JSONEncodable.swift new file mode 100644 index 0000000..480c57b --- /dev/null +++ b/Pods/Freddy/Sources/JSONEncodable.swift @@ -0,0 +1,83 @@ +// +// JSONEncodable.swift +// Freddy +// +// Created by Matthew Mathias on 1/4/16. +// Copyright © 2016 Big Nerd Ranch. All rights reserved. +// + +import Foundation + +/// A protocol to facilitate encoding and decoding of `JSON`. +public protocol JSONEncodable { + /// Converts an instance of a conforming type to `JSON`. + /// - returns: An instance of `JSON`. + /// - Note: If conforming to `JSONEncodable` with a custom type of your own, you should return an instance of + /// `JSON.Dictionary`. + func toJSON() -> JSON +} + +extension Array where Element: JSONEncodable { + /// Converts an instance of `Array` whose elements conform to `JSONEncodable` to `JSON`. + /// - returns: An instance of `JSON` where the enum case is `.Array`. + public func toJSON() -> JSON { + let arrayOfJSON = self.map { $0.toJSON() } + return .Array(arrayOfJSON) + } +} + +extension Dictionary where Value: JSONEncodable { + /// Converts an instance of `Dictionary` whose values conform to `JSONEncodable` to `JSON`. The keys in the resulting + /// `JSON.Dictionary` will be of type `String`. + /// - returns: An instance of `JSON` where the enum case is `.Dictionary`. + public func toJSON() -> JSON { + var jsonDictionary = [String: JSON]() + + for (k, v) in self { + let key = String(k) + jsonDictionary[key] = v.toJSON() + } + + return .Dictionary(jsonDictionary) + } +} + +extension Int: JSONEncodable { + /// Converts an instance of a conforming type to `JSON`. + /// - returns: An instance of `JSON` where the enum case is `.Int`. + public func toJSON() -> JSON { + return .Int(self) + } +} + +extension Double: JSONEncodable { + /// Converts an instance of a conforming type to `JSON`. + /// - returns: An instance of `JSON` where the enum case is `.Double`. + public func toJSON() -> JSON { + return .Double(self) + } +} + +extension String: JSONEncodable { + /// Converts an instance of a conforming type to `JSON`. + /// - returns: An instance of `JSON` where the enum case is `.String`. + public func toJSON() -> JSON { + return .String(self) + } +} + +extension Bool: JSONEncodable { + /// Converts an instance of a conforming type to `JSON`. + /// - returns: An instance of `JSON` where the enum case is `.Bool`. + public func toJSON() -> JSON { + return .Bool(self) + } +} + +extension RawRepresentable where RawValue: JSONEncodable { + /// Converts an instance of a conforming type to `JSON`. + /// - returns: An instance of `JSON` where the enum case is whatever the underlying `RawValue` converts to. + public func toJSON() -> JSON { + return rawValue.toJSON() + } +} diff --git a/Pods/Freddy/Sources/JSONEncodingDetector.swift b/Pods/Freddy/Sources/JSONEncodingDetector.swift new file mode 100644 index 0000000..933bc0c --- /dev/null +++ b/Pods/Freddy/Sources/JSONEncodingDetector.swift @@ -0,0 +1,110 @@ +// +// JSONEncodingDetector.swift +// Freddy +// +// Created by Robert Edwards on 1/27/16. +// Copyright © 2016 Big Nerd Ranch. All rights reserved. +// + +/// Struct for attempting to detect the Unicode encoding used with the data supplied to the JSONParser +public struct JSONEncodingDetector { + + //// The Unicode encodings looked for during detection + public enum Encoding { + //// UTF-8 + case UTF8 + //// UTF-16 Little Endian + case UTF16LE + //// UTF-16 Big Endian + case UTF16BE + //// UTF-32 Little Endian + case UTF32LE + //// UTF-32 Big Endian + case UTF32BE + } + + //// The Unicode encodings supported by JSONParser.swift + public static let supportedEncodings: [Encoding] = [.UTF8] + + typealias ByteStreamPrefixInformation = (encoding: Encoding, byteOrderMarkLength: Int) + + //// Attempts to detect the Unicode encoding used for a given set of data. + //// + //// This function initially looks for a Byte Order Mark in the following form: + //// + //// Bytes | Encoding Form + //// --------------|---------------- + //// 00 00 FE FF | UTF-32, big-endian + //// FF FE 00 00 | UTF-32, little-endian + //// FE FF | UTF-16, big-endian + //// FF FE | UTF-16, little-endian + //// EF BB BF | UTF-8 + //// + //// If a BOM is not found then we detect using the following approach described in + //// the JSON RFC http://www.ietf.org/rfc/rfc4627.txt: + //// + //// Since the first two characters of a JSON text will always be ASCII + //// characters [RFC0020], it is possible to determine whether an octet + //// stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking + //// at the pattern of nulls in the first four octets. + //// + //// 00 00 00 xx UTF-32BE + //// 00 xx 00 xx UTF-16BE + //// xx 00 00 00 UTF-32LE + //// xx 00 xx 00 UTF-16LE + //// xx xx xx xx UTF-8 + //// + //// - parameter header: The front Slice of data being read and evaluated. + //// - returns: A tuple containing the detected Unicode encoding and the lenght of the byte order mark. + static func detectEncoding(header: Slice>) -> ByteStreamPrefixInformation { + + guard let prefix = prefixFromHeader(header) else { + return (.UTF8, 0) + } + + if let prefixInfo = JSONEncodingDetector.encodingFromBOM(prefix) { + return prefixInfo + } else { + switch prefix { + case(0, 0, 0?, _): + return (.UTF32BE, 0) + case(_, 0, 0?, 0?): + return (.UTF32LE, 0) + case (0, _, 0?, _), (0, _, _, _): + return (.UTF16BE, 0) + case (_, 0, _, 0?), (_, 0, _, _): + return (.UTF16LE, 0) + default: + return (.UTF8, 0) + } + } + } + + private typealias EncodingBytePrefix = (UInt8, UInt8, UInt8?, UInt8?) + + private static func prefixFromHeader(header: Slice>) -> EncodingBytePrefix? { + if header.count >= 4 { + return(header[0], header[1], header[2], header[3]) + } else if header.count >= 2 { + return (header[0], header[1], nil, nil) + } + return nil + } + + private static func encodingFromBOM(prefix: EncodingBytePrefix) -> ByteStreamPrefixInformation? { + switch prefix { + case(0xFE, 0xFF, _, _): + return (.UTF16BE, 2) + case(0x00, 0x00, 0xFE?, 0xFF?): + return (.UTF32BE, 4) + case(0xEF, 0xBB, 0xBF?, _): + return (.UTF8, 3) + case(0xFF, 0xFE, 0?, 0?): + return (.UTF32LE, 4) + case(0xFF, 0xFE, _, _): + return (.UTF16LE, 2) + default: + return nil + } + } +} diff --git a/Pods/Freddy/Sources/JSONLiteralConvertible.swift b/Pods/Freddy/Sources/JSONLiteralConvertible.swift new file mode 100644 index 0000000..b90e052 --- /dev/null +++ b/Pods/Freddy/Sources/JSONLiteralConvertible.swift @@ -0,0 +1,130 @@ +// +// JSONLiteralConvertible.swift +// Freddy +// +// Created by Zachary Waldowski on 5/11/15. +// Copyright © 2015 Big Nerd Ranch. Licensed under MIT. +// + +// MARK: - ArrayLiteralConvertible + +extension JSON: ArrayLiteralConvertible { + + /// Create an instance by copying each element of the `collection` into a + /// new `Array`. + public init(_ collection: Collection) { + self = .Array(Swift.Array(collection)) + } + + /// Create an instance initialized with `elements`. + public init(arrayLiteral elements: JSON...) { + self.init(elements) + } + +} + +// MARK: - DictionaryLiteralConvertible + +extension JSON: DictionaryLiteralConvertible { + + /// Create an instance by copying each key/value pair of the `pairs` into + /// a new `Dictionary`. + public init(_ pairs: Dictionary) { + var dictionary = Swift.Dictionary(minimumCapacity: pairs.underestimateCount()) + for (key, value) in pairs { + dictionary[key] = value + } + self = .Dictionary(dictionary) + } + + /// Create an instance initialized with `pairs`. + public init(dictionaryLiteral pairs: (Swift.String, JSON)...) { + self.init(pairs) + } + +} + +// MARK: - FloatLiteralConvertible + +extension JSON: FloatLiteralConvertible { + + /// Create an instance initialized to `Double` `value`. + public init(_ value: Swift.Double) { + self = .Double(value) + } + + /// Create a literal instance initialized to `value`. + public init(floatLiteral value: Swift.Double) { + self.init(value) + } + +} + +// MARK: - IntegerLiteralConvertible + +extension JSON: IntegerLiteralConvertible { + + /// Create an instance initialized to `Int` by `value`. + public init(_ value: Swift.Int) { + self = .Int(value) + } + + /// Create a literal instance initialized to `value`. + public init(integerLiteral value: Swift.Int) { + self.init(value) + } + +} + +// MARK: - StringLiteralConvertible + +extension JSON: StringLiteralConvertible { + + /// Create an instance initialized to `String` by `text`. + public init(_ text: Swift.String) { + self = .String(text) + } + + /// Create a literal instance initialized to `value`. + public init(stringLiteral value: StringLiteralType) { + self.init(value) + } + + /// Create a literal instance initialized to `value`. + public init(extendedGraphemeClusterLiteral value: StringLiteralType) { + self.init(value) + } + + /// Create a literal instance initialized to `value`. + public init(unicodeScalarLiteral value: StringLiteralType) { + self.init(value) + } + +} + +// MARK: - BooleanLiteralConvertible + +extension JSON: BooleanLiteralConvertible { + + /// Create an instance initialized to `Bool` by `value`. + public init(_ value: Swift.Bool) { + self = .Bool(value) + } + + /// Create a literal instance initialized to `value`. + public init(booleanLiteral value: Swift.Bool) { + self.init(value) + } + +} + +// MARK: - NilLiteralConvertible + +extension JSON: NilLiteralConvertible { + + /// Create an instance initialized with `nil`. + public init(nilLiteral: ()) { + self = .Null + } + +} diff --git a/Pods/Freddy/Sources/JSONParser.swift b/Pods/Freddy/Sources/JSONParser.swift new file mode 100644 index 0000000..00dc9af --- /dev/null +++ b/Pods/Freddy/Sources/JSONParser.swift @@ -0,0 +1,903 @@ +// +// JSONParser.swift +// Freddy +// +// Created by John Gallagher on 4/18/15. +// Copyright © 2015 Big Nerd Ranch. Licensed under MIT. +// + +import Foundation + +private struct Literal { + static let BACKSLASH = UInt8(ascii: "\\") + static let BACKSPACE = UInt8(ascii: "\u{0008}") + static let COLON = UInt8(ascii: ":") + static let COMMA = UInt8(ascii: ",") + static let DOUBLE_QUOTE = UInt8(ascii: "\"") + static let FORMFEED = UInt8(ascii: "\u{000c}") + static let LEFT_BRACE = UInt8(ascii: "{") + static let LEFT_BRACKET = UInt8(ascii: "[") + static let MINUS = UInt8(ascii: "-") + static let NEWLINE = UInt8(ascii: "\n") + static let PERIOD = UInt8(ascii: ".") + static let PLUS = UInt8(ascii: "+") + static let RETURN = UInt8(ascii: "\r") + static let RIGHT_BRACE = UInt8(ascii: "}") + static let RIGHT_BRACKET = UInt8(ascii: "]") + static let SLASH = UInt8(ascii: "/") + static let SPACE = UInt8(ascii: " ") + static let TAB = UInt8(ascii: "\t") + + static let a = UInt8(ascii: "a") + static let b = UInt8(ascii: "b") + static let c = UInt8(ascii: "c") + static let d = UInt8(ascii: "d") + static let e = UInt8(ascii: "e") + static let f = UInt8(ascii: "f") + static let l = UInt8(ascii: "l") + static let n = UInt8(ascii: "n") + static let r = UInt8(ascii: "r") + static let s = UInt8(ascii: "s") + static let t = UInt8(ascii: "t") + static let u = UInt8(ascii: "u") + + static let A = UInt8(ascii: "A") + static let B = UInt8(ascii: "B") + static let C = UInt8(ascii: "C") + static let D = UInt8(ascii: "D") + static let E = UInt8(ascii: "E") + static let F = UInt8(ascii: "F") + + static let zero = UInt8(ascii: "0") + static let one = UInt8(ascii: "1") + static let two = UInt8(ascii: "2") + static let three = UInt8(ascii: "3") + static let four = UInt8(ascii: "4") + static let five = UInt8(ascii: "5") + static let six = UInt8(ascii: "6") + static let seven = UInt8(ascii: "7") + static let eight = UInt8(ascii: "8") + static let nine = UInt8(ascii: "9") +} + +private let ParserMaximumDepth = 512 + + +/// A pure Swift JSON parser. This parser is much faster than the +/// `NSJSONSerialization`-based parser (due to the overhead of having to +/// dynamically cast the Objective-C objects to determine their type); however, +/// it is much newer and has restrictions that the `NSJSONSerialization` parser +/// does not. Two restrictions in particular are that it requires UTF-8 data as +/// input and it does not allow trailing commas in arrays or dictionaries. +public struct JSONParser { + + private enum Sign: Int { + case Positive = 1 + case Negative = -1 + } + + private let input: UnsafeBufferPointer + private let owner: Any? + private var loc = 0 + private var depth = 0 + + private init(buffer: UnsafeBufferPointer, owner: T) { + self.input = buffer + self.owner = owner + } + + /// Decode the root element of the `JSON` stream. This may be any fragment + /// or a structural element, per RFC 7159. + /// + /// The beginning bytes are used to determine the stream's encoding. + /// `JSONParser` currently only supports UTF-8 encoding, with or without + /// a byte-order mark. + /// + /// - throws: `JSONParser.Error` for any decoding failures, including a + /// source location if needed. + public mutating func parse() throws -> JSON { + try guardAgainstUnsupportedEncodings() + let value = try parseValue() + skipWhitespace() + guard loc == input.count else { + throw Error.EndOfStreamGarbage(offset: loc) + } + return value + } + + private mutating func parseValue() throws -> JSON { + guard depth <= ParserMaximumDepth else { + throw Error.ExceededNestingLimit(offset: loc) + } + + guard input.count > 0 else { + throw Error.EndOfStreamUnexpected + } + + advancing: while loc < input.count { + do { + switch input[loc] { + case Literal.LEFT_BRACKET: + depth += 1 + defer { depth -= 1 } + return try decodeArray() + + case Literal.LEFT_BRACE: + depth += 1 + defer { depth -= 1 } + return try decodeObject() + + case Literal.DOUBLE_QUOTE: + return try decodeString() + + case Literal.f: + return try decodeFalse() + + case Literal.n: + return try decodeNull() + + case Literal.t: + return try decodeTrue() + + case Literal.MINUS: + return try decodeIntegralValue(NumberParser(loc: loc, input: input, state: .LeadingMinus)) + + case Literal.zero: + return try decodeIntegralValue(NumberParser(loc: loc, input: input, state: .LeadingZero)) + + case Literal.one...Literal.nine: + return try decodeIntegralValue(NumberParser(loc: loc, input: input, state: .PreDecimalDigits)) + + case Literal.SPACE, Literal.TAB, Literal.RETURN, Literal.NEWLINE: + loc = loc.successor() + + default: + break advancing + } + } catch let InternalError.NumberOverflow(offset: start) { + return try decodeNumberAsString(start) + } + } + + throw Error.ValueInvalid(offset: loc, character: UnicodeScalar(input[loc])) + } + + private mutating func skipWhitespace() { + while loc < input.count { + switch input[loc] { + case Literal.SPACE, Literal.TAB, Literal.RETURN, Literal.NEWLINE: + loc = loc.successor() + + default: + return + } + } + } + + private mutating func guardAgainstUnsupportedEncodings() throws { + let header = input.prefix(4) + let encodingPrefixInformation = JSONEncodingDetector.detectEncoding(header) + guard JSONEncodingDetector.supportedEncodings.contains(encodingPrefixInformation.encoding) else { + throw Error.InvalidUnicodeStreamEncoding(detectedEncoding: encodingPrefixInformation.encoding) + } + loc = loc.advancedBy(encodingPrefixInformation.byteOrderMarkLength) + } + + private mutating func decodeNull() throws -> JSON { + guard loc.advancedBy(3, limit: input.count) != input.count else { + throw Error.LiteralNilMisspelled(offset: loc) + } + + if input[loc+1] != Literal.u + || input[loc+2] != Literal.l + || input[loc+3] != Literal.l { + throw Error.LiteralNilMisspelled(offset: loc) + } + + loc += 4 + return .Null + } + + private mutating func decodeTrue() throws -> JSON { + guard loc.advancedBy(3, limit: input.count) != input.count else { + throw Error.LiteralTrueMisspelled(offset: loc) + } + + if input[loc+1] != Literal.r + || input[loc+2] != Literal.u + || input[loc+3] != Literal.e { + throw Error.LiteralTrueMisspelled(offset: loc) + } + + loc += 4 + return .Bool(true) + } + + private mutating func decodeFalse() throws -> JSON { + guard loc.advancedBy(4, limit: input.count) != input.count else { + throw Error.LiteralFalseMisspelled(offset: loc) + } + + if input[loc+1] != Literal.a + || input[loc+2] != Literal.l + || input[loc+3] != Literal.s + || input[loc+4] != Literal.e { + throw Error.LiteralFalseMisspelled(offset: loc) + } + + loc += 5 + return .Bool(false) + } + + private var stringDecodingBuffer = [UInt8]() + private mutating func decodeString() throws -> JSON { + let start = loc + loc = loc.successor() + stringDecodingBuffer.removeAll(keepCapacity: true) + while loc < input.count { + switch input[loc] { + case Literal.BACKSLASH: + loc = loc.successor() + switch input[loc] { + case Literal.DOUBLE_QUOTE: stringDecodingBuffer.append(Literal.DOUBLE_QUOTE) + case Literal.BACKSLASH: stringDecodingBuffer.append(Literal.BACKSLASH) + case Literal.SLASH: stringDecodingBuffer.append(Literal.SLASH) + case Literal.b: stringDecodingBuffer.append(Literal.BACKSPACE) + case Literal.f: stringDecodingBuffer.append(Literal.FORMFEED) + case Literal.r: stringDecodingBuffer.append(Literal.RETURN) + case Literal.t: stringDecodingBuffer.append(Literal.TAB) + case Literal.n: stringDecodingBuffer.append(Literal.NEWLINE) + case Literal.u: + loc = loc.successor() + try readUnicodeEscape(start: loc - 2) + + // readUnicodeEscape() advances loc on its own, so we'll `continue` now + // to skip the typical "advance past this character" for all the other escapes + continue + + default: + throw Error.ControlCharacterUnrecognized(offset: loc) + } + loc = loc.successor() + + case Literal.DOUBLE_QUOTE: + loc = loc.successor() + stringDecodingBuffer.append(0) + + guard let string = (stringDecodingBuffer.withUnsafeBufferPointer { + String.fromCString(UnsafePointer($0.baseAddress)) + }) else { + throw Error.UnicodeEscapeInvalid(offset: start) + } + + return .String(string) + + case let other: + stringDecodingBuffer.append(other) + loc = loc.successor() + } + } + + throw Error.EndOfStreamUnexpected + } + + private mutating func readCodeUnit() -> UInt16? { + guard loc + 4 <= input.count else { + return nil + } + var codeUnit: UInt16 = 0 + for c in input[loc.. JSON { + let start = loc + loc = loc.successor() + var items = [JSON]() + + while loc < input.count { + skipWhitespace() + + if loc < input.count && input[loc] == Literal.RIGHT_BRACKET { + loc = loc.successor() + return .Array(items) + } + + if !items.isEmpty { + guard loc < input.count && input[loc] == Literal.COMMA else { + throw Error.CollectionMissingSeparator(offset: start) + } + loc = loc.successor() + } + + items.append(try parseValue()) + } + + throw Error.EndOfStreamUnexpected + } + + // Decoding objects can be recursive, so we have to keep more than one + // buffer around for building up key/value pairs (to reduce allocations + // when parsing large JSON documents). + // + // Rough estimate of the difference between this and using a fresh + // [(String,JSON)] for the `pairs` variable in decodeObject() below is + // about 12% on an iPhone 5. + private struct DecodeObjectBuffers { + var buffers = [[(String,JSON)]]() + + mutating func getBuffer() -> [(String,JSON)] { + if !buffers.isEmpty { + var buffer = buffers.removeLast() + buffer.removeAll(keepCapacity: true) + return buffer + } + return [(String,JSON)]() + } + + mutating func putBuffer(buffer: [(String,JSON)]) { + buffers.append(buffer) + } + } + + private var decodeObjectBuffers = DecodeObjectBuffers() + + private mutating func decodeObject() throws -> JSON { + let start = loc + loc = loc.successor() + var pairs = decodeObjectBuffers.getBuffer() + + while loc < input.count { + skipWhitespace() + + if loc < input.count && input[loc] == Literal.RIGHT_BRACE { + loc = loc.successor() + var obj = [String:JSON](minimumCapacity: pairs.count) + for (k, v) in pairs { + obj[k] = v + } + decodeObjectBuffers.putBuffer(pairs) + return .Dictionary(obj) + } + + if !pairs.isEmpty { + guard loc < input.count && input[loc] == Literal.COMMA else { + throw Error.CollectionMissingSeparator(offset: start) + } + loc = loc.successor() + + skipWhitespace() + } + + guard loc < input.count && input[loc] == Literal.DOUBLE_QUOTE else { + throw Error.DictionaryMissingKey(offset: start) + } + + let key = try decodeString().string() + skipWhitespace() + + guard loc < input.count && input[loc] == Literal.COLON else { + throw Error.CollectionMissingSeparator(offset: start) + } + loc = loc.successor() + + pairs.append((key, try parseValue())) + } + + throw Error.EndOfStreamUnexpected + } + + private mutating func decodeIntegralValue(parser: NumberParser) throws -> JSON { + var sign = Sign.Positive + var parser = parser + var value = 0 + + // This would be more natural as `while true { ... }` with a meaningful .Done case, + // but that causes compile time explosion in Swift 2.2. :-| + while parser.state != .Done { + switch parser.state { + case .LeadingMinus: + sign = .Negative + try parser.parseNegative() + + case .LeadingZero: + parser.parseLeadingZero() + + case .PreDecimalDigits: + try parser.parsePreDecimalDigits { c in + guard case let (exponent, false) = Int.multiplyWithOverflow(10, value) else { + throw InternalError.NumberOverflow(offset: parser.start) + } + + guard case let (newValue, false) = Int.addWithOverflow(exponent, Int(c - Literal.zero)) else { + throw InternalError.NumberOverflow(offset: parser.start) + } + + value = newValue + } + + case .Decimal, .Exponent: + return try detectingFloatingPointErrors(parser.start) { + try decodeFloatingPointValue(parser, sign: sign, value: Double(value)) + } + + case .PostDecimalDigits, .ExponentSign, .ExponentDigits: + assertionFailure("Invalid internal state while parsing number") + + case .Done: + fatalError("impossible condition") + } + } + + guard case let (signedValue, false) = Int.multiplyWithOverflow(sign.rawValue, value) else { + throw InternalError.NumberOverflow(offset: parser.start) + } + + loc = parser.loc + return .Int(signedValue) + } + + private mutating func decodeFloatingPointValue(parser: NumberParser, sign: Sign, value: Double) throws -> JSON { + var parser = parser + var value = value + var exponentSign = Sign.Positive + var exponent = Double(0) + var position = 0.1 + + // This would be more natural as `while true { ... }` with a meaningful .Done case, + // but that causes compile time explosion in Swift 2.2. :-| + while parser.state != .Done { + switch parser.state { + case .LeadingMinus, .LeadingZero, .PreDecimalDigits: + assertionFailure("Invalid internal state while parsing number") + + case .Decimal: + try parser.parseDecimal() + + case .PostDecimalDigits: + parser.parsePostDecimalDigits { c in + value += position * Double(c - Literal.zero) + position /= 10 + } + + case .Exponent: + exponentSign = try parser.parseExponent() + + case .ExponentSign: + try parser.parseExponentSign() + + case .ExponentDigits: + parser.parseExponentDigits { c in + exponent = exponent * 10 + Double(c - Literal.zero) + } + + case .Done: + fatalError("impossible condition") + } + } + + loc = parser.loc + return .Double(Double(sign.rawValue) * value * pow(10, Double(exponentSign.rawValue) * exponent)) + } + + private mutating func decodeNumberAsString(start: Int) throws -> JSON { + var parser: NumberParser = { + let state: NumberParser.State + switch input[start] { + case Literal.MINUS: state = .LeadingMinus + case Literal.zero: state = .LeadingZero + case Literal.one...Literal.nine: state = .PreDecimalDigits + default: + fatalError("Internal error: decodeNumber called on not-a-number") + } + return NumberParser(loc: start, input: input, state: state) + }() + + stringDecodingBuffer.removeAll(keepCapacity: true) + + while true { + switch parser.state { + case .LeadingMinus: + try parser.parseNegative() + stringDecodingBuffer.append(Literal.MINUS) + + case .LeadingZero: + parser.parseLeadingZero() + stringDecodingBuffer.append(Literal.zero) + + case .PreDecimalDigits: + parser.parsePreDecimalDigits { stringDecodingBuffer.append($0) } + + case .Decimal: + try parser.parseDecimal() + stringDecodingBuffer.append(Literal.PERIOD) + + case .PostDecimalDigits: + parser.parsePostDecimalDigits { stringDecodingBuffer.append($0) } + + case .Exponent: + stringDecodingBuffer.append(input[parser.loc]) + _ = try parser.parseExponent() + + case .ExponentSign: + stringDecodingBuffer.append(input[parser.loc]) + try parser.parseExponentSign() + + case .ExponentDigits: + parser.parseExponentDigits { stringDecodingBuffer.append($0) } + + case .Done: + stringDecodingBuffer.append(0) + guard let string = (stringDecodingBuffer.withUnsafeBufferPointer { + String.fromCString(UnsafePointer($0.baseAddress)) + }) else { + // Should never fail - any problems with the number string should + // result in thrown errors above + fatalError("Internal error: Invalid numeric string") + } + + loc = parser.loc + return .String(string) + } + } + } + + private func detectingFloatingPointErrors(loc: Int, @noescape _ f: () throws -> T) throws -> T { + let flags = FE_UNDERFLOW | FE_OVERFLOW + feclearexcept(flags) + let value = try f() + guard fetestexcept(flags) == 0 else { + throw InternalError.NumberOverflow(offset: loc) + } + return value + } +} + +private struct NumberParser { + enum State { + case LeadingMinus + case LeadingZero + case PreDecimalDigits + case Decimal + case PostDecimalDigits + case Exponent + case ExponentSign + case ExponentDigits + case Done + } + + let start: Int + var loc = 0 + var state: State + let input: UnsafeBufferPointer + + init(loc: Int, input: UnsafeBufferPointer, state: State) { + assert(loc < input.count, "Invalid input to NumberParser") + self.start = loc + self.loc = loc + self.input = input + self.state = state + } + + mutating func parseNegative() throws { + assert(state == .LeadingMinus, "Unexpected state entering parseNegative") + + loc = loc.successor() + guard loc < input.count else { + throw JSONParser.Error.EndOfStreamUnexpected + } + + switch input[loc] { + case Literal.zero: + state = .LeadingZero + + case Literal.one...Literal.nine: + state = .PreDecimalDigits + + default: + throw JSONParser.Error.NumberSymbolMissingDigits(offset: start) + } + } + + mutating func parseLeadingZero() { + assert(state == .LeadingZero, "Unexpected state entering parseLeadingZero") + + loc = loc.successor() + guard loc < input.count else { + state = .Done + return + } + + guard input[loc] == Literal.PERIOD else { + state = .Done + return + } + + state = .Decimal + } + + mutating func parsePreDecimalDigits(@noescape f: (UInt8) throws -> Void) rethrows { + assert(state == .PreDecimalDigits, "Unexpected state entering parsePreDecimalDigits") + advancing: while loc < input.count { + let c = input[loc] + switch c { + case Literal.zero...Literal.nine: + try f(c) + loc = loc.successor() + + case Literal.PERIOD: + state = .Decimal + return + + case Literal.e, Literal.E: + state = .Exponent + return + + default: + break advancing + } + } + + state = .Done + } + + mutating func parseDecimal() throws { + assert(state == .Decimal, "Unexpected state entering parseDecimal") + loc = loc.successor() + guard loc < input.count else { + throw JSONParser.Error.EndOfStreamUnexpected + } + + switch input[loc] { + case Literal.zero...Literal.nine: + state = .PostDecimalDigits + + default: + throw JSONParser.Error.NumberMissingFractionalDigits(offset: start) + } + } + + mutating func parsePostDecimalDigits(@noescape f: (UInt8) throws -> Void) rethrows { + assert(state == .PostDecimalDigits, "Unexpected state entering parsePostDecimalDigits") + + advancing: while loc < input.count { + let c = input[loc] + switch c { + case Literal.zero...Literal.nine: + try f(c) + loc = loc.successor() + + case Literal.e, Literal.E: + state = .Exponent + return + + default: + break advancing + } + } + + state = .Done + } + + mutating func parseExponent() throws -> JSONParser.Sign { + assert(state == .Exponent, "Unexpected state entering parseExponent") + + loc = loc.successor() + guard loc < input.count else { + throw JSONParser.Error.EndOfStreamUnexpected + } + + switch input[loc] { + case Literal.zero...Literal.nine: + state = .ExponentDigits + + case Literal.PLUS: + state = .ExponentSign + + case Literal.MINUS: + state = .ExponentSign + return .Negative + + default: + throw JSONParser.Error.NumberSymbolMissingDigits(offset: start) + } + + return .Positive + } + + mutating func parseExponentSign() throws { + assert(state == .ExponentSign, "Unexpected state entering parseExponentSign") + loc = loc.successor() + guard loc < input.count else { + throw JSONParser.Error.EndOfStreamUnexpected + } + + switch input[loc] { + case Literal.zero...Literal.nine: + state = .ExponentDigits + + default: + throw JSONParser.Error.NumberSymbolMissingDigits(offset: start) + } + } + + mutating func parseExponentDigits(@noescape f: (UInt8) throws -> Void) rethrows { + assert(state == .ExponentDigits, "Unexpected state entering parseExponentDigits") + advancing: while loc < input.count { + let c = input[loc] + switch c { + case Literal.zero...Literal.nine: + try f(c) + loc = loc.successor() + + default: + break advancing + } + } + + state = .Done + } +} + +public extension JSONParser { + + /// Creates a `JSONParser` ready to parse UTF-8 encoded `NSData`. + /// + /// If the data is mutable, it is copied before parsing. The data's lifetime + /// is extended for the duration of parsing. + init(utf8Data inData: NSData) { + let data = inData.copy() as! NSData + let buffer = UnsafeBufferPointer(start: UnsafePointer(data.bytes), count: data.length) + self.init(buffer: buffer, owner: data) + } + + /// Creates a `JSONParser` from the code units represented by the `string`. + /// + /// The synthesized string is lifetime-extended for the duration of parsing. + init(string: String) { + let codePoints = string.nulTerminatedUTF8 + let buffer = codePoints.withUnsafeBufferPointer { nulTerminatedBuffer in + // don't want to include the nul termination in the buffer - trim it off + UnsafeBufferPointer(start: nulTerminatedBuffer.baseAddress, count: nulTerminatedBuffer.count - 1) + } + self.init(buffer: buffer, owner: codePoints) + } + +} + +extension JSONParser: JSONParserType { + + /// Creates an instance of `JSON` from UTF-8 encoded `NSData`. + /// - parameter data: An instance of `NSData` to parse `JSON` from. + /// - throws: Any `JSONParser.Error` that arises during decoding. + /// - seealso: JSONParser.parse() + public static func createJSONFromData(data: NSData) throws -> JSON { + var parser = JSONParser(utf8Data: data) + return try parser.parse() + } + +} + +// MARK: - Errors + +extension JSONParser { + + /// Enumeration describing possible errors that occur while parsing a JSON + /// document. Most errors include an associated `offset`, representing the + /// offset into the UTF-8 characters making up the document where the error + /// occurred. + public enum Error: ErrorType { + /// The parser ran out of data prematurely. This usually means a value + /// was not escaped, such as a string literal not ending with a double + /// quote. + case EndOfStreamUnexpected + + /// Unexpected non-whitespace data was left around `offset` after + /// parsing all valid JSON. + case EndOfStreamGarbage(offset: Int) + + /// Too many nested objects or arrays occured at the literal started + /// around `offset`. + case ExceededNestingLimit(offset: Int) + + /// A `character` was not a valid start of a value around `offset`. + case ValueInvalid(offset: Int, character: UnicodeScalar) + + /// Badly-formed Unicode escape sequence at `offset`. A Unicode escape + /// uses the text "\u" followed by 4 hex digits, such as "\uF09F\uA684" + /// to represent U+1F984, "UNICORN FACE". + case UnicodeEscapeInvalid(offset: Int) + + /// Badly-formed control character around `offset`. JSON supports + /// backslash-escaped double quotes, slashes, whitespace control codes, + /// and Unicode escape sequences. + case ControlCharacterUnrecognized(offset: Int) + + /// Invalid token, expected `null` around `offset` + case LiteralNilMisspelled(offset: Int) + + /// Invalid token, expected `true` around `offset` + case LiteralTrueMisspelled(offset: Int) + + /// Invalid token, expected `false` around `offset` + case LiteralFalseMisspelled(offset: Int) + + /// Badly-formed collection at given `offset`, expected `,` or `:` + case CollectionMissingSeparator(offset: Int) + + /// While parsing an object literal, a value was found without a key + /// around `offset`. The start of a string literal was expected. + case DictionaryMissingKey(offset: Int) + + /// Badly-formed number with no digits around `offset`. After a decimal + /// point, a number must include some number of digits. + case NumberMissingFractionalDigits(offset: Int) + + /// Badly-formed number with symbols ("-" or "e") but no following + /// digits around `offset`. + case NumberSymbolMissingDigits(offset: Int) + + /// Supplied data is encoded in an unsupported format. + case InvalidUnicodeStreamEncoding(detectedEncoding: JSONEncodingDetector.Encoding) + } + + private enum InternalError: ErrorType { + /// Attempted to parse an integer outside the range of [Int.min, Int.max] + /// or a double outside the range of representable doubles. Note that + /// for doubles, this could be an overflow or an underflow - we don't + /// get enough information from Swift here to know which it is. The number + /// causing the overflow/underflow began at `offset`. + case NumberOverflow(offset: Int) + } +} diff --git a/Pods/Freddy/Sources/JSONParsing.swift b/Pods/Freddy/Sources/JSONParsing.swift new file mode 100644 index 0000000..90cb6be --- /dev/null +++ b/Pods/Freddy/Sources/JSONParsing.swift @@ -0,0 +1,126 @@ +// +// JSONParsing.swift +// Freddy +// +// Created by Matthew D. Mathias on 3/17/15. +// Copyright © 2015 Big Nerd Ranch. All rights reserved. +// + +import Foundation + +// MARK: - Deserialize JSON + +/// Protocol describing a backend parser that can produce `JSON` from `NSData`. +public protocol JSONParserType { + + /// Creates an instance of `JSON` from `NSData`. + /// - parameter data: An instance of `NSData` to use to create `JSON`. + /// - throws: An error that may arise from calling `JSONObjectWithData(_:options:)` on `NSJSONSerialization` with the given data. + /// - returns: An instance of `JSON`. + static func createJSONFromData(data: NSData) throws -> JSON + +} + +extension JSON { + + /// Create `JSON` from UTF-8 `data`. By default, parses using the + /// Swift-native `JSONParser` backend. + public init(data: NSData, usingParser parser: JSONParserType.Type = JSONParser.self) throws { + self = try parser.createJSONFromData(data) + } + + /// Create `JSON` from UTF-8 `string`. + public init(jsonString: Swift.String, usingParser parser: JSONParserType.Type = JSONParser.self) throws { + self = try parser.createJSONFromData((jsonString as NSString).dataUsingEncoding(NSUTF8StringEncoding) ?? NSData()) + } +} + +// MARK: - NSJSONSerialization + +extension NSJSONSerialization: JSONParserType { + + // MARK: Decode NSData + + /// Use the built-in, Objective-C based JSON parser to create `JSON`. + /// - parameter data: An instance of `NSData`. + /// - returns: An instance of `JSON`. + /// - throws: An error that may arise if the `NSData` cannot be parsed into an object. + public static func createJSONFromData(data: NSData) throws -> JSON { + return makeJSON(try NSJSONSerialization.JSONObjectWithData(data, options: [])) + } + + // MARK: Make JSON + + /// Makes a `JSON` object by matching its argument to a case in the `JSON` enum. + /// - parameter object: The instance of `AnyObject` returned from serializing the JSON. + /// - returns: An instance of `JSON` matching the JSON given to the function. + private static func makeJSON(object: AnyObject) -> JSON { + switch object { + case let n as NSNumber: + let numberType = CFNumberGetType(n) + switch numberType { + case .CharType: + return .Bool(n.boolValue) + + case .ShortType, .IntType, .LongType, .CFIndexType, .NSIntegerType, .SInt8Type, .SInt16Type, .SInt32Type: + return .Int(n.integerValue) + + case .SInt64Type, .LongLongType /* overflows 32-bit Int */: + #if /* 32-bit arch */ arch(arm) || arch(i386) + // Why double, when the Freddy parser would bump to String? + // + // Returning Double avoids making the type depend on whether you're running + // 32-bit or 64-bit code when using the NSJSONSerialization parser. + // NSJSONSerialization appears to bump numbers larger than Int.max to Double on + // 64-bit platforms but use .SInt64Type on 32-bit platforms. + // If we returned a String here, you'd get a String value on 32-bit, + // but a Double value on 64-bit. Instead, we return Double. + // + // This means that, if you switch parsers, + // you'll have to switch from .double to .string for pulling out + // overflowing values, but if you stick with a single parser, + // you at least won't have architecture-dependent lookups! + return .Double(n.doubleValue) + #else + return .Int(n.integerValue) + #endif + + case .Float32Type, .Float64Type, .FloatType, .DoubleType, .CGFloatType: + return .Double(n.doubleValue) + } + + case let arr as [AnyObject]: + return makeJSONArray(arr) + + case let dict as [Swift.String: AnyObject]: + return makeJSONDictionary(dict) + + case let s as Swift.String: + return .String(s) + + default: + return .Null + } + } + + // MARK: Make a JSON Array + + /// Makes a `JSON` array from the object passed in. + /// - parameter jsonArray: The array to transform into a `JSON`. + /// - returns: An instance of `JSON` matching the array. + private static func makeJSONArray(jsonArray: [AnyObject]) -> JSON { + return .Array(jsonArray.map(makeJSON)) + } + + // MARK: Make a JSON Dictionary + + /// Makes a `JSON` dictionary from the Cocoa dictionary passed in. + /// - parameter jsonDict: The dictionary to transform into `JSON`. + /// - returns: An instance of `JSON` matching the dictionary. + private static func makeJSONDictionary(jsonDict: [Swift.String: AnyObject]) -> JSON { + return JSON(jsonDict.lazy.map { (key, value) in + (key, makeJSON(value)) + }) + } + +} diff --git a/Pods/Freddy/Sources/JSONSerializing.swift b/Pods/Freddy/Sources/JSONSerializing.swift new file mode 100644 index 0000000..343a5a3 --- /dev/null +++ b/Pods/Freddy/Sources/JSONSerializing.swift @@ -0,0 +1,43 @@ +// Copyright (C) 2016 Big Nerd Ranch, Inc. Licensed under the MIT license WITHOUT ANY WARRANTY. + +import Foundation + +// MARK: - Serialize JSON + +extension JSON { + + /// Attempt to serialize `JSON` into an `NSData`. + /// - returns: A byte-stream containing the `JSON` ready for wire transfer. + /// - throws: Errors that arise from `NSJSONSerialization`. + /// - see: Foundation.NSJSONSerialization + public func serialize() throws -> NSData { + let obj: AnyObject = toNSJSONSerializationObject() + return try NSJSONSerialization.dataWithJSONObject(obj, options: []) + } + + /// A function to help with the serialization of `JSON`. + /// - returns: An `AnyObject` suitable for `NSJSONSerialization`'s use. + private func toNSJSONSerializationObject() -> AnyObject { + switch self { + case .Array(let jsonArray): + return jsonArray.map { $0.toNSJSONSerializationObject() } + case .Dictionary(let jsonDictionary): + var cocoaDictionary = Swift.Dictionary(minimumCapacity: jsonDictionary.count) + for (key, json) in jsonDictionary { + cocoaDictionary[key] = json.toNSJSONSerializationObject() + } + return cocoaDictionary + case .String(let str): + return str + case .Double(let num): + return num + case .Int(let int): + return int + case .Bool(let b): + return b + case .Null: + return NSNull() + } + + } +} diff --git a/Pods/Freddy/Sources/JSONSubscripting.swift b/Pods/Freddy/Sources/JSONSubscripting.swift new file mode 100644 index 0000000..785f8ce --- /dev/null +++ b/Pods/Freddy/Sources/JSONSubscripting.swift @@ -0,0 +1,643 @@ +// +// JSONSubscripting.swift +// Freddy +// +// Created by Zachary Waldowski on 8/15/15. +// Copyright © 2015 Big Nerd Ranch. All rights reserved. +// + +// MARK: JSONPathType + +/// A protocol used to define a path within an instance of `JSON` that leads to some desired value. +/// +/// A custom type, such as a `RawRepresentable` enum, may be made to conform to `JSONPathType` +/// and used with the subscript APIs. +public protocol JSONPathType { + /// Use `self` to key into a `dictionary`. + /// + /// Unlike Swift dictionaries, failing to find a value for a key should throw + /// an error rather than convert to `nil`. + /// + /// Upon failure, implementers should throw an error from `JSON.Error`. + func valueInDictionary(dictionary: [Swift.String : JSON]) throws -> JSON + + /// Use `self` to index into an `array`. + /// + /// Unlike Swift array, attempting to index outside the collection's bounds + /// should throw an error rather than crash. + /// + /// Upon failure, implementers should throw an error from `JSON.Error`. + func valueInArray(array: [JSON]) throws -> JSON +} + +extension JSONPathType { + + /// The default behavior for keying into a dictionary is to throw + /// `JSON.Error.UnexpectedSubscript`. + public func valueInDictionary(dictionary: [Swift.String : JSON]) throws -> JSON { + throw JSON.Error.UnexpectedSubscript(type: Self.self) + } + + /// The default behavior for indexing into an array is to throw + /// `JSON.Error.UnexpectedSubscript`. + public func valueInArray(array: [JSON]) throws -> JSON { + throw JSON.Error.UnexpectedSubscript(type: Self.self) + } + +} + +extension String: JSONPathType { + + /// A method used to retrieve a value from a given dictionary for a specific key. + /// - throws: `.KeyNotFound` with an associated value of `self`, where `self` is a `String`, + /// should the key not be present within the `JSON`. + /// - returns: The `JSON` value associated with the given key. + public func valueInDictionary(dictionary: [Swift.String : JSON]) throws -> JSON { + guard let next = dictionary[self] else { + throw JSON.Error.KeyNotFound(key: self) + } + return next + } + +} + +extension Int: JSONPathType { + + /// A method used to retrieve a value from a given array for a specific index. + /// - throws: `.IndexOutOfBounds` with an associated value of `self`, where `self` is an `Int`, + /// should the index not be within the valid range for the array of `JSON`. + /// - returns: The `JSON` value found at the given index. + public func valueInArray(array: [JSON]) throws -> JSON { + guard case array.indices = self else { + throw JSON.Error.IndexOutOfBounds(index: self) + } + return array[self] + } + +} + +// MARK: - Subscripting core + +private extension JSON { + + enum SubscriptError: ErrorType { + case SubscriptIntoNull(JSONPathType) + } + + func valueForPathFragment(fragment: JSONPathType, detectNull: Swift.Bool) throws -> JSON { + switch self { + case .Null where detectNull: + throw SubscriptError.SubscriptIntoNull(fragment) + case let .Dictionary(dict): + return try fragment.valueInDictionary(dict) + case let .Array(array): + return try fragment.valueInArray(array) + default: + throw Error.UnexpectedSubscript(type: fragment.dynamicType) + } + } + + func valueAtPath(path: [JSONPathType], detectNull: Swift.Bool = false) throws -> JSON { + var result = self + for fragment in path { + result = try result.valueForPathFragment(fragment, detectNull: detectNull) + } + return result + } + +} + +// MARK: - Subscripting operator + +extension JSON { + + public subscript(key: Swift.String) -> JSON? { + return try? valueForPathFragment(key, detectNull: false) + } + + public subscript(index: Swift.Int) -> JSON? { + return try? valueForPathFragment(index, detectNull: false) + } + +} + +// MARK: - Simple member unpacking + +extension JSON { + + /// Attempts to decode into the returning type from a path into JSON. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON`. + /// - parameter type: If the context this method is called from does not + /// make the return type clear, pass a type implementing `JSONDecodable` + /// to disambiguate the type to decode with. + /// - returns: An initialized member from the inner JSON. + /// - throws: One of the following errors contained in `JSON.Error`: + /// * `KeyNotFound`: A given `String` key does not exist inside a + /// descendant `JSON` dictionary. + /// * `IndexOutOfBounds`: A given `Int` index is outside the bounds of a + /// descendant `JSON` array. + /// * `UnexpectedSubscript`: A given subscript cannot be used with the + /// corresponding `JSON` value. + /// * `TypeNotConvertible`: The target value's type inside of + /// the `JSON` instance does not match `Decoded`. + public func decode(path: JSONPathType..., type: Decoded.Type = Decoded.self) throws -> Decoded { + return try Decoded(json: valueAtPath(path)) + } + + /// Retrieves a `Double` from a path into JSON. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - returns: A floating-point `Double` + /// - throws: One of the `JSON.Error` cases thrown by `decode(_:type:)`. + /// - seealso: `JSON.decode(_:type:)` + public func double(path: JSONPathType...) throws -> Swift.Double { + return try Swift.Double(json: valueAtPath(path)) + } + + /// Retrieves an `Int` from a path into JSON. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - returns: A numeric `Int` + /// - throws: One of the `JSON.Error` cases thrown by `decode(_:type:)`. + /// - seealso: `JSON.decode(_:type:)` + public func int(path: JSONPathType...) throws -> Swift.Int { + return try Swift.Int(json: valueAtPath(path)) + } + + /// Retrieves a `String` from a path into JSON. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - returns: A textual `String` + /// - throws: One of the `JSON.Error` cases thrown by `decode(_:type:)`. + /// - seealso: `JSON.decode(_:type:)` + public func string(path: JSONPathType...) throws -> Swift.String { + return try Swift.String(json: valueAtPath(path)) + } + + /// Retrieves a `Bool` from a path into JSON. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - returns: A truthy `Bool` + /// - throws: One of the `JSON.Error` cases thrown by `decode(_:type:)`. + /// - seealso: `JSON.decode(_:type:)` + public func bool(path: JSONPathType...) throws -> Swift.Bool { + return try Swift.Bool(json: valueAtPath(path)) + } + + /// Retrieves a `[JSON]` from a path into JSON. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - returns: An `Array` of `JSON` elements + /// - throws: One of the `JSON.Error` cases thrown by `decode(_:type:)`. + /// - seealso: `JSON.decode(_:type:)` + public func array(path: JSONPathType...) throws -> [JSON] { + return try JSON.getArray(valueAtPath(path)) + } + + /// Attempts to decodes many values from a desendant JSON array at a path + /// into JSON. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - parameter type: If the context this method is called from does not + /// make the return type clear, pass a type implementing `JSONDecodable` + /// to disambiguate the type to decode with. + /// - returns: An `Array` of decoded elements + /// - throws: One of the `JSON.Error` cases thrown by `decode(_:type:)`, or + /// any error that arises from decoding the contained values. + /// - seealso: `JSON.decode(_:type:)` + public func arrayOf(path: JSONPathType..., type: Decoded.Type = Decoded.self) throws -> [Decoded] { + return try JSON.getArrayOf(valueAtPath(path)) + } + + /// Retrieves a `[String: JSON]` from a path into JSON. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - returns: An `Dictionary` of `String` mapping to `JSON` elements + /// - throws: One of the `JSON.Error` cases thrown by `decode(_:type:)`. + /// - seealso: `JSON.decode(_:type:)` + public func dictionary(path: JSONPathType...) throws -> [Swift.String: JSON] { + return try JSON.getDictionary(valueAtPath(path)) + } + +} + +// MARK: - NotFound-Or-Null-to-Optional unpacking + +extension JSON { + + /// An `OptionSetType` used to represent the different options available for subscripting `JSON` with `null` values or missing keys. + /// * `.NullBecomesNil` - Treat `null` values as `nil`. + /// * `.MissingKeyBecomesNil` - Treat missing keys as `nil`. + public struct SubscriptingOptions: OptionSetType { + public let rawValue: Swift.Int + public init(rawValue: Swift.Int) { + self.rawValue = rawValue + } + + /// Treat `null` values as `nil`. + public static let NullBecomesNil = SubscriptingOptions(rawValue: 1 << 0) + /// Treat missing keys as `nil`. + public static let MissingKeyBecomesNil = SubscriptingOptions(rawValue: 1 << 1) + } + + private func mapOptionalAtPath(path: [JSONPathType], alongPath: SubscriptingOptions, @noescape transform: JSON throws -> Value) throws -> Value? { + let detectNull = alongPath.contains(.NullBecomesNil) + let detectNotFound = alongPath.contains(.MissingKeyBecomesNil) + var json: JSON? + do { + json = try valueAtPath(path, detectNull: detectNull) + return try json.map(transform) + } catch Error.IndexOutOfBounds where detectNotFound { + return nil + } catch Error.KeyNotFound where detectNotFound { + return nil + } catch Error.ValueNotConvertible where detectNull && json == .Null { + return nil + } catch SubscriptError.SubscriptIntoNull where detectNull { + return nil + } + } +} + +extension JSON { + + /// Optionally decodes into the returning type from a path into JSON. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - parameter alongPath: Options that control what should be done with values that are `null` or keys that are missing. + /// - parameter type: If the context this method is called from does not + /// make the return type clear, pass a type implementing `JSONDecodable` + /// to disambiguate the type to decode with. + /// - returns: A decoded value from the inner JSON if found, or `nil`. + /// - throws: One of the following errors contained in `JSON.Error`: + /// * `KeyNotFound`: A key `path` does not exist inside a descendant + /// `JSON` dictionary. + /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a + /// descendant `JSON` array. + /// * `UnexpectedSubscript`: A `path` item cannot be used with the + /// corresponding `JSON` value. + /// * `TypeNotConvertible`: The target value's type inside of the `JSON` + /// instance does not match the decoded value. + /// * Any error that arises from decoding the value. + public func decode(path: JSONPathType..., alongPath options: SubscriptingOptions, type: Decoded.Type = Decoded.self) throws -> Decoded? { + return try mapOptionalAtPath(path, alongPath: options, transform: Decoded.init) + } + + /// Optionally retrieves a `Double` from a path into JSON. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON`. + /// - parameter alongPath: Options that control what should be done with values that are `null` or keys that are missing. + /// - returns: A `Double` if a value could be found, otherwise `nil`. + /// - throws: One of the following errors contained in `JSON.Error`: + /// * `KeyNotFound`: A key `path` does not exist inside a descendant + /// `JSON` dictionary. + /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a + /// descendant `JSON` array. + /// * `UnexpectedSubscript`: A `path` item cannot be used with the + /// corresponding `JSON` value. + /// * `TypeNotConvertible`: The target value's type inside of the `JSON` + /// instance does not match the decoded value. + public func double(path: JSONPathType..., alongPath options: SubscriptingOptions) throws -> Swift.Double? { + return try mapOptionalAtPath(path, alongPath: options, transform: Swift.Double.init) + } + + /// Optionally retrieves a `Int` from a path into JSON. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - parameter alongPath: Options that control what should be done with values that are `null` or keys that are missing. + /// - returns: A numeric `Int` if a value could be found, otherwise `nil`. + /// - throws: One of the following errors contained in `JSON.Error`: + /// * `KeyNotFound`: A key `path` does not exist inside a descendant + /// `JSON` dictionary. + /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a + /// descendant `JSON` array. + /// * `UnexpectedSubscript`: A `path` item cannot be used with the + /// corresponding `JSON` value. + /// * `TypeNotConvertible`: The target value's type inside of the `JSON` + /// instance does not match the decoded value. + public func int(path: JSONPathType..., alongPath options: SubscriptingOptions) throws -> Swift.Int? { + return try mapOptionalAtPath(path, alongPath: options, transform: Swift.Int.init) + } + + /// Optionally retrieves a `String` from a path into JSON. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - parameter alongPath: Options that control what should be done with values that are `null` or keys that are missing. + /// - returns: A text `String` if a value could be found, otherwise `nil`. + /// - throws: One of the following errors contained in `JSON.Error`: + /// * `KeyNotFound`: A key `path` does not exist inside a descendant + /// `JSON` dictionary. + /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a + /// descendant `JSON` array. + /// * `UnexpectedSubscript`: A `path` item cannot be used with the + /// corresponding `JSON` value. + /// * `TypeNotConvertible`: The target value's type inside of the `JSON` + /// instance does not match the decoded value. + public func string(path: JSONPathType..., alongPath options: SubscriptingOptions) throws -> Swift.String? { + return try mapOptionalAtPath(path, alongPath: options, transform: Swift.String.init) + } + + /// Optionally retrieves a `Bool` from a path into JSON. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - parameter alongPath: Options that control what should be done with values that are `null` or keys that are missing. + /// - returns: A truthy `Bool` if a value could be found, otherwise `nil`. + /// - throws: One of the following errors contained in `JSON.Error`: + /// * `KeyNotFound`: A key `path` does not exist inside a descendant + /// `JSON` dictionary. + /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a + /// descendant `JSON` array. + /// * `UnexpectedSubscript`: A `path` item cannot be used with the + /// corresponding `JSON` value. + /// * `TypeNotConvertible`: The target value's type inside of the `JSON` + /// instance does not match the decoded value. + public func bool(path: JSONPathType..., alongPath options: SubscriptingOptions) throws -> Swift.Bool? { + return try mapOptionalAtPath(path, alongPath: options, transform: Swift.Bool.init) + } + + /// Optionally retrieves a `[JSON]` from a path into the recieving structure. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - parameter alongPath: Options that control what should be done with values that are `null` or keys that are missing. + /// - returns: An `Array` of `JSON` elements if a value could be found, + /// otherwise `nil`. + /// - throws: One of the following errors contained in `JSON.Error`: + /// * `KeyNotFound`: A key `path` does not exist inside a descendant + /// `JSON` dictionary. + /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a + /// descendant `JSON` array. + /// * `UnexpectedSubscript`: A `path` item cannot be used with the + /// corresponding `JSON` value. + /// * `TypeNotConvertible`: The target value's type inside of the `JSON` + /// instance does not match the decoded value. + public func array(path: JSONPathType..., alongPath options: SubscriptingOptions) throws -> [JSON]? { + return try mapOptionalAtPath(path, alongPath: options, transform: JSON.getArray) + } + + /// Optionally decodes many values from a descendant array at a path into + /// JSON. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - parameter alongPath: Options that control what should be done with values that are `null` or keys that are missing. + /// - returns: An `Array` of decoded elements if found, otherwise `nil`. + /// - throws: One of the following errors contained in `JSON.Error`: + /// * `KeyNotFound`: A key `path` does not exist inside a descendant + /// `JSON` dictionary. + /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a + /// descendant `JSON` array. + /// * `UnexpectedSubscript`: A `path` item cannot be used with the + /// corresponding `JSON` value. + /// * `TypeNotConvertible`: The target value's type inside of the `JSON` + /// instance does not match the decoded value. + /// * Any error that arises from decoding the value. + public func arrayOf(path: JSONPathType..., alongPath options: SubscriptingOptions, type: Decoded.Type = Decoded.self) throws -> [Decoded]? { + return try mapOptionalAtPath(path, alongPath: options, transform: JSON.getArrayOf) + } + + /// Optionally retrieves a `[String: JSON]` from a path into the recieving + /// structure. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - parameter alongPath: Options that control what should be done with values that are `null` or keys that are missing. + /// - returns: A `Dictionary` of `String` mapping to `JSON` elements if a + /// value could be found, otherwise `nil`. + /// - throws: One of the following errors contained in `JSON.Error`: + /// * `KeyNotFound`: A key `path` does not exist inside a descendant + /// `JSON` dictionary. + /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a + /// descendant `JSON` array. + /// * `UnexpectedSubscript`: A `path` item cannot be used with the + /// corresponding `JSON` value. + /// * `TypeNotConvertible`: The target value's type inside of the `JSON` + /// instance does not match the decoded value. + public func dictionary(path: JSONPathType..., alongPath options: SubscriptingOptions) throws -> [Swift.String: JSON]? { + return try mapOptionalAtPath(path, alongPath: options, transform: JSON.getDictionary) + } + +} + +// MARK: - Missing-with-fallback unpacking + +extension JSON { + + private func mapOptionalAtPath(path: [JSONPathType], @noescape fallback: () -> Value, @noescape transform: JSON throws -> Value) throws -> Value { + return try mapOptionalAtPath(path, alongPath: .MissingKeyBecomesNil, transform: transform) ?? fallback() + } + + /// Attempts to decode into the returning type from a path into + /// JSON, or returns a fallback if not found. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - parameter fallback: Value to use when one is missing at the subscript. + /// - returns: An initialized member from the inner JSON. + /// - throws: One of the following errors contained in `JSON.Error`: + /// * `UnexpectedSubscript`: A given subscript cannot be used with the + /// corresponding `JSON` value. + /// * `TypeNotConvertible`: The target value's type inside of + /// the `JSON` instance does not match `Decoded`. + public func decode(path: JSONPathType..., @autoclosure or fallback: () -> Decoded) throws -> Decoded { + return try mapOptionalAtPath(path, fallback: fallback, transform: Decoded.init) + } + + /// Retrieves a `Double` from a path into JSON or a fallback if not found. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - parameter fallback: Array to use when one is missing at the subscript. + /// - returns: A floating-point `Double` + /// - throws: One of the `JSON.Error` cases thrown by calling `mapOptionalAtPath(_:fallback:transform:)`. + /// - seealso: `optionalAtPath(_:ifNotFound)`. + public func double(path: JSONPathType..., @autoclosure or fallback: () -> Swift.Double) throws -> Swift.Double { + return try mapOptionalAtPath(path, fallback: fallback, transform: Swift.Double.init) + } + + /// Retrieves an `Int` from a path into JSON or a fallback if not found. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - parameter fallback: Array to use when one is missing at the subscript. + /// - returns: A numeric `Int` + /// - throws: One of the following errors contained in `JSON.Error`: + /// * `KeyNotFound`: A key `path` does not exist inside a descendant + /// `JSON` dictionary. + /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a + /// descendant `JSON` array. + /// * `UnexpectedSubscript`: A `path` item cannot be used with the + /// corresponding `JSON` value. + /// * `TypeNotConvertible`: The target value's type inside of the `JSON` + /// instance does not match the decoded value. + public func int(path: JSONPathType..., @autoclosure or fallback: () -> Swift.Int) throws -> Swift.Int { + return try mapOptionalAtPath(path, fallback: fallback, transform: Swift.Int.init) + } + + /// Retrieves a `String` from a path into JSON or a fallback if not found. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - parameter fallback: Array to use when one is missing at the subscript. + /// - returns: A textual `String` + /// - throws: One of the following errors contained in `JSON.Error`: + /// * `KeyNotFound`: A key `path` does not exist inside a descendant + /// `JSON` dictionary. + /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a + /// descendant `JSON` array. + /// * `UnexpectedSubscript`: A `path` item cannot be used with the + /// corresponding `JSON` value. + /// * `TypeNotConvertible`: The target value's type inside of the `JSON` + /// instance does not match the decoded value. + public func string(path: JSONPathType..., @autoclosure or fallback: () -> Swift.String) throws -> Swift.String { + return try mapOptionalAtPath(path, fallback: fallback, transform: Swift.String.init) + } + + /// Retrieves a `Bool` from a path into JSON or a fallback if not found. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - parameter fallback: Array to use when one is missing at the subscript. + /// - returns: A truthy `Bool` + /// - throws: One of the following errors contained in `JSON.Error`: + /// * `KeyNotFound`: A key `path` does not exist inside a descendant + /// `JSON` dictionary. + /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a + /// descendant `JSON` array. + /// * `UnexpectedSubscript`: A `path` item cannot be used with the + /// corresponding `JSON` value. + /// * `TypeNotConvertible`: The target value's type inside of the `JSON` + /// instance does not match the decoded value. + public func bool(path: JSONPathType..., @autoclosure or fallback: () -> Swift.Bool) throws -> Swift.Bool { + return try mapOptionalAtPath(path, fallback: fallback, transform: Swift.Bool.init) + } + + /// Retrieves a `[JSON]` from a path into JSON or a fallback if not found. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - parameter fallback: Array to use when one is missing at the subscript. + /// - returns: An `Array` of `JSON` elements + /// - throws: One of the following errors contained in `JSON.Error`: + /// * `KeyNotFound`: A key `path` does not exist inside a descendant + /// `JSON` dictionary. + /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a + /// descendant `JSON` array. + /// * `UnexpectedSubscript`: A `path` item cannot be used with the + /// corresponding `JSON` value. + /// * `TypeNotConvertible`: The target value's type inside of the `JSON` + /// instance does not match the decoded value. + public func array(path: JSONPathType..., @autoclosure or fallback: () -> [JSON]) throws -> [JSON] { + return try mapOptionalAtPath(path, fallback: fallback, transform: JSON.getArray) + } + + /// Attempts to decodes many values from a desendant JSON array at a path + /// into the recieving structure, returning a fallback if not found. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - parameter fallback: Array to use when one is missing at the subscript. + /// - returns: An `Array` of decoded elements + /// - throws: One of the following errors contained in `JSON.Error`: + /// * `KeyNotFound`: A key `path` does not exist inside a descendant + /// `JSON` dictionary. + /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a + /// descendant `JSON` array. + /// * `UnexpectedSubscript`: A `path` item cannot be used with the + /// corresponding `JSON` value. + /// * `TypeNotConvertible`: The target value's type inside of the `JSON` + /// instance does not match the decoded value. + /// * Any error that arises from decoding the value. + public func arrayOf(path: JSONPathType..., @autoclosure or fallback: () -> [Decoded]) throws -> [Decoded] { + return try mapOptionalAtPath(path, fallback: fallback, transform: JSON.getArrayOf) + } + + /// Retrieves a `[String: JSON]` from a path into JSON or a fallback if not + /// found. + /// - parameter path: 0 or more `String` or `Int` that subscript the `JSON` + /// - parameter fallback: Value to use when one is missing at the subscript + /// - returns: An `Dictionary` of `String` mapping to `JSON` elements + /// - throws: One of the following errors contained in `JSON.Error`: + /// * `KeyNotFound`: A key `path` does not exist inside a descendant + /// `JSON` dictionary. + /// * `IndexOutOfBounds`: An index `path` is outside the bounds of a + /// descendant `JSON` array. + /// * `UnexpectedSubscript`: A `path` item cannot be used with the + /// corresponding `JSON` value. + /// * `TypeNotConvertible`: The target value's type inside of the `JSON` + /// instance does not match the decoded value. + public func dictionary(path: JSONPathType..., @autoclosure or fallback: () -> [Swift.String: JSON]) throws -> [Swift.String: JSON] { + return try mapOptionalAtPath(path, fallback: fallback, transform: JSON.getDictionary) + } + +} + +// MARK: - Deprecated methods + +extension JSON { + + @available(*, deprecated, message="Use 'decode(_:alongPath:type:)' with options '[.MissingKeyBecomesNil]'") + public func decode(path: JSONPathType..., ifNotFound: Swift.Bool, type: Decoded.Type = Decoded.self) throws -> Decoded? { + let options: SubscriptingOptions = ifNotFound ? [.MissingKeyBecomesNil] : [] + return try mapOptionalAtPath(path, alongPath: options, transform: Decoded.init) + } + + @available(*, deprecated, message="Use 'decode(_:alongPath:type:)' with options '[.NullBecomesNil]'") + public func decode(path: JSONPathType..., ifNull: Swift.Bool, type: Decoded.Type = Decoded.self) throws -> Decoded? { + let options: SubscriptingOptions = ifNull ? [.NullBecomesNil] : [] + return try mapOptionalAtPath(path, alongPath: options, transform: Decoded.init) + } + + @available(*, deprecated, message="Use 'double(_:alongPath:)' with options '[.MissingKeyBecomesNil]'") + public func double(path: JSONPathType..., ifNotFound: Swift.Bool) throws -> Swift.Double? { + let options: SubscriptingOptions = ifNotFound ? [.MissingKeyBecomesNil] : [] + return try mapOptionalAtPath(path, alongPath: options, transform: Swift.Double.init) + } + + @available(*, deprecated, message="Use 'double(_:alongPath:)' with options '[.NullBecomesNil]'") + public func double(path: JSONPathType..., ifNull: Swift.Bool) throws -> Swift.Double? { + let options: SubscriptingOptions = ifNull ? [.NullBecomesNil] : [] + return try mapOptionalAtPath(path, alongPath: options, transform: Swift.Double.init) + } + + @available(*, deprecated, message="Use 'int(_:alongPath:)' with options '[.MissingKeyBecomesNil]'") + public func int(path: JSONPathType..., ifNotFound: Swift.Bool) throws -> Swift.Int? { + let options: SubscriptingOptions = ifNotFound ? [.MissingKeyBecomesNil] : [] + return try mapOptionalAtPath(path, alongPath: options, transform: Swift.Int.init) + } + + @available(*, deprecated, message="Use 'int(_:alongPath:)' with options '[.NullBecomesNil]'") + public func int(path: JSONPathType..., ifNull: Swift.Bool) throws -> Swift.Int? { + let options: SubscriptingOptions = ifNull ? [.NullBecomesNil] : [] + return try mapOptionalAtPath(path, alongPath: options, transform: Swift.Int.init) + } + + @available(*, deprecated, message="Use 'string(_:alongPath:)' with options '[.MissingKeyBecomesNil]'") + public func string(path: JSONPathType..., ifNotFound: Swift.Bool) throws -> Swift.String? { + let options: SubscriptingOptions = ifNotFound ? [.MissingKeyBecomesNil] : [] + return try mapOptionalAtPath(path, alongPath: options, transform: Swift.String.init) + } + + @available(*, deprecated, message="Use 'string(_:alongPath:)' with options '[.NullBecomesNil]'") + public func string(path: JSONPathType..., ifNull: Swift.Bool) throws -> Swift.String? { + let options: SubscriptingOptions = ifNull ? [.NullBecomesNil] : [] + return try mapOptionalAtPath(path, alongPath: options, transform: Swift.String.init) + } + + @available(*, deprecated, message="Use 'bool(_:alongPath:)' with options '[.MissingKeyBecomesNil]'") + public func bool(path: JSONPathType..., ifNotFound: Swift.Bool) throws -> Swift.Bool? { + let options: SubscriptingOptions = ifNotFound ? [.MissingKeyBecomesNil] : [] + return try mapOptionalAtPath(path, alongPath: options, transform: Swift.Bool.init) + } + + @available(*, deprecated, message="Use 'bool(_:alongPath:)' with options '[.NullBecomesNil]'") + public func bool(path: JSONPathType..., ifNull: Swift.Bool) throws -> Swift.Bool? { + let options: SubscriptingOptions = ifNull ? [.NullBecomesNil] : [] + return try mapOptionalAtPath(path, alongPath: options, transform: Swift.Bool.init) + } + + @available(*, deprecated, message="Use 'array(_:alongPath:)' with options '[.MissingKeyBecomesNil]'") + public func array(path: JSONPathType..., ifNotFound: Swift.Bool) throws -> [JSON]? { + let options: SubscriptingOptions = ifNotFound ? [.MissingKeyBecomesNil] : [] + return try mapOptionalAtPath(path, alongPath: options, transform: JSON.getArray) + } + + @available(*, deprecated, message="Use 'array(_:alongPath:)' with options '[.NullBecomesNil]'") + public func array(path: JSONPathType..., ifNull: Swift.Bool) throws -> [JSON]? { + let options: SubscriptingOptions = ifNull ? [.NullBecomesNil] : [] + return try mapOptionalAtPath(path, alongPath: options, transform: JSON.getArray) + } + + @available(*, deprecated, message="Use 'arrayOf(_:alongPath:)' with options '[.MissingKeyBecomesNil]'") + public func arrayOf(path: JSONPathType..., ifNotFound: Swift.Bool) throws -> [Decoded]? { + let options: SubscriptingOptions = ifNotFound ? [.MissingKeyBecomesNil] : [] + return try mapOptionalAtPath(path, alongPath: options, transform: JSON.getArrayOf) + } + + @available(*, deprecated, message="Use 'arrayOf(_:alongPath:)' with options '[.NullBecomesNil]'") + public func arrayOf(path: JSONPathType..., ifNull: Swift.Bool) throws -> [Decoded]? { + let options: SubscriptingOptions = ifNull ? [.NullBecomesNil] : [] + return try mapOptionalAtPath(path, alongPath: options, transform: JSON.getArrayOf) + } + + @available(*, deprecated, message="Use 'dictionary(_:alongPath:)' with options '[.MissingKeyBecomesNil]'") + public func dictionary(path: JSONPathType..., ifNotFound: Swift.Bool) throws -> [Swift.String: JSON]? { + let options: SubscriptingOptions = ifNotFound ? [.MissingKeyBecomesNil] : [] + return try mapOptionalAtPath(path, alongPath: options, transform: JSON.getDictionary) + } + + @available(*, deprecated, message="Use 'dictionary(_:alongPath:)' with options '[.NullBecomesNil]'") + public func dictionary(path: JSONPathType..., ifNull: Swift.Bool) throws -> [Swift.String: JSON]? { + let options: SubscriptingOptions = ifNull ? [.NullBecomesNil] : [] + return try mapOptionalAtPath(path, alongPath: options, transform: JSON.getDictionary) + } + +} diff --git a/Pods/Local Podspecs/Astro.podspec.json b/Pods/Local Podspecs/Astro.podspec.json new file mode 100644 index 0000000..3dd7ea2 --- /dev/null +++ b/Pods/Local Podspecs/Astro.podspec.json @@ -0,0 +1,66 @@ +{ + "name": "Astro", + "version": "0.8.7", + "summary": "A RoboPod containing a small collection of utilities for project reuse", + "homepage": "https://RobotsAndPencils.com", + "license": { + "type": "MIT", + "text": "Copyright (c) 2015 Robots and Pencils, Inc. All rights reserved.\nPermission 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:\nNeither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. \nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\nTHE 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.\n" + }, + "authors": { + "Chad Sykes": "Chad.Sykes@RobotsAndPencils.com", + "Colin Gislason": "Colin.Gislason@RobotsAndPencils.com", + "Dominic Pepin": "Dominic.Pepin@RobotsAndPencils.com", + "Michael Beaureguard": "Michael.Beauregard@RobotsAndPencils.com" + }, + "source": { + "git": "git@github.com:RobotsAndPencils/Astro.git", + "tag": "0.8.7" + }, + "platforms": { + "ios": "8.0" + }, + "requires_arc": true, + "subspecs": [ + { + "name": "Logging", + "source_files": "Astro/Logging/**/*.swift" + }, + { + "name": "Networking", + "source_files": "Astro/Networking/**/*.swift", + "dependencies": { + "Astro/Logging": [ + + ], + "Alamofire": [ + "~> 3.3" + ], + "Freddy": [ + "~> 2.0" + ], + "SwiftTask": [ + "5.0" + ] + } + }, + { + "name": "Security", + "source_files": "Astro/Security/**/*.swift", + "dependencies": { + "Astro/Logging": [ + + ] + } + }, + { + "name": "UI", + "source_files": "Astro/UI/**/*.swift", + "frameworks": "UIKit" + }, + { + "name": "Utils", + "source_files": "Astro/Utils/**/*.swift" + } + ] +} diff --git a/Pods/Manifest.lock b/Pods/Manifest.lock new file mode 100644 index 0000000..0df7efb --- /dev/null +++ b/Pods/Manifest.lock @@ -0,0 +1,46 @@ +PODS: + - Alamofire (3.4.1) + - Astro (0.8.7): + - Astro/Logging (= 0.8.7) + - Astro/Networking (= 0.8.7) + - Astro/Security (= 0.8.7) + - Astro/UI (= 0.8.7) + - Astro/Utils (= 0.8.7) + - Astro/Logging (0.8.7) + - Astro/Networking (0.8.7): + - Alamofire (~> 3.3) + - Astro/Logging + - Freddy (~> 2.0) + - SwiftTask (= 5.0) + - Astro/Security (0.8.7): + - Astro/Logging + - Astro/UI (0.8.7) + - Astro/Utils (0.8.7) + - Freddy (2.1.0) + - Nimble (3.2.0) + - Nocilla (0.11.0) + - Quick (0.9.3) + - SwiftTask (5.0.0) + +DEPENDENCIES: + - Astro (from `.`) + - Nimble (~> 3.2) + - Nocilla (~> 0.10) + - Quick (~> 0.9) + +EXTERNAL SOURCES: + Astro: + :path: . + +SPEC CHECKSUMS: + Alamofire: 01a82e2f6c0f860ade35534c8dd88be61bdef40c + Astro: f82a0d1983abf285fdddb40017cdd72a5ac1fea7 + Freddy: bbdca013977db29638b24baf6572ce94452bec29 + Nimble: 703854335d181df169bbca9c97117b5cf8c47c1d + Nocilla: 7af7a386071150cc8aa5da4da97d060f049dd61c + Quick: 13a2a2b19a5d8e3ed4fd0c36ee46597fd77ebf71 + SwiftTask: 7fcd92f8ac16876e82c0e4ced0cea7e028456b6b + +PODFILE CHECKSUM: bc9ce865bd684a337e5df1b14f2a1427f0613efa + +COCOAPODS: 1.0.1 diff --git a/Pods/Nimble/LICENSE.md b/Pods/Nimble/LICENSE.md new file mode 100644 index 0000000..0f3eb71 --- /dev/null +++ b/Pods/Nimble/LICENSE.md @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2014 Quick Team + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Pods/Nimble/README.md b/Pods/Nimble/README.md new file mode 100644 index 0000000..e6f9e9f --- /dev/null +++ b/Pods/Nimble/README.md @@ -0,0 +1,1217 @@ +# Nimble + +Use Nimble to express the expected outcomes of Swift +or Objective-C expressions. Inspired by +[Cedar](https://github.com/pivotal/cedar). + +```swift +// Swift + +expect(1 + 1).to(equal(2)) +expect(1.2).to(beCloseTo(1.1, within: 0.1)) +expect(3) > 2 +expect("seahorse").to(contain("sea")) +expect(["Atlantic", "Pacific"]).toNot(contain("Mississippi")) +expect(ocean.isClean).toEventually(beTruthy()) +``` + +# How to Use Nimble + + + +**Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)* + +- [Some Background: Expressing Outcomes Using Assertions in XCTest](#some-background-expressing-outcomes-using-assertions-in-xctest) +- [Nimble: Expectations Using `expect(...).to`](#nimble-expectations-using-expectto) + - [Custom Failure Messages](#custom-failure-messages) + - [Type Checking](#type-checking) + - [Operator Overloads](#operator-overloads) + - [Lazily Computed Values](#lazily-computed-values) + - [C Primitives](#c-primitives) + - [Asynchronous Expectations](#asynchronous-expectations) + - [Objective-C Support](#objective-c-support) + - [Disabling Objective-C Shorthand](#disabling-objective-c-shorthand) +- [Built-in Matcher Functions](#built-in-matcher-functions) + - [Equivalence](#equivalence) + - [Identity](#identity) + - [Comparisons](#comparisons) + - [Types/Classes](#typesclasses) + - [Truthiness](#truthiness) + - [Swift Error Handling](#swift-error-handling) + - [Exceptions](#exceptions) + - [Collection Membership](#collection-membership) + - [Strings](#strings) + - [Checking if all elements of a collection pass a condition](#checking-if-all-elements-of-a-collection-pass-a-condition) + - [Verify collection count](#verify-collection-count) + - [Matching a value to any of a group of matchers](#matching-a-value-to-any-of-a-group-of-matchers) +- [Writing Your Own Matchers](#writing-your-own-matchers) + - [Lazy Evaluation](#lazy-evaluation) + - [Type Checking via Swift Generics](#type-checking-via-swift-generics) + - [Customizing Failure Messages](#customizing-failure-messages) + - [Supporting Objective-C](#supporting-objective-c) + - [Properly Handling `nil` in Objective-C Matchers](#properly-handling-nil-in-objective-c-matchers) +- [Installing Nimble](#installing-nimble) + - [Installing Nimble as a Submodule](#installing-nimble-as-a-submodule) + - [Installing Nimble via CocoaPods](#installing-nimble-via-cocoapods) + - [Using Nimble without XCTest](#using-nimble-without-xctest) + + + +# Some Background: Expressing Outcomes Using Assertions in XCTest + +Apple's Xcode includes the XCTest framework, which provides +assertion macros to test whether code behaves properly. +For example, to assert that `1 + 1 = 2`, XCTest has you write: + +```swift +// Swift + +XCTAssertEqual(1 + 1, 2, "expected one plus one to equal two") +``` + +Or, in Objective-C: + +```objc +// Objective-C + +XCTAssertEqual(1 + 1, 2, @"expected one plus one to equal two"); +``` + +XCTest assertions have a couple of drawbacks: + +1. **Not enough macros.** There's no easy way to assert that a string + contains a particular substring, or that a number is less than or + equal to another. +2. **It's hard to write asynchronous tests.** XCTest forces you to write + a lot of boilerplate code. + +Nimble addresses these concerns. + +# Nimble: Expectations Using `expect(...).to` + +Nimble allows you to express expectations using a natural, +easily understood language: + +```swift +// Swift + +import Nimble + +expect(seagull.squawk).to(equal("Squee!")) +``` + +```objc +// Objective-C + +@import Nimble; + +expect(seagull.squawk).to(equal(@"Squee!")); +``` + +> The `expect` function autocompletes to include `file:` and `line:`, + but these parameters are optional. Use the default values to have + Xcode highlight the correct line when an expectation is not met. + +To perform the opposite expectation--to assert something is *not* +equal--use `toNot` or `notTo`: + +```swift +// Swift + +import Nimble + +expect(seagull.squawk).toNot(equal("Oh, hello there!")) +expect(seagull.squawk).notTo(equal("Oh, hello there!")) +``` + +```objc +// Objective-C + +@import Nimble; + +expect(seagull.squawk).toNot(equal(@"Oh, hello there!")); +expect(seagull.squawk).notTo(equal(@"Oh, hello there!")); +``` + +## Custom Failure Messages + +Would you like to add more information to the test's failure messages? Use the `description` optional argument to add your own text: + +```swift +// Swift + +expect(1 + 1).to(equal(3)) +// failed - expected to equal <3>, got <2> + +expect(1 + 1).to(equal(3), description: "Make sure libKindergartenMath is loaded") +// failed - Make sure libKindergartenMath is loaded +// expected to equal <3>, got <2> +``` + +Or the *WithDescription version in Objective-C: + +```objc +// Objective-C + +@import Nimble; + +expect(@(1+1)).to(equal(@3)); +// failed - expected to equal <3.0000>, got <2.0000> + +expect(@(1+1)).toWithDescription(equal(@3), @"Make sure libKindergartenMath is loaded"); +// failed - Make sure libKindergartenMath is loaded +// expected to equal <3.0000>, got <2.0000> +``` + +## Type Checking + +Nimble makes sure you don't compare two types that don't match: + +```swift +// Swift + +// Does not compile: +expect(1 + 1).to(equal("Squee!")) +``` + +> Nimble uses generics--only available in Swift--to ensure + type correctness. That means type checking is + not available when using Nimble in Objective-C. :sob: + +## Operator Overloads + +Tired of so much typing? With Nimble, you can use overloaded operators +like `==` for equivalence, or `>` for comparisons: + +```swift +// Swift + +// Passes if squawk does not equal "Hi!": +expect(seagull.squawk) != "Hi!" + +// Passes if 10 is greater than 2: +expect(10) > 2 +``` + +> Operator overloads are only available in Swift, so you won't be able + to use this syntax in Objective-C. :broken_heart: + +## Lazily Computed Values + +The `expect` function doesn't evaluate the value it's given until it's +time to match. So Nimble can test whether an expression raises an +exception once evaluated: + +```swift +// Swift + +// Note: Swift currently doesn't have exceptions. +// Only Objective-C code can raise exceptions +// that Nimble will catch. +// (see https://github.com/Quick/Nimble/issues/220#issuecomment-172667064) +let exception = NSException( + name: NSInternalInconsistencyException, + reason: "Not enough fish in the sea.", + userInfo: ["something": "is fishy"]) +expect { exception.raise() }.to(raiseException()) + +// Also, you can customize raiseException to be more specific +expect { exception.raise() }.to(raiseException(named: NSInternalInconsistencyException)) +expect { exception.raise() }.to(raiseException( + named: NSInternalInconsistencyException, + reason: "Not enough fish in the sea")) +expect { exception.raise() }.to(raiseException( + named: NSInternalInconsistencyException, + reason: "Not enough fish in the sea", + userInfo: ["something": "is fishy"])) +``` + +Objective-C works the same way, but you must use the `expectAction` +macro when making an expectation on an expression that has no return +value: + +```objc +// Objective-C + +NSException *exception = [NSException exceptionWithName:NSInternalInconsistencyException + reason:@"Not enough fish in the sea." + userInfo:nil]; +expectAction(^{ [exception raise]; }).to(raiseException()); + +// Use the property-block syntax to be more specific. +expectAction(^{ [exception raise]; }).to(raiseException().named(NSInternalInconsistencyException)); +expectAction(^{ [exception raise]; }).to(raiseException(). + named(NSInternalInconsistencyException). + reason("Not enough fish in the sea")); +expectAction(^{ [exception raise]; }).to(raiseException(). + named(NSInternalInconsistencyException). + reason("Not enough fish in the sea"). + userInfo(@{@"something": @"is fishy"})); + +// You can also pass a block for custom matching of the raised exception +expectAction(exception.raise()).to(raiseException().satisfyingBlock(^(NSException *exception) { + expect(exception.name).to(beginWith(NSInternalInconsistencyException)); +})); +``` + +## C Primitives + +Some testing frameworks make it hard to test primitive C values. +In Nimble, it just works: + +```swift +// Swift + +let actual: CInt = 1 +let expectedValue: CInt = 1 +expect(actual).to(equal(expectedValue)) +``` + +In fact, Nimble uses type inference, so you can write the above +without explicitly specifying both types: + +```swift +// Swift + +expect(1 as CInt).to(equal(1)) +``` + +> In Objective-C, Nimble only supports Objective-C objects. To + make expectations on primitive C values, wrap then in an object + literal: + + ```objc + expect(@(1 + 1)).to(equal(@2)); + ``` + +## Asynchronous Expectations + +In Nimble, it's easy to make expectations on values that are updated +asynchronously. Just use `toEventually` or `toEventuallyNot`: + +```swift +// Swift + +dispatch_async(dispatch_get_main_queue()) { + ocean.add("dolphins") + ocean.add("whales") +} +expect(ocean).toEventually(contain("dolphins", "whales")) +``` + + +```objc +// Objective-C +dispatch_async(dispatch_get_main_queue(), ^{ + [ocean add:@"dolphins"]; + [ocean add:@"whales"]; +}); +expect(ocean).toEventually(contain(@"dolphins", @"whales")); +``` + +Note: toEventually triggers its polls on the main thread. Blocking the main +thread will cause Nimble to stop the run loop. This can cause test pollution +for whatever incomplete code that was running on the main thread. Blocking the +main thread can be caused by blocking IO, calls to sleep(), deadlocks, and +synchronous IPC. + +In the above example, `ocean` is constantly re-evaluated. If it ever +contains dolphins and whales, the expectation passes. If `ocean` still +doesn't contain them, even after being continuously re-evaluated for one +whole second, the expectation fails. + +Sometimes it takes more than a second for a value to update. In those +cases, use the `timeout` parameter: + +```swift +// Swift + +// Waits three seconds for ocean to contain "starfish": +expect(ocean).toEventually(contain("starfish"), timeout: 3) +``` + +```objc +// Objective-C + +// Waits three seconds for ocean to contain "starfish": +expect(ocean).withTimeout(3).toEventually(contain(@"starfish")); +``` + +You can also provide a callback by using the `waitUntil` function: + +```swift +// Swift + +waitUntil { done in + // do some stuff that takes a while... + NSThread.sleepForTimeInterval(0.5) + done() +} +``` + +```objc +// Objective-C + +waitUntil(^(void (^done)(void)){ + // do some stuff that takes a while... + [NSThread sleepForTimeInterval:0.5]; + done(); +}); +``` + +`waitUntil` also optionally takes a timeout parameter: + +```swift +// Swift + +waitUntil(timeout: 10) { done in + // do some stuff that takes a while... + NSThread.sleepForTimeInterval(1) + done() +} +``` + +```objc +// Objective-C + +waitUntilTimeout(10, ^(void (^done)(void)){ + // do some stuff that takes a while... + [NSThread sleepForTimeInterval:1]; + done(); +}); +``` + +Note: waitUntil triggers its timeout code on the main thread. Blocking the main +thread will cause Nimble to stop the run loop to continue. This can cause test +pollution for whatever incomplete code that was running on the main thread. +Blocking the main thread can be caused by blocking IO, calls to sleep(), +deadlocks, and synchronous IPC. + +In some cases (e.g. when running on slower machines) it can be useful to modify +the default timeout and poll interval values. This can be done as follows: + +```swift +// Swift + +// Increase the global timeout to 5 seconds: +Nimble.Defaults.AsyncTimeout = 5 + +// Slow the polling interval to 0.1 seconds: +Nimble.Defaults.AsyncPollInterval = 0.1 +``` + +## Objective-C Support + +Nimble has full support for Objective-C. However, there are two things +to keep in mind when using Nimble in Objective-C: + +1. All parameters passed to the `expect` function, as well as matcher + functions like `equal`, must be Objective-C objects: + + ```objc + // Objective-C + + @import Nimble; + + expect(@(1 + 1)).to(equal(@2)); + expect(@"Hello world").to(contain(@"world")); + ``` + +2. To make an expectation on an expression that does not return a value, + such as `-[NSException raise]`, use `expectAction` instead of + `expect`: + + ```objc + // Objective-C + + expectAction(^{ [exception raise]; }).to(raiseException()); + ``` + +## Disabling Objective-C Shorthand + +Nimble provides a shorthand for expressing expectations using the +`expect` function. To disable this shorthand in Objective-C, define the +`NIMBLE_DISABLE_SHORT_SYNTAX` macro somewhere in your code before +importing Nimble: + +```objc +#define NIMBLE_DISABLE_SHORT_SYNTAX 1 + +@import Nimble; + +NMB_expect(^{ return seagull.squawk; }, __FILE__, __LINE__).to(NMB_equal(@"Squee!")); +``` + +> Disabling the shorthand is useful if you're testing functions with + names that conflict with Nimble functions, such as `expect` or + `equal`. If that's not the case, there's no point in disabling the + shorthand. + +# Built-in Matcher Functions + +Nimble includes a wide variety of matcher functions. + +## Equivalence + +```swift +// Swift + +// Passes if actual is equivalent to expected: +expect(actual).to(equal(expected)) +expect(actual) == expected + +// Passes if actual is not equivalent to expected: +expect(actual).toNot(equal(expected)) +expect(actual) != expected +``` + +```objc +// Objective-C + +// Passes if actual is equivalent to expected: +expect(actual).to(equal(expected)) + +// Passes if actual is not equivalent to expected: +expect(actual).toNot(equal(expected)) +``` + +Values must be `Equatable`, `Comparable`, or subclasses of `NSObject`. +`equal` will always fail when used to compare one or more `nil` values. + +## Identity + +```swift +// Swift + +// Passes if actual has the same pointer address as expected: +expect(actual).to(beIdenticalTo(expected)) +expect(actual) === expected + +// Passes if actual does not have the same pointer address as expected: +expect(actual).toNot(beIdenticalTo(expected)) +expect(actual) !== expected +``` + +```objc +// Objective-C + +// Passes if actual has the same pointer address as expected: +expect(actual).to(beIdenticalTo(expected)); + +// Passes if actual does not have the same pointer address as expected: +expect(actual).toNot(beIdenticalTo(expected)); +``` + +## Comparisons + +```swift +// Swift + +expect(actual).to(beLessThan(expected)) +expect(actual) < expected + +expect(actual).to(beLessThanOrEqualTo(expected)) +expect(actual) <= expected + +expect(actual).to(beGreaterThan(expected)) +expect(actual) > expected + +expect(actual).to(beGreaterThanOrEqualTo(expected)) +expect(actual) >= expected +``` + +```objc +// Objective-C + +expect(actual).to(beLessThan(expected)); +expect(actual).to(beLessThanOrEqualTo(expected)); +expect(actual).to(beGreaterThan(expected)); +expect(actual).to(beGreaterThanOrEqualTo(expected)); +``` + +> Values given to the comparison matchers above must implement + `Comparable`. + +Because of how computers represent floating point numbers, assertions +that two floating point numbers be equal will sometimes fail. To express +that two numbers should be close to one another within a certain margin +of error, use `beCloseTo`: + +```swift +// Swift + +expect(actual).to(beCloseTo(expected, within: delta)) +``` + +```objc +// Objective-C + +expect(actual).to(beCloseTo(expected).within(delta)); +``` + +For example, to assert that `10.01` is close to `10`, you can write: + +```swift +// Swift + +expect(10.01).to(beCloseTo(10, within: 0.1)) +``` + +```objc +// Objective-C + +expect(@(10.01)).to(beCloseTo(@10).within(0.1)); +``` + +There is also an operator shortcut available in Swift: + +```swift +// Swift + +expect(actual) ≈ expected +expect(actual) ≈ (expected, delta) + +``` +(Type Option-x to get ≈ on a U.S. keyboard) + +The former version uses the default delta of 0.0001. Here is yet another way to do this: + +```swift +// Swift + +expect(actual) ≈ expected ± delta +expect(actual) == expected ± delta + +``` +(Type Option-Shift-= to get ± on a U.S. keyboard) + +If you are comparing arrays of floating point numbers, you'll find the following useful: + +```swift +// Swift + +expect([0.0, 2.0]) ≈ [0.0001, 2.0001] +expect([0.0, 2.0]).to(beCloseTo([0.1, 2.1], within: 0.1)) + +``` + +> Values given to the `beCloseTo` matcher must be coercable into a + `Double`. + +## Types/Classes + +```swift +// Swift + +// Passes if instance is an instance of aClass: +expect(instance).to(beAnInstanceOf(aClass)) + +// Passes if instance is an instance of aClass or any of its subclasses: +expect(instance).to(beAKindOf(aClass)) +``` + +```objc +// Objective-C + +// Passes if instance is an instance of aClass: +expect(instance).to(beAnInstanceOf(aClass)); + +// Passes if instance is an instance of aClass or any of its subclasses: +expect(instance).to(beAKindOf(aClass)); +``` + +> Instances must be Objective-C objects: subclasses of `NSObject`, + or Swift objects bridged to Objective-C with the `@objc` prefix. + +For example, to assert that `dolphin` is a kind of `Mammal`: + +```swift +// Swift + +expect(dolphin).to(beAKindOf(Mammal)) +``` + +```objc +// Objective-C + +expect(dolphin).to(beAKindOf([Mammal class])); +``` + +> `beAnInstanceOf` uses the `-[NSObject isMemberOfClass:]` method to + test membership. `beAKindOf` uses `-[NSObject isKindOfClass:]`. + +## Truthiness + +```swift +// Passes if actual is not nil, true, or an object with a boolean value of true: +expect(actual).to(beTruthy()) + +// Passes if actual is only true (not nil or an object conforming to BooleanType true): +expect(actual).to(beTrue()) + +// Passes if actual is nil, false, or an object with a boolean value of false: +expect(actual).to(beFalsy()) + +// Passes if actual is only false (not nil or an object conforming to BooleanType false): +expect(actual).to(beFalse()) + +// Passes if actual is nil: +expect(actual).to(beNil()) +``` + +```objc +// Objective-C + +// Passes if actual is not nil, true, or an object with a boolean value of true: +expect(actual).to(beTruthy()); + +// Passes if actual is only true (not nil or an object conforming to BooleanType true): +expect(actual).to(beTrue()); + +// Passes if actual is nil, false, or an object with a boolean value of false: +expect(actual).to(beFalsy()); + +// Passes if actual is only false (not nil or an object conforming to BooleanType false): +expect(actual).to(beFalse()); + +// Passes if actual is nil: +expect(actual).to(beNil()); +``` + +## Swift Error Handling + +If you're using Swift 2.0+, you can use the `throwError` matcher to check if an error is thrown. + +```swift +// Swift + +// Passes if somethingThatThrows() throws an ErrorType: +expect{ try somethingThatThrows() }.to(throwError()) + +// Passes if somethingThatThrows() throws an error with a given domain: +expect{ try somethingThatThrows() }.to(throwError { (error: ErrorType) in + expect(error._domain).to(equal(NSCocoaErrorDomain)) +}) + +// Passes if somethingThatThrows() throws an error with a given case: +expect{ try somethingThatThrows() }.to(throwError(NSCocoaError.PropertyListReadCorruptError)) + +// Passes if somethingThatThrows() throws an error with a given type: +expect{ try somethingThatThrows() }.to(throwError(errorType: MyError.self)) +``` + +Note: This feature is only available in Swift. + +## Exceptions + +```swift +// Swift + +// Passes if actual, when evaluated, raises an exception: +expect(actual).to(raiseException()) + +// Passes if actual raises an exception with the given name: +expect(actual).to(raiseException(named: name)) + +// Passes if actual raises an exception with the given name and reason: +expect(actual).to(raiseException(named: name, reason: reason)) + +// Passes if actual raises an exception and it passes expectations in the block +// (in this case, if name begins with 'a r') +expect { exception.raise() }.to(raiseException { (exception: NSException) in + expect(exception.name).to(beginWith("a r")) +}) +``` + +```objc +// Objective-C + +// Passes if actual, when evaluated, raises an exception: +expect(actual).to(raiseException()) + +// Passes if actual raises an exception with the given name +expect(actual).to(raiseException().named(name)) + +// Passes if actual raises an exception with the given name and reason: +expect(actual).to(raiseException().named(name).reason(reason)) + +// Passes if actual raises an exception and it passes expectations in the block +// (in this case, if name begins with 'a r') +expect(actual).to(raiseException().satisfyingBlock(^(NSException *exception) { + expect(exception.name).to(beginWith(@"a r")); +})); +``` + +Note: Swift currently doesn't have exceptions (see [#220](https://github.com/Quick/Nimble/issues/220#issuecomment-172667064)). Only Objective-C code can raise +exceptions that Nimble will catch. + +## Collection Membership + +```swift +// Swift + +// Passes if all of the expected values are members of actual: +expect(actual).to(contain(expected...)) + +// Passes if actual is an empty collection (it contains no elements): +expect(actual).to(beEmpty()) +``` + +```objc +// Objective-C + +// Passes if expected is a member of actual: +expect(actual).to(contain(expected)); + +// Passes if actual is an empty collection (it contains no elements): +expect(actual).to(beEmpty()); +``` + +> In Swift `contain` takes any number of arguments. The expectation + passes if all of them are members of the collection. In Objective-C, + `contain` only takes one argument [for now](https://github.com/Quick/Nimble/issues/27). + +For example, to assert that a list of sea creature names contains +"dolphin" and "starfish": + +```swift +// Swift + +expect(["whale", "dolphin", "starfish"]).to(contain("dolphin", "starfish")) +``` + +```objc +// Objective-C + +expect(@[@"whale", @"dolphin", @"starfish"]).to(contain(@"dolphin")); +expect(@[@"whale", @"dolphin", @"starfish"]).to(contain(@"starfish")); +``` + +> `contain` and `beEmpty` expect collections to be instances of + `NSArray`, `NSSet`, or a Swift collection composed of `Equatable` elements. + +To test whether a set of elements is present at the beginning or end of +an ordered collection, use `beginWith` and `endWith`: + +```swift +// Swift + +// Passes if the elements in expected appear at the beginning of actual: +expect(actual).to(beginWith(expected...)) + +// Passes if the the elements in expected come at the end of actual: +expect(actual).to(endWith(expected...)) +``` + +```objc +// Objective-C + +// Passes if the elements in expected appear at the beginning of actual: +expect(actual).to(beginWith(expected)); + +// Passes if the the elements in expected come at the end of actual: +expect(actual).to(endWith(expected)); +``` + +> `beginWith` and `endWith` expect collections to be instances of + `NSArray`, or ordered Swift collections composed of `Equatable` + elements. + + Like `contain`, in Objective-C `beginWith` and `endWith` only support + a single argument [for now](https://github.com/Quick/Nimble/issues/27). + +## Strings + +```swift +// Swift + +// Passes if actual contains substring expected: +expect(actual).to(contain(expected)) + +// Passes if actual begins with substring: +expect(actual).to(beginWith(expected)) + +// Passes if actual ends with substring: +expect(actual).to(endWith(expected)) + +// Passes if actual is an empty string, "": +expect(actual).to(beEmpty()) + +// Passes if actual matches the regular expression defined in expected: +expect(actual).to(match(expected)) +``` + +```objc +// Objective-C + +// Passes if actual contains substring expected: +expect(actual).to(contain(expected)); + +// Passes if actual begins with substring: +expect(actual).to(beginWith(expected)); + +// Passes if actual ends with substring: +expect(actual).to(endWith(expected)); + +// Passes if actual is an empty string, "": +expect(actual).to(beEmpty()); + +// Passes if actual matches the regular expression defined in expected: +expect(actual).to(match(expected)) +``` + +## Checking if all elements of a collection pass a condition + +```swift +// Swift + +// with a custom function: +expect([1,2,3,4]).to(allPass({$0 < 5})) + +// with another matcher: +expect([1,2,3,4]).to(allPass(beLessThan(5))) +``` + +```objc +// Objective-C + +expect(@[@1, @2, @3,@4]).to(allPass(beLessThan(@5))); +``` + +For Swift the actual value has to be a SequenceType, e.g. an array, a set or a custom seqence type. + +For Objective-C the actual value has to be a NSFastEnumeration, e.g. NSArray and NSSet, of NSObjects and only the variant which +uses another matcher is available here. + +## Verify collection count + +```swift +// passes if actual collection's count is equal to expected +expect(actual).to(haveCount(expected)) + +// passes if actual collection's count is not equal to expected +expect(actual).notTo(haveCount(expected)) +``` + +```objc +// passes if actual collection's count is equal to expected +expect(actual).to(haveCount(expected)) + +// passes if actual collection's count is not equal to expected +expect(actual).notTo(haveCount(expected)) +``` + +For Swift the actual value must be a `CollectionType` such as array, dictionary or set. + +For Objective-C the actual value has to be one of the following classes `NSArray`, `NSDictionary`, `NSSet`, `NSHashTable` or one of their subclasses. + +## Matching a value to any of a group of matchers + +```swift +// passes if actual is either less than 10 or greater than 20 +expect(actual).to(satisfyAnyOf(beLessThan(10), beGreaterThan(20))) + +// can include any number of matchers -- the following will pass +// **be careful** -- too many matchers can be the sign of an unfocused test +expect(6).to(satisfyAnyOf(equal(2), equal(3), equal(4), equal(5), equal(6), equal(7))) + +// in Swift you also have the option to use the || operator to achieve a similar function +expect(82).to(beLessThan(50) || beGreaterThan(80)) +``` + +```objc +// passes if actual is either less than 10 or greater than 20 +expect(actual).to(satisfyAnyOf(beLessThan(@10), beGreaterThan(@20))) + +// can include any number of matchers -- the following will pass +// **be careful** -- too many matchers can be the sign of an unfocused test +expect(@6).to(satisfyAnyOf(equal(@2), equal(@3), equal(@4), equal(@5), equal(@6), equal(@7))) +``` + +Note: This matcher allows you to chain any number of matchers together. This provides flexibility, + but if you find yourself chaining many matchers together in one test, consider whether you + could instead refactor that single test into multiple, more precisely focused tests for + better coverage. + +# Writing Your Own Matchers + +In Nimble, matchers are Swift functions that take an expected +value and return a `MatcherFunc` closure. Take `equal`, for example: + +```swift +// Swift + +public func equal(expectedValue: T?) -> MatcherFunc { + return MatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "equal <\(expectedValue)>" + return actualExpression.evaluate() == expectedValue + } +} +``` + +The return value of a `MatcherFunc` closure is a `Bool` that indicates +whether the actual value matches the expectation: `true` if it does, or +`false` if it doesn't. + +> The actual `equal` matcher function does not match when either + `actual` or `expected` are nil; the example above has been edited for + brevity. + +Since matchers are just Swift functions, you can define them anywhere: +at the top of your test file, in a file shared by all of your tests, or +in an Xcode project you distribute to others. + +> If you write a matcher you think everyone can use, consider adding it + to Nimble's built-in set of matchers by sending a pull request! Or + distribute it yourself via GitHub. + +For examples of how to write your own matchers, just check out the +[`Matchers` directory](https://github.com/Quick/Nimble/tree/master/Nimble/Matchers) +to see how Nimble's built-in set of matchers are implemented. You can +also check out the tips below. + +## Lazy Evaluation + +`actualExpression` is a lazy, memoized closure around the value provided to the +`expect` function. The expression can either be a closure or a value directly +passed to `expect(...)`. In order to determine whether that value matches, +custom matchers should call `actualExpression.evaluate()`: + +```swift +// Swift + +public func beNil() -> MatcherFunc { + return MatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be nil" + return actualExpression.evaluate() == nil + } +} +``` + +In the above example, `actualExpression` is not `nil`--it is a closure +that returns a value. The value it returns, which is accessed via the +`evaluate()` method, may be `nil`. If that value is `nil`, the `beNil` +matcher function returns `true`, indicating that the expectation passed. + +Use `expression.isClosure` to determine if the expression will be invoking +a closure to produce its value. + +## Type Checking via Swift Generics + +Using Swift's generics, matchers can constrain the type of the actual value +passed to the `expect` function by modifying the return type. + +For example, the following matcher, `haveDescription`, only accepts actual +values that implement the `Printable` protocol. It checks their `description` +against the one provided to the matcher function, and passes if they are the same: + +```swift +// Swift + +public func haveDescription(description: String) -> MatcherFunc { + return MatcherFunc { actual, failureMessage in + return actual.evaluate().description == description + } +} +``` + +## Customizing Failure Messages + +By default, Nimble outputs the following failure message when an +expectation fails: + +``` +expected to match, got <\(actual)> +``` + +You can customize this message by modifying the `failureMessage` struct +from within your `MatcherFunc` closure. To change the verb "match" to +something else, update the `postfixMessage` property: + +```swift +// Swift + +// Outputs: expected to be under the sea, got <\(actual)> +failureMessage.postfixMessage = "be under the sea" +``` + +You can change how the `actual` value is displayed by updating +`failureMessage.actualValue`. Or, to remove it altogether, set it to +`nil`: + +```swift +// Swift + +// Outputs: expected to be under the sea +failureMessage.actualValue = nil +failureMessage.postfixMessage = "be under the sea" +``` + +## Supporting Objective-C + +To use a custom matcher written in Swift from Objective-C, you'll have +to extend the `NMBObjCMatcher` class, adding a new class method for your +custom matcher. The example below defines the class method +`+[NMBObjCMatcher beNilMatcher]`: + +```swift +// Swift + +extension NMBObjCMatcher { + public class func beNilMatcher() -> NMBObjCMatcher { + return NMBObjCMatcher { actualBlock, failureMessage, location in + let block = ({ actualBlock() as NSObject? }) + let expr = Expression(expression: block, location: location) + return beNil().matches(expr, failureMessage: failureMessage) + } + } +} +``` + +The above allows you to use the matcher from Objective-C: + +```objc +// Objective-C + +expect(actual).to([NMBObjCMatcher beNilMatcher]()); +``` + +To make the syntax easier to use, define a C function that calls the +class method: + +```objc +// Objective-C + +FOUNDATION_EXPORT id beNil() { + return [NMBObjCMatcher beNilMatcher]; +} +``` + +### Properly Handling `nil` in Objective-C Matchers + +When supporting Objective-C, make sure you handle `nil` appropriately. +Like [Cedar](https://github.com/pivotal/cedar/issues/100), +**most matchers do not match with nil**. This is to bring prevent test +writers from being surprised by `nil` values where they did not expect +them. + +Nimble provides the `beNil` matcher function for test writer that want +to make expectations on `nil` objects: + +```objc +// Objective-C + +expect(nil).to(equal(nil)); // fails +expect(nil).to(beNil()); // passes +``` + +If your matcher does not want to match with nil, you use `NonNilMatcherFunc` +and the `canMatchNil` constructor on `NMBObjCMatcher`. Using both types will +automatically generate expected value failure messages when they're nil. + +```swift + +public func beginWith(startingElement: T) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "begin with <\(startingElement)>" + if let actualValue = actualExpression.evaluate() { + var actualGenerator = actualValue.generate() + return actualGenerator.next() == startingElement + } + return false + } +} + +extension NMBObjCMatcher { + public class func beginWithMatcher(expected: AnyObject) -> NMBObjCMatcher { + return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in + let actual = actualExpression.evaluate() + let expr = actualExpression.cast { $0 as? NMBOrderedCollection } + return beginWith(expected).matches(expr, failureMessage: failureMessage) + } + } +} +``` + +# Installing Nimble + +> Nimble can be used on its own, or in conjunction with its sister + project, [Quick](https://github.com/Quick/Quick). To install both + Quick and Nimble, follow [the installation instructions in the Quick + README](https://github.com/Quick/Quick#how-to-install-quick). + +Nimble can currently be installed in one of two ways: using CocoaPods, or with +git submodules. + +## Installing Nimble as a Submodule + +To use Nimble as a submodule to test your iOS or OS X applications, follow these +4 easy steps: + +1. Clone the Nimble repository +2. Add Nimble.xcodeproj to the Xcode workspace for your project +3. Link Nimble.framework to your test target +4. Start writing expectations! + +For more detailed instructions on each of these steps, +read [How to Install Quick](https://github.com/Quick/Quick#how-to-install-quick). +Ignore the steps involving adding Quick to your project in order to +install just Nimble. + +## Installing Nimble via CocoaPods + +To use Nimble in CocoaPods to test your iOS or OS X applications, add Nimble to +your podfile and add the ```use_frameworks!``` line to enable Swift support for +CocoaPods. + +```ruby +platform :ios, '8.0' + +source 'https://github.com/CocoaPods/Specs.git' + +# Whatever pods you need for your app go here + +target 'YOUR_APP_NAME_HERE_Tests', :exclusive => true do + use_frameworks! + pod 'Nimble', '~> 3.1.0' +end +``` + +Finally run `pod install`. + +## Using Nimble without XCTest + +Nimble is integrated with XCTest to allow it work well when used in Xcode test +bundles, however it can also be used in a standalone app. After installing +Nimble using one of the above methods, there are two additional steps required +to make this work. + +1. Create a custom assertion handler and assign an instance of it to the + global `NimbleAssertionHandler` variable. For example: + +```swift +class MyAssertionHandler : AssertionHandler { + func assert(assertion: Bool, message: FailureMessage, location: SourceLocation) { + if (!assertion) { + print("Expectation failed: \(message.stringValue)") + } + } +} +``` +```swift +// Somewhere before you use any assertions +NimbleAssertionHandler = MyAssertionHandler() +``` + +2. Add a post-build action to fix an issue with the Swift XCTest support + library being unnecessarily copied into your app + * Edit your scheme in Xcode, and navigate to Build -> Post-actions + * Click the "+" icon and select "New Run Script Action" + * Open the "Provide build settings from" dropdown and select your target + * Enter the following script contents: +``` +rm "${SWIFT_STDLIB_TOOL_DESTINATION_DIR}/libswiftXCTest.dylib" +``` + +You can now use Nimble assertions in your code and handle failures as you see +fit. diff --git a/Pods/Nimble/Sources/Nimble/Adapters/AdapterProtocols.swift b/Pods/Nimble/Sources/Nimble/Adapters/AdapterProtocols.swift new file mode 100644 index 0000000..306d4ce --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Adapters/AdapterProtocols.swift @@ -0,0 +1,17 @@ +import Foundation + +/// Protocol for the assertion handler that Nimble uses for all expectations. +public protocol AssertionHandler { + func assert(assertion: Bool, message: FailureMessage, location: SourceLocation) +} + +/// Global backing interface for assertions that Nimble creates. +/// Defaults to a private test handler that passes through to XCTest. +/// +/// If XCTest is not available, you must assign your own assertion handler +/// before using any matchers, otherwise Nimble will abort the program. +/// +/// @see AssertionHandler +public var NimbleAssertionHandler: AssertionHandler = { () -> AssertionHandler in + return isXCTestAvailable() ? NimbleXCTestHandler() : NimbleXCTestUnavailableHandler() +}() diff --git a/Pods/Nimble/Sources/Nimble/Adapters/AssertionDispatcher.swift b/Pods/Nimble/Sources/Nimble/Adapters/AssertionDispatcher.swift new file mode 100644 index 0000000..09caf2a --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Adapters/AssertionDispatcher.swift @@ -0,0 +1,20 @@ + +/// AssertionDispatcher allows multiple AssertionHandlers to receive +/// assertion messages. +/// +/// @warning Does not fully dispatch if one of the handlers raises an exception. +/// This is possible with XCTest-based assertion handlers. +/// +public class AssertionDispatcher: AssertionHandler { + let handlers: [AssertionHandler] + + public init(handlers: [AssertionHandler]) { + self.handlers = handlers + } + + public func assert(assertion: Bool, message: FailureMessage, location: SourceLocation) { + for handler in handlers { + handler.assert(assertion, message: message, location: location) + } + } +} diff --git a/Pods/Nimble/Sources/Nimble/Adapters/AssertionRecorder.swift b/Pods/Nimble/Sources/Nimble/Adapters/AssertionRecorder.swift new file mode 100644 index 0000000..a1615a7 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Adapters/AssertionRecorder.swift @@ -0,0 +1,100 @@ +import Foundation + +/// A data structure that stores information about an assertion when +/// AssertionRecorder is set as the Nimble assertion handler. +/// +/// @see AssertionRecorder +/// @see AssertionHandler +public struct AssertionRecord: CustomStringConvertible { + /// Whether the assertion succeeded or failed + public let success: Bool + /// The failure message the assertion would display on failure. + public let message: FailureMessage + /// The source location the expectation occurred on. + public let location: SourceLocation + + public var description: String { + return "AssertionRecord { success=\(success), message='\(message.stringValue)', location=\(location) }" + } +} + +/// An AssertionHandler that silently records assertions that Nimble makes. +/// This is useful for testing failure messages for matchers. +/// +/// @see AssertionHandler +public class AssertionRecorder : AssertionHandler { + /// All the assertions that were captured by this recorder + public var assertions = [AssertionRecord]() + + public init() {} + + public func assert(assertion: Bool, message: FailureMessage, location: SourceLocation) { + assertions.append( + AssertionRecord( + success: assertion, + message: message, + location: location)) + } +} + +/// Allows you to temporarily replace the current Nimble assertion handler with +/// the one provided for the scope of the closure. +/// +/// Once the closure finishes, then the original Nimble assertion handler is restored. +/// +/// @see AssertionHandler +public func withAssertionHandler(tempAssertionHandler: AssertionHandler, closure: () throws -> Void) { + let environment = NimbleEnvironment.activeInstance + let oldRecorder = environment.assertionHandler + let capturer = NMBExceptionCapture(handler: nil, finally: ({ + environment.assertionHandler = oldRecorder + })) + environment.assertionHandler = tempAssertionHandler + capturer.tryBlock { + try! closure() + } +} + +/// Captures expectations that occur in the given closure. Note that all +/// expectations will still go through to the default Nimble handler. +/// +/// This can be useful if you want to gather information about expectations +/// that occur within a closure. +/// +/// @param silently expectations are no longer send to the default Nimble +/// assertion handler when this is true. Defaults to false. +/// +/// @see gatherFailingExpectations +public func gatherExpectations(silently silently: Bool = false, closure: () -> Void) -> [AssertionRecord] { + let previousRecorder = NimbleEnvironment.activeInstance.assertionHandler + let recorder = AssertionRecorder() + let handlers: [AssertionHandler] + + if silently { + handlers = [recorder] + } else { + handlers = [recorder, previousRecorder] + } + + let dispatcher = AssertionDispatcher(handlers: handlers) + withAssertionHandler(dispatcher, closure: closure) + return recorder.assertions +} + +/// Captures failed expectations that occur in the given closure. Note that all +/// expectations will still go through to the default Nimble handler. +/// +/// This can be useful if you want to gather information about failed +/// expectations that occur within a closure. +/// +/// @param silently expectations are no longer send to the default Nimble +/// assertion handler when this is true. Defaults to false. +/// +/// @see gatherExpectations +/// @see raiseException source for an example use case. +public func gatherFailingExpectations(silently silently: Bool = false, closure: () -> Void) -> [AssertionRecord] { + let assertions = gatherExpectations(silently: silently, closure: closure) + return assertions.filter { assertion in + !assertion.success + } +} diff --git a/Pods/Nimble/Sources/Nimble/Adapters/NimbleEnvironment.swift b/Pods/Nimble/Sources/Nimble/Adapters/NimbleEnvironment.swift new file mode 100644 index 0000000..27cdac9 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Adapters/NimbleEnvironment.swift @@ -0,0 +1,38 @@ +import Foundation + +/// "Global" state of Nimble is stored here. Only DSL functions should access / be aware of this +/// class' existance +internal class NimbleEnvironment { + static var activeInstance: NimbleEnvironment { + get { + let env = NSThread.currentThread().threadDictionary["NimbleEnvironment"] + if let env = env as? NimbleEnvironment { + return env + } else { + let newEnv = NimbleEnvironment() + self.activeInstance = newEnv + return newEnv + } + } + set { + NSThread.currentThread().threadDictionary["NimbleEnvironment"] = newValue + } + } + + // TODO: eventually migrate the global to this environment value + var assertionHandler: AssertionHandler { + get { return NimbleAssertionHandler } + set { NimbleAssertionHandler = newValue } + } + +#if _runtime(_ObjC) + var awaiter: Awaiter + + init() { + awaiter = Awaiter( + waitLock: AssertionWaitLock(), + asyncQueue: dispatch_get_main_queue(), + timeoutQueue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) + } +#endif +} diff --git a/Pods/Nimble/Sources/Nimble/Adapters/NimbleXCTestHandler.swift b/Pods/Nimble/Sources/Nimble/Adapters/NimbleXCTestHandler.swift new file mode 100644 index 0000000..7d84f45 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Adapters/NimbleXCTestHandler.swift @@ -0,0 +1,77 @@ +import Foundation +import XCTest + +/// Default handler for Nimble. This assertion handler passes failures along to +/// XCTest. +public class NimbleXCTestHandler : AssertionHandler { + public func assert(assertion: Bool, message: FailureMessage, location: SourceLocation) { + if !assertion { + recordFailure("\(message.stringValue)\n", location: location) + } + } +} + +/// Alternative handler for Nimble. This assertion handler passes failures along +/// to XCTest by attempting to reduce the failure message size. +public class NimbleShortXCTestHandler: AssertionHandler { + public func assert(assertion: Bool, message: FailureMessage, location: SourceLocation) { + if !assertion { + let msg: String + if let actual = message.actualValue { + msg = "got: \(actual) \(message.postfixActual)" + } else { + msg = "expected \(message.to) \(message.postfixMessage)" + } + recordFailure("\(msg)\n", location: location) + } + } +} + +/// Fallback handler in case XCTest is unavailable. This assertion handler will abort +/// the program if it is invoked. +class NimbleXCTestUnavailableHandler : AssertionHandler { + func assert(assertion: Bool, message: FailureMessage, location: SourceLocation) { + fatalError("XCTest is not available and no custom assertion handler was configured. Aborting.") + } +} + +#if _runtime(_ObjC) + /// Helper class providing access to the currently executing XCTestCase instance, if any +@objc final internal class CurrentTestCaseTracker: NSObject, XCTestObservation { + @objc static let sharedInstance = CurrentTestCaseTracker() + + private(set) var currentTestCase: XCTestCase? + + @objc func testCaseWillStart(testCase: XCTestCase) { + currentTestCase = testCase + } + + @objc func testCaseDidFinish(testCase: XCTestCase) { + currentTestCase = nil + } +} +#endif + + +func isXCTestAvailable() -> Bool { +#if _runtime(_ObjC) + // XCTest is weakly linked and so may not be present + return NSClassFromString("XCTestCase") != nil +#else + return true +#endif +} + +private func recordFailure(message: String, location: SourceLocation) { +#if _runtime(_ObjC) + if let testCase = CurrentTestCaseTracker.sharedInstance.currentTestCase { + testCase.recordFailureWithDescription(message, inFile: location.file, atLine: location.line, expected: true) + } else { + let msg = "Attempted to report a test failure to XCTest while no test case was running. " + + "The failure was:\n\"\(message)\"\nIt occurred at: \(location.file):\(location.line)" + NSException(name: NSInternalInconsistencyException, reason: msg, userInfo: nil).raise() + } +#else + XCTFail("\(message)\n", file: location.file, line: location.line) +#endif +} diff --git a/Pods/Nimble/Sources/Nimble/DSL+Wait.swift b/Pods/Nimble/Sources/Nimble/DSL+Wait.swift new file mode 100644 index 0000000..63495c2 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/DSL+Wait.swift @@ -0,0 +1,93 @@ +import Foundation + +#if _runtime(_ObjC) +private enum ErrorResult { + case Exception(NSException) + case Error(ErrorType) + case None +} + +/// Only classes, protocols, methods, properties, and subscript declarations can be +/// bridges to Objective-C via the @objc keyword. This class encapsulates callback-style +/// asynchronous waiting logic so that it may be called from Objective-C and Swift. +internal class NMBWait: NSObject { + internal class func until( + timeout timeout: NSTimeInterval, + file: FileString = __FILE__, + line: UInt = __LINE__, + action: (() -> Void) -> Void) -> Void { + return throwableUntil(timeout: timeout, file: file, line: line) { (done: () -> Void) throws -> Void in + action() { done() } + } + } + + // Using a throwable closure makes this method not objc compatible. + internal class func throwableUntil( + timeout timeout: NSTimeInterval, + file: FileString = __FILE__, + line: UInt = __LINE__, + action: (() -> Void) throws -> Void) -> Void { + let awaiter = NimbleEnvironment.activeInstance.awaiter + let leeway = timeout / 2.0 + let result = awaiter.performBlock { (done: (ErrorResult) -> Void) throws -> Void in + dispatch_async(dispatch_get_main_queue()) { + let capture = NMBExceptionCapture( + handler: ({ exception in + done(.Exception(exception)) + }), + finally: ({ }) + ) + capture.tryBlock { + do { + try action() { + done(.None) + } + } catch let e { + done(.Error(e)) + } + } + } + }.timeout(timeout, forcefullyAbortTimeout: leeway).wait("waitUntil(...)", file: file, line: line) + + switch result { + case .Incomplete: internalError("Reached .Incomplete state for waitUntil(...).") + case .BlockedRunLoop: + fail(blockedRunLoopErrorMessageFor("-waitUntil()", leeway: leeway), + file: file, line: line) + case .TimedOut: + let pluralize = (timeout == 1 ? "" : "s") + fail("Waited more than \(timeout) second\(pluralize)", file: file, line: line) + case let .RaisedException(exception): + fail("Unexpected exception raised: \(exception)") + case let .ErrorThrown(error): + fail("Unexpected error thrown: \(error)") + case .Completed(.Exception(let exception)): + fail("Unexpected exception raised: \(exception)") + case .Completed(.Error(let error)): + fail("Unexpected error thrown: \(error)") + case .Completed(.None): // success + break + } + } + + @objc(untilFile:line:action:) + internal class func until(file: FileString = __FILE__, line: UInt = __LINE__, action: (() -> Void) -> Void) -> Void { + until(timeout: 1, file: file, line: line, action: action) + } +} + +internal func blockedRunLoopErrorMessageFor(fnName: String, leeway: NSTimeInterval) -> String { + return "\(fnName) timed out but was unable to run the timeout handler because the main thread is unresponsive (\(leeway) seconds is allow after the wait times out). Conditions that may cause this include processing blocking IO on the main thread, calls to sleep(), deadlocks, and synchronous IPC. Nimble forcefully stopped run loop which may cause future failures in test run." +} + +/// Wait asynchronously until the done closure is called or the timeout has been reached. +/// +/// @discussion +/// Call the done() closure to indicate the waiting has completed. +/// +/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function +/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. +public func waitUntil(timeout timeout: NSTimeInterval = 1, file: FileString = __FILE__, line: UInt = __LINE__, action: (() -> Void) -> Void) -> Void { + NMBWait.until(timeout: timeout, file: file, line: line, action: action) +} +#endif diff --git a/Pods/Nimble/Sources/Nimble/DSL.swift b/Pods/Nimble/Sources/Nimble/DSL.swift new file mode 100644 index 0000000..4bfb702 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/DSL.swift @@ -0,0 +1,68 @@ +import Foundation + +/// Make an expectation on a given actual value. The value given is lazily evaluated. +@warn_unused_result(message="Follow 'expect(…)' with '.to(…)', '.toNot(…)', 'toEventually(…)', '==', etc.") +public func expect(@autoclosure(escaping) expression: () throws -> T?, file: FileString = __FILE__, line: UInt = __LINE__) -> Expectation { + return Expectation( + expression: Expression( + expression: expression, + location: SourceLocation(file: file, line: line), + isClosure: true)) +} + +/// Make an expectation on a given actual value. The closure is lazily invoked. +@warn_unused_result(message="Follow 'expect(…)' with '.to(…)', '.toNot(…)', 'toEventually(…)', '==', etc.") +public func expect(file: FileString = __FILE__, line: UInt = __LINE__, expression: () throws -> T?) -> Expectation { + return Expectation( + expression: Expression( + expression: expression, + location: SourceLocation(file: file, line: line), + isClosure: true)) +} + +/// Always fails the test with a message and a specified location. +public func fail(message: String, location: SourceLocation) { + let handler = NimbleEnvironment.activeInstance.assertionHandler + handler.assert(false, message: FailureMessage(stringValue: message), location: location) +} + +/// Always fails the test with a message. +public func fail(message: String, file: FileString = __FILE__, line: UInt = __LINE__) { + fail(message, location: SourceLocation(file: file, line: line)) +} + +/// Always fails the test. +public func fail(file: FileString = __FILE__, line: UInt = __LINE__) { + fail("fail() always fails", file: file, line: line) +} + +/// Like Swift's precondition(), but raises NSExceptions instead of sigaborts +internal func nimblePrecondition( + @autoclosure expr: () -> Bool, + @autoclosure _ name: () -> String, + @autoclosure _ message: () -> String, + file: StaticString = __FILE__, + line: UInt = __LINE__) -> Bool { + let result = expr() + if !result { +#if _runtime(_ObjC) + let e = NSException( + name: name(), + reason: message(), + userInfo: nil) + e.raise() +#else + preconditionFailure("\(name()) - \(message())", file: file, line: line) +#endif + } + return result +} + +@noreturn +internal func internalError(msg: String, file: FileString = __FILE__, line: UInt = __LINE__) { + fatalError( + "Nimble Bug Found: \(msg) at \(file):\(line).\n" + + "Please file a bug to Nimble: https://github.com/Quick/Nimble/issues with the " + + "code snippet that caused this error." + ) +} \ No newline at end of file diff --git a/Pods/Nimble/Sources/Nimble/Expectation.swift b/Pods/Nimble/Sources/Nimble/Expectation.swift new file mode 100644 index 0000000..520902d --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Expectation.swift @@ -0,0 +1,65 @@ +import Foundation + +internal func expressionMatches(expression: Expression, matcher: U, to: String, description: String?) -> (Bool, FailureMessage) { + let msg = FailureMessage() + msg.userDescription = description + msg.to = to + do { + let pass = try matcher.matches(expression, failureMessage: msg) + if msg.actualValue == "" { + msg.actualValue = "<\(stringify(try expression.evaluate()))>" + } + return (pass, msg) + } catch let error { + msg.actualValue = "an unexpected error thrown: <\(error)>" + return (false, msg) + } +} + +internal func expressionDoesNotMatch(expression: Expression, matcher: U, toNot: String, description: String?) -> (Bool, FailureMessage) { + let msg = FailureMessage() + msg.userDescription = description + msg.to = toNot + do { + let pass = try matcher.doesNotMatch(expression, failureMessage: msg) + if msg.actualValue == "" { + msg.actualValue = "<\(stringify(try expression.evaluate()))>" + } + return (pass, msg) + } catch let error { + msg.actualValue = "an unexpected error thrown: <\(error)>" + return (false, msg) + } +} + +public struct Expectation { + let expression: Expression + + public func verify(pass: Bool, _ message: FailureMessage) { + let handler = NimbleEnvironment.activeInstance.assertionHandler + handler.assert(pass, message: message, location: expression.location) + } + + /// Tests the actual value using a matcher to match. + public func to(matcher: U, description: String? = nil) { + let (pass, msg) = expressionMatches(expression, matcher: matcher, to: "to", description: description) + verify(pass, msg) + } + + /// Tests the actual value using a matcher to not match. + public func toNot(matcher: U, description: String? = nil) { + let (pass, msg) = expressionDoesNotMatch(expression, matcher: matcher, toNot: "to not", description: description) + verify(pass, msg) + } + + /// Tests the actual value using a matcher to not match. + /// + /// Alias to toNot(). + public func notTo(matcher: U, description: String? = nil) { + toNot(matcher, description: description) + } + + // see: + // - AsyncMatcherWrapper for extension + // - NMBExpectation for Objective-C interface +} diff --git a/Pods/Nimble/Sources/Nimble/Expression.swift b/Pods/Nimble/Sources/Nimble/Expression.swift new file mode 100644 index 0000000..f64ee24 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Expression.swift @@ -0,0 +1,90 @@ +import Foundation + +// Memoizes the given closure, only calling the passed +// closure once; even if repeat calls to the returned closure +internal func memoizedClosure(closure: () throws -> T) -> (Bool) throws -> T { + var cache: T? + return ({ withoutCaching in + if (withoutCaching || cache == nil) { + cache = try closure() + } + return cache! + }) +} + +/// Expression represents the closure of the value inside expect(...). +/// Expressions are memoized by default. This makes them safe to call +/// evaluate() multiple times without causing a re-evaluation of the underlying +/// closure. +/// +/// @warning Since the closure can be any code, Objective-C code may choose +/// to raise an exception. Currently, Expression does not memoize +/// exception raising. +/// +/// This provides a common consumable API for matchers to utilize to allow +/// Nimble to change internals to how the captured closure is managed. +public struct Expression { + internal let _expression: (Bool) throws -> T? + internal let _withoutCaching: Bool + public let location: SourceLocation + public let isClosure: Bool + + /// Creates a new expression struct. Normally, expect(...) will manage this + /// creation process. The expression is memoized. + /// + /// @param expression The closure that produces a given value. + /// @param location The source location that this closure originates from. + /// @param isClosure A bool indicating if the captured expression is a + /// closure or internally produced closure. Some matchers + /// may require closures. For example, toEventually() + /// requires an explicit closure. This gives Nimble + /// flexibility if @autoclosure behavior changes between + /// Swift versions. Nimble internals always sets this true. + public init(expression: () throws -> T?, location: SourceLocation, isClosure: Bool = true) { + self._expression = memoizedClosure(expression) + self.location = location + self._withoutCaching = false + self.isClosure = isClosure + } + + /// Creates a new expression struct. Normally, expect(...) will manage this + /// creation process. + /// + /// @param expression The closure that produces a given value. + /// @param location The source location that this closure originates from. + /// @param withoutCaching Indicates if the struct should memoize the given + /// closure's result. Subsequent evaluate() calls will + /// not call the given closure if this is true. + /// @param isClosure A bool indicating if the captured expression is a + /// closure or internally produced closure. Some matchers + /// may require closures. For example, toEventually() + /// requires an explicit closure. This gives Nimble + /// flexibility if @autoclosure behavior changes between + /// Swift versions. Nimble internals always sets this true. + public init(memoizedExpression: (Bool) throws -> T?, location: SourceLocation, withoutCaching: Bool, isClosure: Bool = true) { + self._expression = memoizedExpression + self.location = location + self._withoutCaching = withoutCaching + self.isClosure = isClosure + } + + /// Returns a new Expression from the given expression. Identical to a map() + /// on this type. This should be used only to typecast the Expression's + /// closure value. + /// + /// The returned expression will preserve location and isClosure. + /// + /// @param block The block that can cast the current Expression value to a + /// new type. + public func cast(block: (T?) throws -> U?) -> Expression { + return Expression(expression: ({ try block(self.evaluate()) }), location: self.location, isClosure: self.isClosure) + } + + public func evaluate() throws -> T? { + return try self._expression(_withoutCaching) + } + + public func withoutCaching() -> Expression { + return Expression(memoizedExpression: self._expression, location: location, withoutCaching: true, isClosure: isClosure) + } +} diff --git a/Pods/Nimble/Sources/Nimble/FailureMessage.swift b/Pods/Nimble/Sources/Nimble/FailureMessage.swift new file mode 100644 index 0000000..4d23bc8 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/FailureMessage.swift @@ -0,0 +1,56 @@ +import Foundation + +/// Encapsulates the failure message that matchers can report to the end user. +/// +/// This is shared state between Nimble and matchers that mutate this value. +public class FailureMessage: NSObject { + public var expected: String = "expected" + public var actualValue: String? = "" // empty string -> use default; nil -> exclude + public var to: String = "to" + public var postfixMessage: String = "match" + public var postfixActual: String = "" + public var userDescription: String? = nil + + public var stringValue: String { + get { + if let value = _stringValueOverride { + return value + } else { + return computeStringValue() + } + } + set { + _stringValueOverride = newValue + } + } + + internal var _stringValueOverride: String? + + public override init() { + } + + public init(stringValue: String) { + _stringValueOverride = stringValue + } + + internal func stripNewlines(str: String) -> String { + var lines: [String] = NSString(string: str).componentsSeparatedByString("\n") as [String] + let whitespace = NSCharacterSet.whitespaceAndNewlineCharacterSet() + lines = lines.map { line in NSString(string: line).stringByTrimmingCharactersInSet(whitespace) } + return lines.joinWithSeparator("") + } + + internal func computeStringValue() -> String { + var value = "\(expected) \(to) \(postfixMessage)" + if let actualValue = actualValue { + value = "\(expected) \(to) \(postfixMessage), got \(actualValue)\(postfixActual)" + } + value = stripNewlines(value) + + if let userDescription = userDescription { + return "\(userDescription)\n\(value)" + } + + return value + } +} \ No newline at end of file diff --git a/Pods/Nimble/Sources/Nimble/Matchers/AllPass.swift b/Pods/Nimble/Sources/Nimble/Matchers/AllPass.swift new file mode 100644 index 0000000..d67714b --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/AllPass.swift @@ -0,0 +1,92 @@ +import Foundation + +public func allPass + (passFunc: (T?) -> Bool) -> NonNilMatcherFunc { + return allPass("pass a condition", passFunc) +} + +public func allPass + (passName: String, _ passFunc: (T?) -> Bool) -> NonNilMatcherFunc { + return createAllPassMatcher() { + expression, failureMessage in + failureMessage.postfixMessage = passName + return passFunc(try expression.evaluate()) + } +} + +public func allPass + (matcher: V) -> NonNilMatcherFunc { + return createAllPassMatcher() { + try matcher.matches($0, failureMessage: $1) + } +} + +private func createAllPassMatcher + (elementEvaluator:(Expression, FailureMessage) throws -> Bool) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.actualValue = nil + if let actualValue = try actualExpression.evaluate() { + for currentElement in actualValue { + let exp = Expression( + expression: {currentElement}, location: actualExpression.location) + if try !elementEvaluator(exp, failureMessage) { + failureMessage.postfixMessage = + "all \(failureMessage.postfixMessage)," + + " but failed first at element <\(stringify(currentElement))>" + + " in <\(stringify(actualValue))>" + return false + } + } + failureMessage.postfixMessage = "all \(failureMessage.postfixMessage)" + } else { + failureMessage.postfixMessage = "all pass (use beNil() to match nils)" + return false + } + + return true + } +} + +#if _runtime(_ObjC) +extension NMBObjCMatcher { + public class func allPassMatcher(matcher: NMBObjCMatcher) -> NMBObjCMatcher { + return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in + let location = actualExpression.location + let actualValue = try! actualExpression.evaluate() + var nsObjects = [NSObject]() + + var collectionIsUsable = true + if let value = actualValue as? NSFastEnumeration { + let generator = NSFastGenerator(value) + while let obj:AnyObject = generator.next() { + if let nsObject = obj as? NSObject { + nsObjects.append(nsObject) + } else { + collectionIsUsable = false + break + } + } + } else { + collectionIsUsable = false + } + + if !collectionIsUsable { + failureMessage.postfixMessage = + "allPass only works with NSFastEnumeration (NSArray, NSSet, ...) of NSObjects" + failureMessage.expected = "" + failureMessage.to = "" + return false + } + + let expr = Expression(expression: ({ nsObjects }), location: location) + let elementEvaluator: (Expression, FailureMessage) -> Bool = { + expression, failureMessage in + return matcher.matches( + {try! expression.evaluate()}, failureMessage: failureMessage, location: expr.location) + } + return try! createAllPassMatcher(elementEvaluator).matches( + expr, failureMessage: failureMessage) + } + } +} +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/BeAKindOf.swift b/Pods/Nimble/Sources/Nimble/Matchers/BeAKindOf.swift new file mode 100644 index 0000000..d1f3737 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/BeAKindOf.swift @@ -0,0 +1,38 @@ +import Foundation + +#if _runtime(_ObjC) + +// A Nimble matcher that catches attempts to use beAKindOf with non Objective-C types +public func beAKindOf(expectedClass: Any) -> NonNilMatcherFunc { + return NonNilMatcherFunc {actualExpression, failureMessage in + failureMessage.stringValue = "beAKindOf only works on Objective-C types since" + + " the Swift compiler will automatically type check Swift-only types." + + " This expectation is redundant." + return false + } +} + +/// A Nimble matcher that succeeds when the actual value is an instance of the given class. +/// @see beAnInstanceOf if you want to match against the exact class +public func beAKindOf(expectedClass: AnyClass) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + let instance = try actualExpression.evaluate() + if let validInstance = instance { + failureMessage.actualValue = "<\(classAsString(validInstance.dynamicType)) instance>" + } else { + failureMessage.actualValue = "" + } + failureMessage.postfixMessage = "be a kind of \(classAsString(expectedClass))" + return instance != nil && instance!.isKindOfClass(expectedClass) + } +} + +extension NMBObjCMatcher { + public class func beAKindOfMatcher(expected: AnyClass) -> NMBMatcher { + return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in + return try! beAKindOf(expected).matches(actualExpression, failureMessage: failureMessage) + } + } +} + +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/BeAnInstanceOf.swift b/Pods/Nimble/Sources/Nimble/Matchers/BeAnInstanceOf.swift new file mode 100644 index 0000000..32477dd --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/BeAnInstanceOf.swift @@ -0,0 +1,40 @@ +import Foundation + +// A Nimble matcher that catches attempts to use beAnInstanceOf with non Objective-C types +public func beAnInstanceOf(expectedClass: Any) -> NonNilMatcherFunc { + return NonNilMatcherFunc {actualExpression, failureMessage in + failureMessage.stringValue = "beAnInstanceOf only works on Objective-C types since" + + " the Swift compiler will automatically type check Swift-only types." + + " This expectation is redundant." + return false + } +} + +/// A Nimble matcher that succeeds when the actual value is an instance of the given class. +/// @see beAKindOf if you want to match against subclasses +public func beAnInstanceOf(expectedClass: AnyClass) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + let instance = try actualExpression.evaluate() + if let validInstance = instance { + failureMessage.actualValue = "<\(classAsString(validInstance.dynamicType)) instance>" + } else { + failureMessage.actualValue = "" + } + failureMessage.postfixMessage = "be an instance of \(classAsString(expectedClass))" +#if _runtime(_ObjC) + return instance != nil && instance!.isMemberOfClass(expectedClass) +#else + return instance != nil && instance!.dynamicType == expectedClass +#endif + } +} + +#if _runtime(_ObjC) +extension NMBObjCMatcher { + public class func beAnInstanceOfMatcher(expected: AnyClass) -> NMBMatcher { + return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in + return try! beAnInstanceOf(expected).matches(actualExpression, failureMessage: failureMessage) + } + } +} +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/BeCloseTo.swift b/Pods/Nimble/Sources/Nimble/Matchers/BeCloseTo.swift new file mode 100644 index 0000000..bcab1c9 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/BeCloseTo.swift @@ -0,0 +1,128 @@ +#if os(Linux) +import Glibc +#endif +import Foundation + +internal let DefaultDelta = 0.0001 + +internal func isCloseTo(actualValue: NMBDoubleConvertible?, expectedValue: NMBDoubleConvertible, delta: Double, failureMessage: FailureMessage) -> Bool { + failureMessage.postfixMessage = "be close to <\(stringify(expectedValue))> (within \(stringify(delta)))" + if actualValue != nil { + failureMessage.actualValue = "<\(stringify(actualValue!))>" + } else { + failureMessage.actualValue = "" + } + return actualValue != nil && abs(actualValue!.doubleValue - expectedValue.doubleValue) < delta +} + +/// A Nimble matcher that succeeds when a value is close to another. This is used for floating +/// point values which can have imprecise results when doing arithmetic on them. +/// +/// @see equal +public func beCloseTo(expectedValue: Double, within delta: Double = DefaultDelta) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + return isCloseTo(try actualExpression.evaluate(), expectedValue: expectedValue, delta: delta, failureMessage: failureMessage) + } +} + +/// A Nimble matcher that succeeds when a value is close to another. This is used for floating +/// point values which can have imprecise results when doing arithmetic on them. +/// +/// @see equal +public func beCloseTo(expectedValue: NMBDoubleConvertible, within delta: Double = DefaultDelta) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + return isCloseTo(try actualExpression.evaluate(), expectedValue: expectedValue, delta: delta, failureMessage: failureMessage) + } +} + +#if _runtime(_ObjC) +public class NMBObjCBeCloseToMatcher : NSObject, NMBMatcher { + var _expected: NSNumber + var _delta: CDouble + init(expected: NSNumber, within: CDouble) { + _expected = expected + _delta = within + } + + public func matches(actualExpression: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { + let actualBlock: () -> NMBDoubleConvertible? = ({ + return actualExpression() as? NMBDoubleConvertible + }) + let expr = Expression(expression: actualBlock, location: location) + let matcher = beCloseTo(self._expected, within: self._delta) + return try! matcher.matches(expr, failureMessage: failureMessage) + } + + public func doesNotMatch(actualExpression: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { + let actualBlock: () -> NMBDoubleConvertible? = ({ + return actualExpression() as? NMBDoubleConvertible + }) + let expr = Expression(expression: actualBlock, location: location) + let matcher = beCloseTo(self._expected, within: self._delta) + return try! matcher.doesNotMatch(expr, failureMessage: failureMessage) + } + + public var within: (CDouble) -> NMBObjCBeCloseToMatcher { + return ({ delta in + return NMBObjCBeCloseToMatcher(expected: self._expected, within: delta) + }) + } +} + +extension NMBObjCMatcher { + public class func beCloseToMatcher(expected: NSNumber, within: CDouble) -> NMBObjCBeCloseToMatcher { + return NMBObjCBeCloseToMatcher(expected: expected, within: within) + } +} +#endif + +public func beCloseTo(expectedValues: [Double], within delta: Double = DefaultDelta) -> NonNilMatcherFunc <[Double]> { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be close to <\(stringify(expectedValues))> (each within \(stringify(delta)))" + if let actual = try actualExpression.evaluate() { + failureMessage.actualValue = "<\(stringify(actual))>" + + if actual.count != expectedValues.count { + return false + } else { + for (index, actualItem) in actual.enumerate() { + if fabs(actualItem - expectedValues[index]) > delta { + return false + } + } + return true + } + } + return false + } +} + +// MARK: - Operators + +infix operator ≈ { + associativity none + precedence 130 +} + +public func ≈(lhs: Expectation<[Double]>, rhs: [Double]) { + lhs.to(beCloseTo(rhs)) +} + +public func ≈(lhs: Expectation, rhs: Double) { + lhs.to(beCloseTo(rhs)) +} + +public func ≈(lhs: Expectation, rhs: (expected: Double, delta: Double)) { + lhs.to(beCloseTo(rhs.expected, within: rhs.delta)) +} + +public func ==(lhs: Expectation, rhs: (expected: Double, delta: Double)) { + lhs.to(beCloseTo(rhs.expected, within: rhs.delta)) +} + +// make this higher precedence than exponents so the Doubles either end aren't pulled in +// unexpectantly +infix operator ± { precedence 170 } +public func ±(lhs: Double, rhs: Double) -> (expected: Double, delta: Double) { + return (expected: lhs, delta: rhs) +} diff --git a/Pods/Nimble/Sources/Nimble/Matchers/BeEmpty.swift b/Pods/Nimble/Sources/Nimble/Matchers/BeEmpty.swift new file mode 100644 index 0000000..bc1bb9f --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/BeEmpty.swift @@ -0,0 +1,92 @@ +import Foundation + + +/// A Nimble matcher that succeeds when a value is "empty". For collections, this +/// means the are no items in that collection. For strings, it is an empty string. +public func beEmpty() -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be empty" + let actualSeq = try actualExpression.evaluate() + if actualSeq == nil { + return true + } + var generator = actualSeq!.generate() + return generator.next() == nil + } +} + +/// A Nimble matcher that succeeds when a value is "empty". For collections, this +/// means the are no items in that collection. For strings, it is an empty string. +public func beEmpty() -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be empty" + let actualString = try actualExpression.evaluate() + return actualString == nil || NSString(string: actualString!).length == 0 + } +} + +/// A Nimble matcher that succeeds when a value is "empty". For collections, this +/// means the are no items in that collection. For NSString instances, it is an empty string. +public func beEmpty() -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be empty" + let actualString = try actualExpression.evaluate() + return actualString == nil || actualString!.length == 0 + } +} + +// Without specific overrides, beEmpty() is ambiguous for NSDictionary, NSArray, +// etc, since they conform to SequenceType as well as NMBCollection. + +/// A Nimble matcher that succeeds when a value is "empty". For collections, this +/// means the are no items in that collection. For strings, it is an empty string. +public func beEmpty() -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be empty" + let actualDictionary = try actualExpression.evaluate() + return actualDictionary == nil || actualDictionary!.count == 0 + } +} + +/// A Nimble matcher that succeeds when a value is "empty". For collections, this +/// means the are no items in that collection. For strings, it is an empty string. +public func beEmpty() -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be empty" + let actualArray = try actualExpression.evaluate() + return actualArray == nil || actualArray!.count == 0 + } +} + +/// A Nimble matcher that succeeds when a value is "empty". For collections, this +/// means the are no items in that collection. For strings, it is an empty string. +public func beEmpty() -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be empty" + let actual = try actualExpression.evaluate() + return actual == nil || actual!.count == 0 + } +} + +#if _runtime(_ObjC) +extension NMBObjCMatcher { + public class func beEmptyMatcher() -> NMBObjCMatcher { + return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in + let location = actualExpression.location + let actualValue = try! actualExpression.evaluate() + failureMessage.postfixMessage = "be empty" + if let value = actualValue as? NMBCollection { + let expr = Expression(expression: ({ value as NMBCollection }), location: location) + return try! beEmpty().matches(expr, failureMessage: failureMessage) + } else if let value = actualValue as? NSString { + let expr = Expression(expression: ({ value as String }), location: location) + return try! beEmpty().matches(expr, failureMessage: failureMessage) + } else if let actualValue = actualValue { + failureMessage.postfixMessage = "be empty (only works for NSArrays, NSSets, NSDictionaries, NSHashTables, and NSStrings)" + failureMessage.actualValue = "\(classAsString(actualValue.dynamicType)) type" + } + return false + } + } +} +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/BeGreaterThan.swift b/Pods/Nimble/Sources/Nimble/Matchers/BeGreaterThan.swift new file mode 100644 index 0000000..0f24ab5 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/BeGreaterThan.swift @@ -0,0 +1,39 @@ +import Foundation + + +/// A Nimble matcher that succeeds when the actual value is greater than the expected value. +public func beGreaterThan(expectedValue: T?) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be greater than <\(stringify(expectedValue))>" + return try actualExpression.evaluate() > expectedValue + } +} + +/// A Nimble matcher that succeeds when the actual value is greater than the expected value. +public func beGreaterThan(expectedValue: NMBComparable?) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be greater than <\(stringify(expectedValue))>" + let actualValue = try actualExpression.evaluate() + let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) == NSComparisonResult.OrderedDescending + return matches + } +} + +public func >(lhs: Expectation, rhs: T) { + lhs.to(beGreaterThan(rhs)) +} + +public func >(lhs: Expectation, rhs: NMBComparable?) { + lhs.to(beGreaterThan(rhs)) +} + +#if _runtime(_ObjC) +extension NMBObjCMatcher { + public class func beGreaterThanMatcher(expected: NMBComparable?) -> NMBObjCMatcher { + return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in + let expr = actualExpression.cast { $0 as? NMBComparable } + return try! beGreaterThan(expected).matches(expr, failureMessage: failureMessage) + } + } +} +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/BeGreaterThanOrEqualTo.swift b/Pods/Nimble/Sources/Nimble/Matchers/BeGreaterThanOrEqualTo.swift new file mode 100644 index 0000000..c89ff07 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/BeGreaterThanOrEqualTo.swift @@ -0,0 +1,41 @@ +import Foundation + +/// A Nimble matcher that succeeds when the actual value is greater than +/// or equal to the expected value. +public func beGreaterThanOrEqualTo(expectedValue: T?) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be greater than or equal to <\(stringify(expectedValue))>" + let actualValue = try actualExpression.evaluate() + return actualValue >= expectedValue + } +} + +/// A Nimble matcher that succeeds when the actual value is greater than +/// or equal to the expected value. +public func beGreaterThanOrEqualTo(expectedValue: T?) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be greater than or equal to <\(stringify(expectedValue))>" + let actualValue = try actualExpression.evaluate() + let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) != NSComparisonResult.OrderedAscending + return matches + } +} + +public func >=(lhs: Expectation, rhs: T) { + lhs.to(beGreaterThanOrEqualTo(rhs)) +} + +public func >=(lhs: Expectation, rhs: T) { + lhs.to(beGreaterThanOrEqualTo(rhs)) +} + +#if _runtime(_ObjC) +extension NMBObjCMatcher { + public class func beGreaterThanOrEqualToMatcher(expected: NMBComparable?) -> NMBObjCMatcher { + return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in + let expr = actualExpression.cast { $0 as? NMBComparable } + return try! beGreaterThanOrEqualTo(expected).matches(expr, failureMessage: failureMessage) + } + } +} +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/BeIdenticalTo.swift b/Pods/Nimble/Sources/Nimble/Matchers/BeIdenticalTo.swift new file mode 100644 index 0000000..a369501 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/BeIdenticalTo.swift @@ -0,0 +1,39 @@ +import Foundation + + +/// A Nimble matcher that succeeds when the actual value is the same instance +/// as the expected instance. +public func beIdenticalTo(expected: AnyObject?) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + let actual = try actualExpression.evaluate() + failureMessage.actualValue = "\(identityAsString(actual))" + failureMessage.postfixMessage = "be identical to \(identityAsString(expected))" + return actual === expected && actual !== nil + } +} + +public func ===(lhs: Expectation, rhs: AnyObject?) { + lhs.to(beIdenticalTo(rhs)) +} +public func !==(lhs: Expectation, rhs: AnyObject?) { + lhs.toNot(beIdenticalTo(rhs)) +} + +/// A Nimble matcher that succeeds when the actual value is the same instance +/// as the expected instance. +/// +/// Alias for "beIdenticalTo". +public func be(expected: AnyObject?) -> NonNilMatcherFunc { + return beIdenticalTo(expected) +} + +#if _runtime(_ObjC) +extension NMBObjCMatcher { + public class func beIdenticalToMatcher(expected: NSObject?) -> NMBObjCMatcher { + return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in + let aExpr = actualExpression.cast { $0 as AnyObject? } + return try! beIdenticalTo(expected).matches(aExpr, failureMessage: failureMessage) + } + } +} +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/BeLessThan.swift b/Pods/Nimble/Sources/Nimble/Matchers/BeLessThan.swift new file mode 100644 index 0000000..ea4725b --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/BeLessThan.swift @@ -0,0 +1,38 @@ +import Foundation + +/// A Nimble matcher that succeeds when the actual value is less than the expected value. +public func beLessThan(expectedValue: T?) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be less than <\(stringify(expectedValue))>" + return try actualExpression.evaluate() < expectedValue + } +} + +/// A Nimble matcher that succeeds when the actual value is less than the expected value. +public func beLessThan(expectedValue: NMBComparable?) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be less than <\(stringify(expectedValue))>" + let actualValue = try actualExpression.evaluate() + let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) == NSComparisonResult.OrderedAscending + return matches + } +} + +public func <(lhs: Expectation, rhs: T) { + lhs.to(beLessThan(rhs)) +} + +public func <(lhs: Expectation, rhs: NMBComparable?) { + lhs.to(beLessThan(rhs)) +} + +#if _runtime(_ObjC) +extension NMBObjCMatcher { + public class func beLessThanMatcher(expected: NMBComparable?) -> NMBObjCMatcher { + return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in + let expr = actualExpression.cast { $0 as! NMBComparable? } + return try! beLessThan(expected).matches(expr, failureMessage: failureMessage) + } + } +} +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/BeLessThanOrEqual.swift b/Pods/Nimble/Sources/Nimble/Matchers/BeLessThanOrEqual.swift new file mode 100644 index 0000000..a24cf8c --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/BeLessThanOrEqual.swift @@ -0,0 +1,39 @@ +import Foundation + +/// A Nimble matcher that succeeds when the actual value is less than +/// or equal to the expected value. +public func beLessThanOrEqualTo(expectedValue: T?) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be less than or equal to <\(stringify(expectedValue))>" + return try actualExpression.evaluate() <= expectedValue + } +} + +/// A Nimble matcher that succeeds when the actual value is less than +/// or equal to the expected value. +public func beLessThanOrEqualTo(expectedValue: T?) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be less than or equal to <\(stringify(expectedValue))>" + let actualValue = try actualExpression.evaluate() + return actualValue != nil && actualValue!.NMB_compare(expectedValue) != NSComparisonResult.OrderedDescending + } +} + +public func <=(lhs: Expectation, rhs: T) { + lhs.to(beLessThanOrEqualTo(rhs)) +} + +public func <=(lhs: Expectation, rhs: T) { + lhs.to(beLessThanOrEqualTo(rhs)) +} + +#if _runtime(_ObjC) +extension NMBObjCMatcher { + public class func beLessThanOrEqualToMatcher(expected: NMBComparable?) -> NMBObjCMatcher { + return NMBObjCMatcher(canMatchNil:false) { actualExpression, failureMessage in + let expr = actualExpression.cast { $0 as? NMBComparable } + return try! beLessThanOrEqualTo(expected).matches(expr, failureMessage: failureMessage) + } + } +} +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/BeLogical.swift b/Pods/Nimble/Sources/Nimble/Matchers/BeLogical.swift new file mode 100644 index 0000000..cabf583 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/BeLogical.swift @@ -0,0 +1,95 @@ +import Foundation + +internal func matcherWithFailureMessage(matcher: M, postprocessor: (FailureMessage) -> Void) -> FullMatcherFunc { + return FullMatcherFunc { actualExpression, failureMessage, isNegation in + let pass: Bool + if isNegation { + pass = try matcher.doesNotMatch(actualExpression, failureMessage: failureMessage) + } else { + pass = try matcher.matches(actualExpression, failureMessage: failureMessage) + } + postprocessor(failureMessage) + return pass + } +} + +// MARK: beTrue() / beFalse() + +/// A Nimble matcher that succeeds when the actual value is exactly true. +/// This matcher will not match against nils. +public func beTrue() -> FullMatcherFunc { + return matcherWithFailureMessage(equal(true)) { failureMessage in + failureMessage.postfixMessage = "be true" + } +} + +/// A Nimble matcher that succeeds when the actual value is exactly false. +/// This matcher will not match against nils. +public func beFalse() -> FullMatcherFunc { + return matcherWithFailureMessage(equal(false)) { failureMessage in + failureMessage.postfixMessage = "be false" + } +} + +// MARK: beTruthy() / beFalsy() + +/// A Nimble matcher that succeeds when the actual value is not logically false. +public func beTruthy() -> MatcherFunc { + return MatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be truthy" + let actualValue = try actualExpression.evaluate() + if let actualValue = actualValue { + if let actualValue = actualValue as? BooleanType { + return actualValue.boolValue == true + } + } + return actualValue != nil + } +} + +/// A Nimble matcher that succeeds when the actual value is logically false. +/// This matcher will match against nils. +public func beFalsy() -> MatcherFunc { + return MatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be falsy" + let actualValue = try actualExpression.evaluate() + if let actualValue = actualValue { + if let actualValue = actualValue as? BooleanType { + return actualValue.boolValue != true + } + } + return actualValue == nil + } +} + +#if _runtime(_ObjC) +extension NMBObjCMatcher { + public class func beTruthyMatcher() -> NMBObjCMatcher { + return NMBObjCMatcher { actualExpression, failureMessage in + let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false as BooleanType? } + return try! beTruthy().matches(expr, failureMessage: failureMessage) + } + } + + public class func beFalsyMatcher() -> NMBObjCMatcher { + return NMBObjCMatcher { actualExpression, failureMessage in + let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false as BooleanType? } + return try! beFalsy().matches(expr, failureMessage: failureMessage) + } + } + + public class func beTrueMatcher() -> NMBObjCMatcher { + return NMBObjCMatcher { actualExpression, failureMessage in + let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false as Bool? } + return try! beTrue().matches(expr, failureMessage: failureMessage) + } + } + + public class func beFalseMatcher() -> NMBObjCMatcher { + return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in + let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false as Bool? } + return try! beFalse().matches(expr, failureMessage: failureMessage) + } + } +} +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/BeNil.swift b/Pods/Nimble/Sources/Nimble/Matchers/BeNil.swift new file mode 100644 index 0000000..a6fb31f --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/BeNil.swift @@ -0,0 +1,20 @@ +import Foundation + +/// A Nimble matcher that succeeds when the actual value is nil. +public func beNil() -> MatcherFunc { + return MatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be nil" + let actualValue = try actualExpression.evaluate() + return actualValue == nil + } +} + +#if _runtime(_ObjC) +extension NMBObjCMatcher { + public class func beNilMatcher() -> NMBObjCMatcher { + return NMBObjCMatcher { actualExpression, failureMessage in + return try! beNil().matches(actualExpression, failureMessage: failureMessage) + } + } +} +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/BeVoid.swift b/Pods/Nimble/Sources/Nimble/Matchers/BeVoid.swift new file mode 100644 index 0000000..8f86265 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/BeVoid.swift @@ -0,0 +1,18 @@ +import Foundation + +/// A Nimble matcher that succeeds when the actual value is Void. +public func beVoid() -> MatcherFunc<()> { + return MatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "be void" + let actualValue: ()? = try actualExpression.evaluate() + return actualValue != nil + } +} + +public func ==(lhs: Expectation<()>, rhs: ()) { + lhs.to(beVoid()) +} + +public func !=(lhs: Expectation<()>, rhs: ()) { + lhs.toNot(beVoid()) +} \ No newline at end of file diff --git a/Pods/Nimble/Sources/Nimble/Matchers/BeginWith.swift b/Pods/Nimble/Sources/Nimble/Matchers/BeginWith.swift new file mode 100644 index 0000000..0b5e0e1 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/BeginWith.swift @@ -0,0 +1,55 @@ +import Foundation + + +/// A Nimble matcher that succeeds when the actual sequence's first element +/// is equal to the expected value. +public func beginWith(startingElement: T) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "begin with <\(startingElement)>" + if let actualValue = try actualExpression.evaluate() { + var actualGenerator = actualValue.generate() + return actualGenerator.next() == startingElement + } + return false + } +} + +/// A Nimble matcher that succeeds when the actual collection's first element +/// is equal to the expected object. +public func beginWith(startingElement: AnyObject) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "begin with <\(startingElement)>" + let collection = try actualExpression.evaluate() + return collection != nil && collection!.indexOfObject(startingElement) == 0 + } +} + +/// A Nimble matcher that succeeds when the actual string contains expected substring +/// where the expected substring's location is zero. +public func beginWith(startingSubstring: String) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "begin with <\(startingSubstring)>" + if let actual = try actualExpression.evaluate() { + let range = actual.rangeOfString(startingSubstring) + return range != nil && range!.startIndex == actual.startIndex + } + return false + } +} + +#if _runtime(_ObjC) +extension NMBObjCMatcher { + public class func beginWithMatcher(expected: AnyObject) -> NMBObjCMatcher { + return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in + let actual = try! actualExpression.evaluate() + if let _ = actual as? String { + let expr = actualExpression.cast { $0 as? String } + return try! beginWith(expected as! String).matches(expr, failureMessage: failureMessage) + } else { + let expr = actualExpression.cast { $0 as? NMBOrderedCollection } + return try! beginWith(expected).matches(expr, failureMessage: failureMessage) + } + } + } +} +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/Contain.swift b/Pods/Nimble/Sources/Nimble/Matchers/Contain.swift new file mode 100644 index 0000000..bdac2d5 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/Contain.swift @@ -0,0 +1,92 @@ +import Foundation + +/// A Nimble matcher that succeeds when the actual sequence contains the expected value. +public func contain(items: T...) -> NonNilMatcherFunc { + return contain(items) +} + +private func contain(items: [T]) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "contain <\(arrayAsString(items))>" + if let actual = try actualExpression.evaluate() { + return items.all { + return actual.contains($0) + } + } + return false + } +} + +/// A Nimble matcher that succeeds when the actual string contains the expected substring. +public func contain(substrings: String...) -> NonNilMatcherFunc { + return contain(substrings) +} + +private func contain(substrings: [String]) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "contain <\(arrayAsString(substrings))>" + if let actual = try actualExpression.evaluate() { + return substrings.all { + let range = actual.rangeOfString($0) + return range != nil && !range!.isEmpty + } + } + return false + } +} + +/// A Nimble matcher that succeeds when the actual string contains the expected substring. +public func contain(substrings: NSString...) -> NonNilMatcherFunc { + return contain(substrings) +} + +private func contain(substrings: [NSString]) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "contain <\(arrayAsString(substrings))>" + if let actual = try actualExpression.evaluate() { + return substrings.all { actual.rangeOfString($0.description).length != 0 } + } + return false + } +} + +/// A Nimble matcher that succeeds when the actual collection contains the expected object. +public func contain(items: AnyObject?...) -> NonNilMatcherFunc { + return contain(items) +} + +private func contain(items: [AnyObject?]) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "contain <\(arrayAsString(items))>" + guard let actual = try actualExpression.evaluate() else { return false } + return items.all { item in + return item != nil && actual.containsObject(item!) + } + } +} + +#if _runtime(_ObjC) +extension NMBObjCMatcher { + public class func containMatcher(expected: [NSObject]) -> NMBObjCMatcher { + return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in + let location = actualExpression.location + let actualValue = try! actualExpression.evaluate() + if let value = actualValue as? NMBContainer { + let expr = Expression(expression: ({ value as NMBContainer }), location: location) + + // A straightforward cast on the array causes this to crash, so we have to cast the individual items + let expectedOptionals: [AnyObject?] = expected.map({ $0 as AnyObject? }) + return try! contain(expectedOptionals).matches(expr, failureMessage: failureMessage) + } else if let value = actualValue as? NSString { + let expr = Expression(expression: ({ value as String }), location: location) + return try! contain(expected as! [String]).matches(expr, failureMessage: failureMessage) + } else if actualValue != nil { + failureMessage.postfixMessage = "contain <\(arrayAsString(expected))> (only works for NSArrays, NSSets, NSHashTables, and NSStrings)" + } else { + failureMessage.postfixMessage = "contain <\(arrayAsString(expected))>" + } + return false + } + } +} +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/EndWith.swift b/Pods/Nimble/Sources/Nimble/Matchers/EndWith.swift new file mode 100644 index 0000000..ff2bd9e --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/EndWith.swift @@ -0,0 +1,65 @@ +import Foundation + + +/// A Nimble matcher that succeeds when the actual sequence's last element +/// is equal to the expected value. +public func endWith(endingElement: T) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "end with <\(endingElement)>" + + if let actualValue = try actualExpression.evaluate() { + var actualGenerator = actualValue.generate() + var lastItem: T? + var item: T? + repeat { + lastItem = item + item = actualGenerator.next() + } while(item != nil) + + return lastItem == endingElement + } + return false + } +} + +/// A Nimble matcher that succeeds when the actual collection's last element +/// is equal to the expected object. +public func endWith(endingElement: AnyObject) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "end with <\(endingElement)>" + let collection = try actualExpression.evaluate() + return collection != nil && collection!.indexOfObject(endingElement) == collection!.count - 1 + } +} + + +/// A Nimble matcher that succeeds when the actual string contains the expected substring +/// where the expected substring's location is the actual string's length minus the +/// expected substring's length. +public func endWith(endingSubstring: String) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "end with <\(endingSubstring)>" + if let collection = try actualExpression.evaluate() { + let range = collection.rangeOfString(endingSubstring) + return range != nil && range!.endIndex == collection.endIndex + } + return false + } +} + +#if _runtime(_ObjC) +extension NMBObjCMatcher { + public class func endWithMatcher(expected: AnyObject) -> NMBObjCMatcher { + return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in + let actual = try! actualExpression.evaluate() + if let _ = actual as? String { + let expr = actualExpression.cast { $0 as? String } + return try! endWith(expected as! String).matches(expr, failureMessage: failureMessage) + } else { + let expr = actualExpression.cast { $0 as? NMBOrderedCollection } + return try! endWith(expected).matches(expr, failureMessage: failureMessage) + } + } + } +} +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/Equal.swift b/Pods/Nimble/Sources/Nimble/Matchers/Equal.swift new file mode 100644 index 0000000..6373d8c --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/Equal.swift @@ -0,0 +1,181 @@ +import Foundation + +/// A Nimble matcher that succeeds when the actual value is equal to the expected value. +/// Values can support equal by supporting the Equatable protocol. +/// +/// @see beCloseTo if you want to match imprecise types (eg - floats, doubles). +public func equal(expectedValue: T?) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>" + let actualValue = try actualExpression.evaluate() + let matches = actualValue == expectedValue && expectedValue != nil + if expectedValue == nil || actualValue == nil { + if expectedValue == nil { + failureMessage.postfixActual = " (use beNil() to match nils)" + } + return false + } + return matches + } +} + +/// A Nimble matcher that succeeds when the actual value is equal to the expected value. +/// Values can support equal by supporting the Equatable protocol. +/// +/// @see beCloseTo if you want to match imprecise types (eg - floats, doubles). +public func equal(expectedValue: [T: C]?) -> NonNilMatcherFunc<[T: C]> { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>" + let actualValue = try actualExpression.evaluate() + if expectedValue == nil || actualValue == nil { + if expectedValue == nil { + failureMessage.postfixActual = " (use beNil() to match nils)" + } + return false + } + return expectedValue! == actualValue! + } +} + +/// A Nimble matcher that succeeds when the actual collection is equal to the expected collection. +/// Items must implement the Equatable protocol. +public func equal(expectedValue: [T]?) -> NonNilMatcherFunc<[T]> { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>" + let actualValue = try actualExpression.evaluate() + if expectedValue == nil || actualValue == nil { + if expectedValue == nil { + failureMessage.postfixActual = " (use beNil() to match nils)" + } + return false + } + return expectedValue! == actualValue! + } +} + +/// A Nimble matcher allowing comparison of collection with optional type +public func equal(expectedValue: [T?]) -> NonNilMatcherFunc<[T?]> { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>" + if let actualValue = try actualExpression.evaluate() { + if expectedValue.count != actualValue.count { + return false + } + + for (index, item) in actualValue.enumerate() { + let otherItem = expectedValue[index] + if item == nil && otherItem == nil { + continue + } else if item == nil && otherItem != nil { + return false + } else if item != nil && otherItem == nil { + return false + } else if item! != otherItem! { + return false + } + } + + return true + } else { + failureMessage.postfixActual = " (use beNil() to match nils)" + } + + return false + } +} + +/// A Nimble matcher that succeeds when the actual set is equal to the expected set. +public func equal(expectedValue: Set?) -> NonNilMatcherFunc> { + return equal(expectedValue, stringify: stringify) +} + +/// A Nimble matcher that succeeds when the actual set is equal to the expected set. +public func equal(expectedValue: Set?) -> NonNilMatcherFunc> { + return equal(expectedValue, stringify: { + if let set = $0 { + return stringify(Array(set).sort { $0 < $1 }) + } else { + return "nil" + } + }) +} + +private func equal(expectedValue: Set?, stringify: Set? -> String) -> NonNilMatcherFunc> { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>" + + if let expectedValue = expectedValue { + if let actualValue = try actualExpression.evaluate() { + failureMessage.actualValue = "<\(stringify(actualValue))>" + + if expectedValue == actualValue { + return true + } + + let missing = expectedValue.subtract(actualValue) + if missing.count > 0 { + failureMessage.postfixActual += ", missing <\(stringify(missing))>" + } + + let extra = actualValue.subtract(expectedValue) + if extra.count > 0 { + failureMessage.postfixActual += ", extra <\(stringify(extra))>" + } + } + } else { + failureMessage.postfixActual = " (use beNil() to match nils)" + } + + return false + } +} + +public func ==(lhs: Expectation, rhs: T?) { + lhs.to(equal(rhs)) +} + +public func !=(lhs: Expectation, rhs: T?) { + lhs.toNot(equal(rhs)) +} + +public func ==(lhs: Expectation<[T]>, rhs: [T]?) { + lhs.to(equal(rhs)) +} + +public func !=(lhs: Expectation<[T]>, rhs: [T]?) { + lhs.toNot(equal(rhs)) +} + +public func ==(lhs: Expectation>, rhs: Set?) { + lhs.to(equal(rhs)) +} + +public func !=(lhs: Expectation>, rhs: Set?) { + lhs.toNot(equal(rhs)) +} + +public func ==(lhs: Expectation>, rhs: Set?) { + lhs.to(equal(rhs)) +} + +public func !=(lhs: Expectation>, rhs: Set?) { + lhs.toNot(equal(rhs)) +} + +public func ==(lhs: Expectation<[T: C]>, rhs: [T: C]?) { + lhs.to(equal(rhs)) +} + +public func !=(lhs: Expectation<[T: C]>, rhs: [T: C]?) { + lhs.toNot(equal(rhs)) +} + +#if _runtime(_ObjC) +extension NMBObjCMatcher { + public class func equalMatcher(expected: NSObject) -> NMBMatcher { + return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in + return try! equal(expected).matches(actualExpression, failureMessage: failureMessage) + } + } +} +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/HaveCount.swift b/Pods/Nimble/Sources/Nimble/Matchers/HaveCount.swift new file mode 100644 index 0000000..7a66d2a --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/HaveCount.swift @@ -0,0 +1,50 @@ +import Foundation + +/// A Nimble matcher that succeeds when the actual CollectionType's count equals +/// the expected value +public func haveCount(expectedValue: T.Index.Distance) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + if let actualValue = try actualExpression.evaluate() { + failureMessage.postfixMessage = "have \(actualValue) with count \(expectedValue)" + let result = expectedValue == actualValue.count + failureMessage.actualValue = "\(actualValue.count)" + return result + } else { + return false + } + } +} + +/// A Nimble matcher that succeeds when the actual collection's count equals +/// the expected value +public func haveCount(expectedValue: Int) -> MatcherFunc { + return MatcherFunc { actualExpression, failureMessage in + if let actualValue = try actualExpression.evaluate() { + failureMessage.postfixMessage = "have \(actualValue) with count \(expectedValue)" + let result = expectedValue == actualValue.count + failureMessage.actualValue = "\(actualValue.count)" + return result + } else { + return false + } + } +} + +#if _runtime(_ObjC) +extension NMBObjCMatcher { + public class func haveCountMatcher(expected: NSNumber) -> NMBObjCMatcher { + return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in + let location = actualExpression.location + let actualValue = try! actualExpression.evaluate() + if let value = actualValue as? NMBCollection { + let expr = Expression(expression: ({ value as NMBCollection}), location: location) + return try! haveCount(expected.integerValue).matches(expr, failureMessage: failureMessage) + } else if let actualValue = actualValue { + failureMessage.postfixMessage = "get type of NSArray, NSSet, NSDictionary, or NSHashTable" + failureMessage.actualValue = "\(classAsString(actualValue.dynamicType))" + } + return false + } + } +} +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/Match.swift b/Pods/Nimble/Sources/Nimble/Matchers/Match.swift new file mode 100644 index 0000000..586e616 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/Match.swift @@ -0,0 +1,30 @@ +import Foundation + +#if _runtime(_ObjC) + +/// A Nimble matcher that succeeds when the actual string satisfies the regular expression +/// described by the expected string. +public func match(expectedValue: String?) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + failureMessage.postfixMessage = "match <\(stringify(expectedValue))>" + + if let actual = try actualExpression.evaluate() { + if let regexp = expectedValue { + return actual.rangeOfString(regexp, options: .RegularExpressionSearch) != nil + } + } + + return false + } +} + +extension NMBObjCMatcher { + public class func matchMatcher(expected: NSString) -> NMBMatcher { + return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in + let actual = actualExpression.cast { $0 as? String } + return try! match(expected.description).matches(actual, failureMessage: failureMessage) + } + } +} + +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/MatcherProtocols.swift b/Pods/Nimble/Sources/Nimble/Matchers/MatcherProtocols.swift new file mode 100644 index 0000000..dd2e8b4 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/MatcherProtocols.swift @@ -0,0 +1,157 @@ +import Foundation + +/// Implement this protocol to implement a custom matcher for Swift +public protocol Matcher { + typealias ValueType + func matches(actualExpression: Expression, failureMessage: FailureMessage) throws -> Bool + func doesNotMatch(actualExpression: Expression, failureMessage: FailureMessage) throws -> Bool +} + +#if _runtime(_ObjC) +/// Objective-C interface to the Swift variant of Matcher. +@objc public protocol NMBMatcher { + func matches(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool + func doesNotMatch(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool +} +#endif + +#if _runtime(_ObjC) +/// Protocol for types that support contain() matcher. +@objc public protocol NMBContainer { + func containsObject(object: AnyObject!) -> Bool +} + +extension NSHashTable : NMBContainer {} // Corelibs Foundation does not include this class yet +#else +public protocol NMBContainer { + func containsObject(object: AnyObject) -> Bool +} +#endif + +extension NSArray : NMBContainer {} +extension NSSet : NMBContainer {} + +#if _runtime(_ObjC) +/// Protocol for types that support only beEmpty(), haveCount() matchers +@objc public protocol NMBCollection { + var count: Int { get } +} + +extension NSHashTable : NMBCollection {} // Corelibs Foundation does not include these classes yet +extension NSMapTable : NMBCollection {} +#else +public protocol NMBCollection { + var count: Int { get } +} +#endif + +extension NSSet : NMBCollection {} +extension NSDictionary : NMBCollection {} + +#if _runtime(_ObjC) +/// Protocol for types that support beginWith(), endWith(), beEmpty() matchers +@objc public protocol NMBOrderedCollection : NMBCollection { + func indexOfObject(object: AnyObject!) -> Int +} +#else +public protocol NMBOrderedCollection : NMBCollection { + func indexOfObject(object: AnyObject) -> Int +} +#endif + +extension NSArray : NMBOrderedCollection {} + +#if _runtime(_ObjC) +/// Protocol for types to support beCloseTo() matcher +@objc public protocol NMBDoubleConvertible { + var doubleValue: CDouble { get } +} +#else +public protocol NMBDoubleConvertible { + var doubleValue: CDouble { get } +} + +extension Double : NMBDoubleConvertible { + public var doubleValue: CDouble { + get { + return self + } + } +} + +extension Float : NMBDoubleConvertible { + public var doubleValue: CDouble { + get { + return CDouble(self) + } + } +} +#endif + +extension NSNumber : NMBDoubleConvertible { +} + +private let dateFormatter: NSDateFormatter = { + let formatter = NSDateFormatter() + formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS" + formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") + + return formatter +}() + +#if _runtime(_ObjC) +extension NSDate: NMBDoubleConvertible { + public var doubleValue: CDouble { + get { + return self.timeIntervalSinceReferenceDate + } + } +} +#endif + + +extension NMBDoubleConvertible { + public var stringRepresentation: String { + get { + if let date = self as? NSDate { + return dateFormatter.stringFromDate(date) + } + + if let debugStringConvertible = self as? CustomDebugStringConvertible { + return debugStringConvertible.debugDescription + } + + if let stringConvertible = self as? CustomStringConvertible { + return stringConvertible.description + } + + return "" + } + } +} + +/// Protocol for types to support beLessThan(), beLessThanOrEqualTo(), +/// beGreaterThan(), beGreaterThanOrEqualTo(), and equal() matchers. +/// +/// Types that conform to Swift's Comparable protocol will work implicitly too +#if _runtime(_ObjC) +@objc public protocol NMBComparable { + func NMB_compare(otherObject: NMBComparable!) -> NSComparisonResult +} +#else +// This should become obsolete once Corelibs Foundation adds Comparable conformance to NSNumber +public protocol NMBComparable { + func NMB_compare(otherObject: NMBComparable!) -> NSComparisonResult +} +#endif + +extension NSNumber : NMBComparable { + public func NMB_compare(otherObject: NMBComparable!) -> NSComparisonResult { + return compare(otherObject as! NSNumber) + } +} +extension NSString : NMBComparable { + public func NMB_compare(otherObject: NMBComparable!) -> NSComparisonResult { + return compare(otherObject as! String) + } +} diff --git a/Pods/Nimble/Sources/Nimble/Matchers/PostNotification.swift b/Pods/Nimble/Sources/Nimble/Matchers/PostNotification.swift new file mode 100644 index 0000000..0191f88 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/PostNotification.swift @@ -0,0 +1,66 @@ +import Foundation + +internal class NotificationCollector { + private(set) var observedNotifications: [NSNotification] + private let notificationCenter: NSNotificationCenter + #if _runtime(_ObjC) + private var token: AnyObject? + #else + private var token: NSObjectProtocol? + #endif + + required init(notificationCenter: NSNotificationCenter) { + self.notificationCenter = notificationCenter + self.observedNotifications = [] + } + + func startObserving() { + self.token = self.notificationCenter.addObserverForName(nil, object: nil, queue: nil) { + // linux-swift gets confused by .append(n) + [weak self] n in self?.observedNotifications += [n] + } + } + + deinit { + #if _runtime(_ObjC) + if let token = self.token { + self.notificationCenter.removeObserver(token) + } + #else + if let token = self.token as? AnyObject { + self.notificationCenter.removeObserver(token) + } + #endif + } +} + +private let mainThread = pthread_self() + +public func postNotifications( + notificationsMatcher: T, + fromNotificationCenter center: NSNotificationCenter = NSNotificationCenter.defaultCenter()) + -> MatcherFunc { + let _ = mainThread // Force lazy-loading of this value + let collector = NotificationCollector(notificationCenter: center) + collector.startObserving() + var once: Bool = false + return MatcherFunc { actualExpression, failureMessage in + let collectorNotificationsExpression = Expression(memoizedExpression: { _ in + return collector.observedNotifications + }, location: actualExpression.location, withoutCaching: true) + + assert(pthread_equal(mainThread, pthread_self()) != 0, "Only expecting closure to be evaluated on main thread.") + if !once { + once = true + try actualExpression.evaluate() + } + + let match = try notificationsMatcher.matches(collectorNotificationsExpression, failureMessage: failureMessage) + if collector.observedNotifications.isEmpty { + failureMessage.actualValue = "no notifications" + } else { + failureMessage.actualValue = "<\(stringify(collector.observedNotifications))>" + } + return match + } +} \ No newline at end of file diff --git a/Pods/Nimble/Sources/Nimble/Matchers/RaisesException.swift b/Pods/Nimble/Sources/Nimble/Matchers/RaisesException.swift new file mode 100644 index 0000000..ff6b74a --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/RaisesException.swift @@ -0,0 +1,182 @@ +import Foundation + +// This matcher requires the Objective-C, and being built by Xcode rather than the Swift Package Manager +#if _runtime(_ObjC) && !SWIFT_PACKAGE + +/// A Nimble matcher that succeeds when the actual expression raises an +/// exception with the specified name, reason, and/or userInfo. +/// +/// Alternatively, you can pass a closure to do any arbitrary custom matching +/// to the raised exception. The closure only gets called when an exception +/// is raised. +/// +/// nil arguments indicates that the matcher should not attempt to match against +/// that parameter. +public func raiseException( + named named: String? = nil, + reason: String? = nil, + userInfo: NSDictionary? = nil, + closure: ((NSException) -> Void)? = nil) -> MatcherFunc { + return MatcherFunc { actualExpression, failureMessage in + + var exception: NSException? + let capture = NMBExceptionCapture(handler: ({ e in + exception = e + }), finally: nil) + + capture.tryBlock { + try! actualExpression.evaluate() + return + } + + setFailureMessageForException(failureMessage, exception: exception, named: named, reason: reason, userInfo: userInfo, closure: closure) + return exceptionMatchesNonNilFieldsOrClosure(exception, named: named, reason: reason, userInfo: userInfo, closure: closure) + } +} + +internal func setFailureMessageForException( + failureMessage: FailureMessage, + exception: NSException?, + named: String?, + reason: String?, + userInfo: NSDictionary?, + closure: ((NSException) -> Void)?) { + failureMessage.postfixMessage = "raise exception" + + if let named = named { + failureMessage.postfixMessage += " with name <\(named)>" + } + if let reason = reason { + failureMessage.postfixMessage += " with reason <\(reason)>" + } + if let userInfo = userInfo { + failureMessage.postfixMessage += " with userInfo <\(userInfo)>" + } + if let _ = closure { + failureMessage.postfixMessage += " that satisfies block" + } + if named == nil && reason == nil && userInfo == nil && closure == nil { + failureMessage.postfixMessage = "raise any exception" + } + + if let exception = exception { + failureMessage.actualValue = "\(classAsString(exception.dynamicType)) { name=\(exception.name), reason='\(stringify(exception.reason))', userInfo=\(stringify(exception.userInfo)) }" + } else { + failureMessage.actualValue = "no exception" + } +} + +internal func exceptionMatchesNonNilFieldsOrClosure( + exception: NSException?, + named: String?, + reason: String?, + userInfo: NSDictionary?, + closure: ((NSException) -> Void)?) -> Bool { + var matches = false + + if let exception = exception { + matches = true + + if named != nil && exception.name != named { + matches = false + } + if reason != nil && exception.reason != reason { + matches = false + } + if userInfo != nil && exception.userInfo != userInfo { + matches = false + } + if let closure = closure { + let assertions = gatherFailingExpectations { + closure(exception) + } + let messages = assertions.map { $0.message } + if messages.count > 0 { + matches = false + } + } + } + + return matches +} + +public class NMBObjCRaiseExceptionMatcher : NSObject, NMBMatcher { + internal var _name: String? + internal var _reason: String? + internal var _userInfo: NSDictionary? + internal var _block: ((NSException) -> Void)? + + internal init(name: String?, reason: String?, userInfo: NSDictionary?, block: ((NSException) -> Void)?) { + _name = name + _reason = reason + _userInfo = userInfo + _block = block + } + + public func matches(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { + let block: () -> Any? = ({ actualBlock(); return nil }) + let expr = Expression(expression: block, location: location) + + return try! raiseException( + named: _name, + reason: _reason, + userInfo: _userInfo, + closure: _block + ).matches(expr, failureMessage: failureMessage) + } + + public func doesNotMatch(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { + return !matches(actualBlock, failureMessage: failureMessage, location: location) + } + + public var named: (name: String) -> NMBObjCRaiseExceptionMatcher { + return ({ name in + return NMBObjCRaiseExceptionMatcher( + name: name, + reason: self._reason, + userInfo: self._userInfo, + block: self._block + ) + }) + } + + public var reason: (reason: String?) -> NMBObjCRaiseExceptionMatcher { + return ({ reason in + return NMBObjCRaiseExceptionMatcher( + name: self._name, + reason: reason, + userInfo: self._userInfo, + block: self._block + ) + }) + } + + public var userInfo: (userInfo: NSDictionary?) -> NMBObjCRaiseExceptionMatcher { + return ({ userInfo in + return NMBObjCRaiseExceptionMatcher( + name: self._name, + reason: self._reason, + userInfo: userInfo, + block: self._block + ) + }) + } + + public var satisfyingBlock: (block: ((NSException) -> Void)?) -> NMBObjCRaiseExceptionMatcher { + return ({ block in + return NMBObjCRaiseExceptionMatcher( + name: self._name, + reason: self._reason, + userInfo: self._userInfo, + block: block + ) + }) + } +} + +extension NMBObjCMatcher { + public class func raiseExceptionMatcher() -> NMBObjCRaiseExceptionMatcher { + return NMBObjCRaiseExceptionMatcher(name: nil, reason: nil, userInfo: nil, block: nil) + } +} +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/SatisfyAnyOf.swift b/Pods/Nimble/Sources/Nimble/Matchers/SatisfyAnyOf.swift new file mode 100644 index 0000000..ddeddde --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/SatisfyAnyOf.swift @@ -0,0 +1,65 @@ +import Foundation + +/// A Nimble matcher that succeeds when the actual value matches with any of the matchers +/// provided in the variable list of matchers. +public func satisfyAnyOf(matchers: U...) -> NonNilMatcherFunc { + return satisfyAnyOf(matchers) +} + +internal func satisfyAnyOf(matchers: [U]) -> NonNilMatcherFunc { + return NonNilMatcherFunc { actualExpression, failureMessage in + let postfixMessages = NSMutableArray() + var matches = false + for matcher in matchers { + if try matcher.matches(actualExpression, failureMessage: failureMessage) { + matches = true + } + postfixMessages.addObject(NSString(string: "{\(failureMessage.postfixMessage)}")) + } + + failureMessage.postfixMessage = "match one of: " + postfixMessages.componentsJoinedByString(", or ") + if let actualValue = try actualExpression.evaluate() { + failureMessage.actualValue = "\(actualValue)" + } + + return matches + } +} + +public func ||(left: NonNilMatcherFunc, right: NonNilMatcherFunc) -> NonNilMatcherFunc { + return satisfyAnyOf(left, right) +} + +public func ||(left: FullMatcherFunc, right: FullMatcherFunc) -> NonNilMatcherFunc { + return satisfyAnyOf(left, right) +} + +public func ||(left: MatcherFunc, right: MatcherFunc) -> NonNilMatcherFunc { + return satisfyAnyOf(left, right) +} + +#if _runtime(_ObjC) +extension NMBObjCMatcher { + public class func satisfyAnyOfMatcher(matchers: [NMBObjCMatcher]) -> NMBObjCMatcher { + return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in + if matchers.isEmpty { + failureMessage.stringValue = "satisfyAnyOf must be called with at least one matcher" + return false + } + + var elementEvaluators = [NonNilMatcherFunc]() + for matcher in matchers { + let elementEvaluator: (Expression, FailureMessage) -> Bool = { + expression, failureMessage in + return matcher.matches( + {try! expression.evaluate()}, failureMessage: failureMessage, location: actualExpression.location) + } + + elementEvaluators.append(NonNilMatcherFunc(elementEvaluator)) + } + + return try! satisfyAnyOf(elementEvaluators).matches(actualExpression, failureMessage: failureMessage) + } + } +} +#endif diff --git a/Pods/Nimble/Sources/Nimble/Matchers/ThrowError.swift b/Pods/Nimble/Sources/Nimble/Matchers/ThrowError.swift new file mode 100644 index 0000000..c12e31c --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Matchers/ThrowError.swift @@ -0,0 +1,181 @@ +import Foundation + +/// A Nimble matcher that succeeds when the actual expression throws an +/// error of the specified type or from the specified case. +/// +/// Errors are tried to be compared by their implementation of Equatable, +/// otherwise they fallback to comparision by _domain and _code. +/// +/// Alternatively, you can pass a closure to do any arbitrary custom matching +/// to the thrown error. The closure only gets called when an error was thrown. +/// +/// nil arguments indicates that the matcher should not attempt to match against +/// that parameter. +public func throwError( + error: T? = nil, + errorType: T.Type? = nil, + closure: ((T) -> Void)? = nil) -> MatcherFunc { + return MatcherFunc { actualExpression, failureMessage in + + var actualError: ErrorType? + do { + try actualExpression.evaluate() + } catch let catchedError { + actualError = catchedError + } + + setFailureMessageForError(failureMessage, actualError: actualError, error: error, errorType: errorType, closure: closure) + return errorMatchesNonNilFieldsOrClosure(actualError, error: error, errorType: errorType, closure: closure) + } +} + +internal func setFailureMessageForError( + failureMessage: FailureMessage, + actualError: ErrorType?, + error: T?, + errorType: T.Type? = nil, + closure: ((T) -> Void)?) { + failureMessage.postfixMessage = "throw error" + + if let error = error { + if let error = error as? CustomDebugStringConvertible { + failureMessage.postfixMessage += " <\(error.debugDescription)>" + } else { + failureMessage.postfixMessage += " <\(error)>" + } + } else if errorType != nil || closure != nil { + failureMessage.postfixMessage += " from type <\(T.self)>" + } + if let _ = closure { + failureMessage.postfixMessage += " that satisfies block" + } + if error == nil && errorType == nil && closure == nil { + failureMessage.postfixMessage = "throw any error" + } + + if let actualError = actualError { + failureMessage.actualValue = "<\(actualError)>" + } else { + failureMessage.actualValue = "no error" + } +} + +internal func errorMatchesExpectedError( + actualError: ErrorType, + expectedError: T) -> Bool { + return actualError._domain == expectedError._domain + && actualError._code == expectedError._code +} + +internal func errorMatchesExpectedError( + actualError: ErrorType, + expectedError: T) -> Bool { + if let actualError = actualError as? T { + return actualError == expectedError + } + return false +} + +internal func errorMatchesNonNilFieldsOrClosure( + actualError: ErrorType?, + error: T?, + errorType: T.Type?, + closure: ((T) -> Void)?) -> Bool { + var matches = false + + if let actualError = actualError { + matches = true + + if let error = error { + if !errorMatchesExpectedError(actualError, expectedError: error) { + matches = false + } + } + if let actualError = actualError as? T { + if let closure = closure { + let assertions = gatherFailingExpectations { + closure(actualError as T) + } + let messages = assertions.map { $0.message } + if messages.count > 0 { + matches = false + } + } + } else if errorType != nil && closure != nil { + // The closure expects another ErrorType as argument, so this + // is _supposed_ to fail, so that it becomes more obvious. + let assertions = gatherExpectations { + expect(actualError is T).to(equal(true)) + } + precondition(assertions.map { $0.message }.count > 0) + matches = false + } + } + + return matches +} + + +/// A Nimble matcher that succeeds when the actual expression throws any +/// error or when the passed closures' arbitrary custom matching succeeds. +/// +/// This duplication to it's generic adequate is required to allow to receive +/// values of the existential type ErrorType in the closure. +/// +/// The closure only gets called when an error was thrown. +public func throwError( + closure closure: ((ErrorType) -> Void)? = nil) -> MatcherFunc { + return MatcherFunc { actualExpression, failureMessage in + + var actualError: ErrorType? + do { + try actualExpression.evaluate() + } catch let catchedError { + actualError = catchedError + } + + setFailureMessageForError(failureMessage, actualError: actualError, closure: closure) + return errorMatchesNonNilFieldsOrClosure(actualError, closure: closure) + } +} + +internal func setFailureMessageForError( + failureMessage: FailureMessage, + actualError: ErrorType?, + closure: ((ErrorType) -> Void)?) { + failureMessage.postfixMessage = "throw error" + + if let _ = closure { + failureMessage.postfixMessage += " that satisfies block" + } else { + failureMessage.postfixMessage = "throw any error" + } + + if let actualError = actualError { + failureMessage.actualValue = "<\(actualError)>" + } else { + failureMessage.actualValue = "no error" + } +} + +internal func errorMatchesNonNilFieldsOrClosure( + actualError: ErrorType?, + closure: ((ErrorType) -> Void)?) -> Bool { + var matches = false + + if let actualError = actualError { + matches = true + + if let closure = closure { + let assertions = gatherFailingExpectations { + closure(actualError) + } + let messages = assertions.map { $0.message } + if messages.count > 0 { + matches = false + } + } + } + + return matches +} diff --git a/Pods/Nimble/Sources/Nimble/Nimble.h b/Pods/Nimble/Sources/Nimble/Nimble.h new file mode 100644 index 0000000..296760c --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Nimble.h @@ -0,0 +1,6 @@ +#import +#import "NMBExceptionCapture.h" +#import "DSL.h" + +FOUNDATION_EXPORT double NimbleVersionNumber; +FOUNDATION_EXPORT const unsigned char NimbleVersionString[]; \ No newline at end of file diff --git a/Pods/Nimble/Sources/Nimble/ObjCExpectation.swift b/Pods/Nimble/Sources/Nimble/ObjCExpectation.swift new file mode 100644 index 0000000..3f18d06 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/ObjCExpectation.swift @@ -0,0 +1,131 @@ +import Foundation + +#if _runtime(_ObjC) + +internal struct ObjCMatcherWrapper : Matcher { + let matcher: NMBMatcher + + func matches(actualExpression: Expression, failureMessage: FailureMessage) -> Bool { + return matcher.matches( + ({ try! actualExpression.evaluate() }), + failureMessage: failureMessage, + location: actualExpression.location) + } + + func doesNotMatch(actualExpression: Expression, failureMessage: FailureMessage) -> Bool { + return matcher.doesNotMatch( + ({ try! actualExpression.evaluate() }), + failureMessage: failureMessage, + location: actualExpression.location) + } +} + +// Equivalent to Expectation, but for Nimble's Objective-C interface +public class NMBExpectation : NSObject { + internal let _actualBlock: () -> NSObject! + internal var _negative: Bool + internal let _file: FileString + internal let _line: UInt + internal var _timeout: NSTimeInterval = 1.0 + + public init(actualBlock: () -> NSObject!, negative: Bool, file: FileString, line: UInt) { + self._actualBlock = actualBlock + self._negative = negative + self._file = file + self._line = line + } + + private var expectValue: Expectation { + return expect(_file, line: _line){ + self._actualBlock() as NSObject? + } + } + + public var withTimeout: (NSTimeInterval) -> NMBExpectation { + return ({ timeout in self._timeout = timeout + return self + }) + } + + public var to: (NMBMatcher) -> Void { + return ({ matcher in + self.expectValue.to(ObjCMatcherWrapper(matcher: matcher)) + }) + } + + public var toWithDescription: (NMBMatcher, String) -> Void { + return ({ matcher, description in + self.expectValue.to(ObjCMatcherWrapper(matcher: matcher), description: description) + }) + } + + public var toNot: (NMBMatcher) -> Void { + return ({ matcher in + self.expectValue.toNot( + ObjCMatcherWrapper(matcher: matcher) + ) + }) + } + + public var toNotWithDescription: (NMBMatcher, String) -> Void { + return ({ matcher, description in + self.expectValue.toNot( + ObjCMatcherWrapper(matcher: matcher), description: description + ) + }) + } + + public var notTo: (NMBMatcher) -> Void { return toNot } + + public var notToWithDescription: (NMBMatcher, String) -> Void { return toNotWithDescription } + + public var toEventually: (NMBMatcher) -> Void { + return ({ matcher in + self.expectValue.toEventually( + ObjCMatcherWrapper(matcher: matcher), + timeout: self._timeout, + description: nil + ) + }) + } + + public var toEventuallyWithDescription: (NMBMatcher, String) -> Void { + return ({ matcher, description in + self.expectValue.toEventually( + ObjCMatcherWrapper(matcher: matcher), + timeout: self._timeout, + description: description + ) + }) + } + + public var toEventuallyNot: (NMBMatcher) -> Void { + return ({ matcher in + self.expectValue.toEventuallyNot( + ObjCMatcherWrapper(matcher: matcher), + timeout: self._timeout, + description: nil + ) + }) + } + + public var toEventuallyNotWithDescription: (NMBMatcher, String) -> Void { + return ({ matcher, description in + self.expectValue.toEventuallyNot( + ObjCMatcherWrapper(matcher: matcher), + timeout: self._timeout, + description: description + ) + }) + } + + public var toNotEventually: (NMBMatcher) -> Void { return toEventuallyNot } + + public var toNotEventuallyWithDescription: (NMBMatcher, String) -> Void { return toEventuallyNotWithDescription } + + public class func failWithMessage(message: String, file: FileString, line: UInt) { + fail(message, location: SourceLocation(file: file, line: line)) + } +} + +#endif diff --git a/Pods/Nimble/Sources/Nimble/Utils/Async.swift b/Pods/Nimble/Sources/Nimble/Utils/Async.swift new file mode 100644 index 0000000..2a86749 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Utils/Async.swift @@ -0,0 +1,358 @@ +import Foundation + +#if _runtime(_ObjC) +import Dispatch + +private let timeoutLeeway: UInt64 = NSEC_PER_MSEC +private let pollLeeway: UInt64 = NSEC_PER_MSEC + +/// Stores debugging information about callers +internal struct WaitingInfo: CustomStringConvertible { + let name: String + let file: FileString + let lineNumber: UInt + + var description: String { + return "\(name) at \(file):\(lineNumber)" + } +} + +internal protocol WaitLock { + func acquireWaitingLock(fnName: String, file: FileString, line: UInt) + func releaseWaitingLock() + func isWaitingLocked() -> Bool +} + +internal class AssertionWaitLock: WaitLock { + private var currentWaiter: WaitingInfo? = nil + init() { } + + func acquireWaitingLock(fnName: String, file: FileString, line: UInt) { + let info = WaitingInfo(name: fnName, file: file, lineNumber: line) + nimblePrecondition( + NSThread.isMainThread(), + "InvalidNimbleAPIUsage", + "\(fnName) can only run on the main thread." + ) + nimblePrecondition( + currentWaiter == nil, + "InvalidNimbleAPIUsage", + "Nested async expectations are not allowed to avoid creating flaky tests.\n\n" + + "The call to\n\t\(info)\n" + + "triggered this exception because\n\t\(currentWaiter!)\n" + + "is currently managing the main run loop." + ) + currentWaiter = info + } + + func isWaitingLocked() -> Bool { + return currentWaiter != nil + } + + func releaseWaitingLock() { + currentWaiter = nil + } +} + +internal enum AwaitResult { + /// Incomplete indicates None (aka - this value hasn't been fulfilled yet) + case Incomplete + /// TimedOut indicates the result reached its defined timeout limit before returning + case TimedOut + /// BlockedRunLoop indicates the main runloop is too busy processing other blocks to trigger + /// the timeout code. + /// + /// This may also mean the async code waiting upon may have never actually ran within the + /// required time because other timers & sources are running on the main run loop. + case BlockedRunLoop + /// The async block successfully executed and returned a given result + case Completed(T) + /// When a Swift Error is thrown + case ErrorThrown(ErrorType) + /// When an Objective-C Exception is raised + case RaisedException(NSException) + + func isIncomplete() -> Bool { + switch self { + case .Incomplete: return true + default: return false + } + } + + func isCompleted() -> Bool { + switch self { + case .Completed(_): return true + default: return false + } + } +} + +/// Holds the resulting value from an asynchronous expectation. +/// This class is thread-safe at receiving an "response" to this promise. +internal class AwaitPromise { + private(set) internal var asyncResult: AwaitResult = .Incomplete + private var signal: dispatch_semaphore_t + + init() { + signal = dispatch_semaphore_create(1) + } + + /// Resolves the promise with the given result if it has not been resolved. Repeated calls to + /// this method will resolve in a no-op. + /// + /// @returns a Bool that indicates if the async result was accepted or rejected because another + /// value was recieved first. + func resolveResult(result: AwaitResult) -> Bool { + if dispatch_semaphore_wait(signal, DISPATCH_TIME_NOW) == 0 { + self.asyncResult = result + return true + } else { + return false + } + } +} + +internal struct AwaitTrigger { + let timeoutSource: dispatch_source_t + let actionSource: dispatch_source_t? + let start: () throws -> Void +} + +/// Factory for building fully configured AwaitPromises and waiting for their results. +/// +/// This factory stores all the state for an async expectation so that Await doesn't +/// doesn't have to manage it. +internal class AwaitPromiseBuilder { + let awaiter: Awaiter + let waitLock: WaitLock + let trigger: AwaitTrigger + let promise: AwaitPromise + + internal init( + awaiter: Awaiter, + waitLock: WaitLock, + promise: AwaitPromise, + trigger: AwaitTrigger) { + self.awaiter = awaiter + self.waitLock = waitLock + self.promise = promise + self.trigger = trigger + } + + func timeout(timeoutInterval: NSTimeInterval, forcefullyAbortTimeout: NSTimeInterval) -> Self { + // = Discussion = + // + // There's a lot of technical decisions here that is useful to elaborate on. This is + // definitely more lower-level than the previous NSRunLoop based implementation. + // + // + // Why Dispatch Source? + // + // + // We're using a dispatch source to have better control of the run loop behavior. + // A timer source gives us deferred-timing control without having to rely as much on + // a run loop's traditional dispatching machinery (eg - NSTimers, DefaultRunLoopMode, etc.) + // which is ripe for getting corrupted by application code. + // + // And unlike dispatch_async(), we can control how likely our code gets prioritized to + // executed (see leeway parameter) + DISPATCH_TIMER_STRICT. + // + // This timer is assumed to run on the HIGH priority queue to ensure it maintains the + // highest priority over normal application / test code when possible. + // + // + // Run Loop Management + // + // In order to properly interrupt the waiting behavior performed by this factory class, + // this timer stops the main run loop to tell the waiter code that the result should be + // checked. + // + // In addition, stopping the run loop is used to halt code executed on the main run loop. + dispatch_source_set_timer( + trigger.timeoutSource, + dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutInterval * Double(NSEC_PER_SEC))), + DISPATCH_TIME_FOREVER, + timeoutLeeway + ) + dispatch_source_set_event_handler(trigger.timeoutSource) { + guard self.promise.asyncResult.isIncomplete() else { return } + let timedOutSem = dispatch_semaphore_create(0) + let semTimedOutOrBlocked = dispatch_semaphore_create(0) + dispatch_semaphore_signal(semTimedOutOrBlocked) + let runLoop = CFRunLoopGetMain() + CFRunLoopPerformBlock(runLoop, kCFRunLoopDefaultMode) { + if dispatch_semaphore_wait(semTimedOutOrBlocked, DISPATCH_TIME_NOW) == 0 { + dispatch_semaphore_signal(timedOutSem) + dispatch_semaphore_signal(semTimedOutOrBlocked) + if self.promise.resolveResult(.TimedOut) { + CFRunLoopStop(CFRunLoopGetMain()) + } + } + } + // potentially interrupt blocking code on run loop to let timeout code run + CFRunLoopStop(runLoop) + let now = dispatch_time(DISPATCH_TIME_NOW, Int64(forcefullyAbortTimeout * Double(NSEC_PER_SEC))) + let didNotTimeOut = dispatch_semaphore_wait(timedOutSem, now) != 0 + let timeoutWasNotTriggered = dispatch_semaphore_wait(semTimedOutOrBlocked, 0) == 0 + if didNotTimeOut && timeoutWasNotTriggered { + if self.promise.resolveResult(.BlockedRunLoop) { + CFRunLoopStop(CFRunLoopGetMain()) + } + } + } + return self + } + + /// Blocks for an asynchronous result. + /// + /// @discussion + /// This function must be executed on the main thread and cannot be nested. This is because + /// this function (and it's related methods) coordinate through the main run loop. Tampering + /// with the run loop can cause undesireable behavior. + /// + /// This method will return an AwaitResult in the following cases: + /// + /// - The main run loop is blocked by other operations and the async expectation cannot be + /// be stopped. + /// - The async expectation timed out + /// - The async expectation succeeded + /// - The async expectation raised an unexpected exception (objc) + /// - The async expectation raised an unexpected error (swift) + /// + /// The returned AwaitResult will NEVER be .Incomplete. + func wait(fnName: String = __FUNCTION__, file: FileString = __FILE__, line: UInt = __LINE__) -> AwaitResult { + waitLock.acquireWaitingLock( + fnName, + file: file, + line: line) + + let capture = NMBExceptionCapture(handler: ({ exception in + self.promise.resolveResult(.RaisedException(exception)) + }), finally: ({ + self.waitLock.releaseWaitingLock() + })) + capture.tryBlock { + do { + try self.trigger.start() + } catch let error { + self.promise.resolveResult(.ErrorThrown(error)) + } + dispatch_resume(self.trigger.timeoutSource) + while self.promise.asyncResult.isIncomplete() { + // Stopping the run loop does not work unless we run only 1 mode + NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture()) + } + dispatch_suspend(self.trigger.timeoutSource) + dispatch_source_cancel(self.trigger.timeoutSource) + if let asyncSource = self.trigger.actionSource { + dispatch_source_cancel(asyncSource) + } + } + + return promise.asyncResult + } +} + +internal class Awaiter { + let waitLock: WaitLock + let timeoutQueue: dispatch_queue_t + let asyncQueue: dispatch_queue_t + + internal init( + waitLock: WaitLock, + asyncQueue: dispatch_queue_t, + timeoutQueue: dispatch_queue_t) { + self.waitLock = waitLock + self.asyncQueue = asyncQueue + self.timeoutQueue = timeoutQueue + } + + private func createTimerSource(queue: dispatch_queue_t) -> dispatch_source_t { + return dispatch_source_create( + DISPATCH_SOURCE_TYPE_TIMER, + 0, + DISPATCH_TIMER_STRICT, + queue + ) + } + + func performBlock( + closure: ((T) -> Void) throws -> Void) -> AwaitPromiseBuilder { + let promise = AwaitPromise() + let timeoutSource = createTimerSource(timeoutQueue) + var completionCount = 0 + let trigger = AwaitTrigger(timeoutSource: timeoutSource, actionSource: nil) { + try closure() { + completionCount += 1 + nimblePrecondition( + completionCount < 2, + "InvalidNimbleAPIUsage", + "Done closure's was called multiple times. waitUntil(..) expects its " + + "completion closure to only be called once.") + if promise.resolveResult(.Completed($0)) { + CFRunLoopStop(CFRunLoopGetMain()) + } + } + } + + return AwaitPromiseBuilder( + awaiter: self, + waitLock: waitLock, + promise: promise, + trigger: trigger) + } + + func poll(pollInterval: NSTimeInterval, closure: () throws -> T?) -> AwaitPromiseBuilder { + let promise = AwaitPromise() + let timeoutSource = createTimerSource(timeoutQueue) + let asyncSource = createTimerSource(asyncQueue) + let trigger = AwaitTrigger(timeoutSource: timeoutSource, actionSource: asyncSource) { + let interval = UInt64(pollInterval * Double(NSEC_PER_SEC)) + dispatch_source_set_timer(asyncSource, DISPATCH_TIME_NOW, interval, pollLeeway) + dispatch_source_set_event_handler(asyncSource) { + do { + if let result = try closure() { + if promise.resolveResult(.Completed(result)) { + CFRunLoopStop(CFRunLoopGetCurrent()) + } + } + } catch let error { + if promise.resolveResult(.ErrorThrown(error)) { + CFRunLoopStop(CFRunLoopGetCurrent()) + } + } + } + dispatch_resume(asyncSource) + } + + return AwaitPromiseBuilder( + awaiter: self, + waitLock: waitLock, + promise: promise, + trigger: trigger) + } +} + +internal func pollBlock( + pollInterval pollInterval: NSTimeInterval, + timeoutInterval: NSTimeInterval, + file: FileString, + line: UInt, + fnName: String = __FUNCTION__, + expression: () throws -> Bool) -> AwaitResult { + let awaiter = NimbleEnvironment.activeInstance.awaiter + let result = awaiter.poll(pollInterval) { () throws -> Bool? in + do { + if try expression() { + return true + } + return nil + } catch let error { + throw error + } + }.timeout(timeoutInterval, forcefullyAbortTimeout: timeoutInterval / 2.0).wait(fnName, file: file, line: line) + + return result +} + +#endif diff --git a/Pods/Nimble/Sources/Nimble/Utils/ExceptionCapture.swift b/Pods/Nimble/Sources/Nimble/Utils/ExceptionCapture.swift new file mode 100644 index 0000000..e94c45f --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Utils/ExceptionCapture.swift @@ -0,0 +1,31 @@ +import Foundation + +#if !_runtime(_ObjC) +// swift-corelibs-foundation doesn't provide NSException at all, so provide a dummy +class NSException {} +#endif + +// NOTE: This file is not intended to be included in the Xcode project. It +// is picked up by the Swift Package Manager during its build process. + +/// A dummy reimplementation of the `NMBExceptionCapture` class to serve +/// as a stand-in for build and runtime environments that don't support +/// Objective C. +internal class ExceptionCapture { + let finally: (() -> Void)? + + init(handler: ((NSException!) -> Void)?, finally: (() -> Void)?) { + self.finally = finally + } + + func tryBlock(unsafeBlock: (() -> Void)) { + // We have no way of handling Objective C exceptions in Swift, + // so we just go ahead and run the unsafeBlock as-is + unsafeBlock() + + finally?() + } +} + +/// Compatibility with the actual Objective-C implementation +typealias NMBExceptionCapture = ExceptionCapture diff --git a/Pods/Nimble/Sources/Nimble/Utils/Functional.swift b/Pods/Nimble/Sources/Nimble/Utils/Functional.swift new file mode 100644 index 0000000..e85c755 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Utils/Functional.swift @@ -0,0 +1,12 @@ +import Foundation + +extension SequenceType { + internal func all(fn: Generator.Element -> Bool) -> Bool { + for item in self { + if !fn(item) { + return false + } + } + return true + } +} diff --git a/Pods/Nimble/Sources/Nimble/Utils/SourceLocation.swift b/Pods/Nimble/Sources/Nimble/Utils/SourceLocation.swift new file mode 100644 index 0000000..a7279aa --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Utils/SourceLocation.swift @@ -0,0 +1,31 @@ +import Foundation + +// Ideally we would always use `StaticString` as the type for tracking the file name +// that expectations originate from, for consistency with `assert` etc. from the +// stdlib, and because recent versions of the XCTest overlay require `StaticString` +// when calling `XCTFail`. Under the Objective-C runtime (i.e. building on Mac), we +// have to use `String` instead because StaticString can't be generated from Objective-C +#if _runtime(_ObjC) +public typealias FileString = String +#else +public typealias FileString = StaticString +#endif + +public final class SourceLocation : NSObject { + public let file: FileString + public let line: UInt + + override init() { + file = "Unknown File" + line = 0 + } + + init(file: FileString, line: UInt) { + self.file = file + self.line = line + } + + override public var description: String { + return "\(file):\(line)" + } +} diff --git a/Pods/Nimble/Sources/Nimble/Utils/Stringers.swift b/Pods/Nimble/Sources/Nimble/Utils/Stringers.swift new file mode 100644 index 0000000..3faab96 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Utils/Stringers.swift @@ -0,0 +1,80 @@ +import Foundation + + +internal func identityAsString(value: AnyObject?) -> String { + if let value = value { + return NSString(format: "<%p>", unsafeBitCast(value, Int.self)).description + } else { + return "nil" + } +} + +internal func classAsString(cls: AnyClass) -> String { +#if _runtime(_ObjC) + return NSStringFromClass(cls) +#else + return String(cls) +#endif +} + +internal func arrayAsString(items: [T], joiner: String = ", ") -> String { + return items.reduce("") { accum, item in + let prefix = (accum.isEmpty ? "" : joiner) + return accum + prefix + "\(stringify(item))" + } +} + +#if _runtime(_ObjC) +@objc internal protocol NMBStringer { + func NMB_stringify() -> String +} + +extension NSArray : NMBStringer { + func NMB_stringify() -> String { + let str = self.componentsJoinedByString(", ") + return "[\(str)]" + } +} +#endif + +internal func stringify(value: S) -> String { + var generator = value.generate() + var strings = [String]() + var value: S.Generator.Element? + repeat { + value = generator.next() + if value != nil { + strings.append(stringify(value)) + } + } while value != nil + let str = strings.joinWithSeparator(", ") + return "[\(str)]" +} + +internal func stringify(value: T) -> String { + if let value = value as? Double { + return NSString(format: "%.4f", (value)).description + } else if let value = value as? NSData { +#if os(Linux) + // FIXME: Swift on Linux triggers a segfault when calling NSData's hash() (last checked on 03-11) + return "NSData" +#else + return "NSData" +#endif + } + return String(value) +} + +internal func stringify(value: NMBDoubleConvertible) -> String { + if let value = value as? Double { + return NSString(format: "%.4f", (value)).description + } + return value.stringRepresentation +} + +internal func stringify(value: T?) -> String { + if let unboxed = value { + return stringify(unboxed) + } + return "nil" +} diff --git a/Pods/Nimble/Sources/Nimble/Wrappers/AsyncMatcherWrapper.swift b/Pods/Nimble/Sources/Nimble/Wrappers/AsyncMatcherWrapper.swift new file mode 100644 index 0000000..3df6eb6 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Wrappers/AsyncMatcherWrapper.swift @@ -0,0 +1,140 @@ +import Foundation + +#if _runtime(_ObjC) + +public struct AsyncDefaults { + public static var Timeout: NSTimeInterval = 1 + public static var PollInterval: NSTimeInterval = 0.01 +} + +internal struct AsyncMatcherWrapper: Matcher { + let fullMatcher: U + let timeoutInterval: NSTimeInterval + let pollInterval: NSTimeInterval + + init(fullMatcher: U, timeoutInterval: NSTimeInterval = AsyncDefaults.Timeout, pollInterval: NSTimeInterval = AsyncDefaults.PollInterval) { + self.fullMatcher = fullMatcher + self.timeoutInterval = timeoutInterval + self.pollInterval = pollInterval + } + + func matches(actualExpression: Expression, failureMessage: FailureMessage) -> Bool { + let uncachedExpression = actualExpression.withoutCaching() + let fnName = "expect(...).toEventually(...)" + let result = pollBlock( + pollInterval: pollInterval, + timeoutInterval: timeoutInterval, + file: actualExpression.location.file, + line: actualExpression.location.line, + fnName: fnName) { + try self.fullMatcher.matches(uncachedExpression, failureMessage: failureMessage) + } + switch (result) { + case let .Completed(isSuccessful): return isSuccessful + case .TimedOut: return false + case let .ErrorThrown(error): + failureMessage.actualValue = "an unexpected error thrown: <\(error)>" + return false + case let .RaisedException(exception): + failureMessage.actualValue = "an unexpected exception thrown: <\(exception)>" + return false + case .BlockedRunLoop: + failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)." + return false + case .Incomplete: + internalError("Reached .Incomplete state for toEventually(...).") + } + } + + func doesNotMatch(actualExpression: Expression, failureMessage: FailureMessage) -> Bool { + let uncachedExpression = actualExpression.withoutCaching() + let result = pollBlock( + pollInterval: pollInterval, + timeoutInterval: timeoutInterval, + file: actualExpression.location.file, + line: actualExpression.location.line, + fnName: "expect(...).toEventuallyNot(...)") { + try self.fullMatcher.doesNotMatch(uncachedExpression, failureMessage: failureMessage) + } + switch (result) { + case let .Completed(isSuccessful): return isSuccessful + case .TimedOut: return false + case let .ErrorThrown(error): + failureMessage.actualValue = "an unexpected error thrown: <\(error)>" + return false + case let .RaisedException(exception): + failureMessage.actualValue = "an unexpected exception thrown: <\(exception)>" + return false + case .BlockedRunLoop: + failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)." + return false + case .Incomplete: + internalError("Reached .Incomplete state for toEventuallyNot(...).") + } + } +} + +private let toEventuallyRequiresClosureError = FailureMessage(stringValue: "expect(...).toEventually(...) requires an explicit closure (eg - expect { ... }.toEventually(...) )\nSwift 1.2 @autoclosure behavior has changed in an incompatible way for Nimble to function") + + +extension Expectation { + /// Tests the actual value using a matcher to match by checking continuously + /// at each pollInterval until the timeout is reached. + /// + /// @discussion + /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function + /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. + public func toEventually(matcher: U, timeout: NSTimeInterval = AsyncDefaults.Timeout, pollInterval: NSTimeInterval = AsyncDefaults.PollInterval, description: String? = nil) { + if expression.isClosure { + let (pass, msg) = expressionMatches( + expression, + matcher: AsyncMatcherWrapper( + fullMatcher: matcher, + timeoutInterval: timeout, + pollInterval: pollInterval), + to: "to eventually", + description: description + ) + verify(pass, msg) + } else { + verify(false, toEventuallyRequiresClosureError) + } + } + + /// Tests the actual value using a matcher to not match by checking + /// continuously at each pollInterval until the timeout is reached. + /// + /// @discussion + /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function + /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. + public func toEventuallyNot(matcher: U, timeout: NSTimeInterval = AsyncDefaults.Timeout, pollInterval: NSTimeInterval = AsyncDefaults.PollInterval, description: String? = nil) { + if expression.isClosure { + let (pass, msg) = expressionDoesNotMatch( + expression, + matcher: AsyncMatcherWrapper( + fullMatcher: matcher, + timeoutInterval: timeout, + pollInterval: pollInterval), + toNot: "to eventually not", + description: description + ) + verify(pass, msg) + } else { + verify(false, toEventuallyRequiresClosureError) + } + } + + /// Tests the actual value using a matcher to not match by checking + /// continuously at each pollInterval until the timeout is reached. + /// + /// Alias of toEventuallyNot() + /// + /// @discussion + /// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function + /// is executing. Any attempts to touch the run loop may cause non-deterministic behavior. + public func toNotEventually(matcher: U, timeout: NSTimeInterval = AsyncDefaults.Timeout, pollInterval: NSTimeInterval = AsyncDefaults.PollInterval, description: String? = nil) { + return toEventuallyNot(matcher, timeout: timeout, pollInterval: pollInterval, description: description) + } +} + +#endif diff --git a/Pods/Nimble/Sources/Nimble/Wrappers/MatcherFunc.swift b/Pods/Nimble/Sources/Nimble/Wrappers/MatcherFunc.swift new file mode 100644 index 0000000..ff9c2ee --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Wrappers/MatcherFunc.swift @@ -0,0 +1,95 @@ +/// A convenience API to build matchers that allow full control over +/// to() and toNot() match cases. +/// +/// The final bool argument in the closure is if the match is for negation. +/// +/// You may use this when implementing your own custom matchers. +/// +/// Use the Matcher protocol instead of this type to accept custom matchers as +/// input parameters. +/// @see allPass for an example that uses accepts other matchers as input. +public struct FullMatcherFunc: Matcher { + public let matcher: (Expression, FailureMessage, Bool) throws -> Bool + + public init(_ matcher: (Expression, FailureMessage, Bool) throws -> Bool) { + self.matcher = matcher + } + + public func matches(actualExpression: Expression, failureMessage: FailureMessage) throws -> Bool { + return try matcher(actualExpression, failureMessage, false) + } + + public func doesNotMatch(actualExpression: Expression, failureMessage: FailureMessage) throws -> Bool { + return try matcher(actualExpression, failureMessage, true) + } +} + +/// A convenience API to build matchers that don't need special negation +/// behavior. The toNot() behavior is the negation of to(). +/// +/// @see NonNilMatcherFunc if you prefer to have this matcher fail when nil +/// values are recieved in an expectation. +/// +/// You may use this when implementing your own custom matchers. +/// +/// Use the Matcher protocol instead of this type to accept custom matchers as +/// input parameters. +/// @see allPass for an example that uses accepts other matchers as input. +public struct MatcherFunc: Matcher { + public let matcher: (Expression, FailureMessage) throws -> Bool + + public init(_ matcher: (Expression, FailureMessage) throws -> Bool) { + self.matcher = matcher + } + + public func matches(actualExpression: Expression, failureMessage: FailureMessage) throws -> Bool { + return try matcher(actualExpression, failureMessage) + } + + public func doesNotMatch(actualExpression: Expression, failureMessage: FailureMessage) throws -> Bool { + return try !matcher(actualExpression, failureMessage) + } +} + +/// A convenience API to build matchers that don't need special negation +/// behavior. The toNot() behavior is the negation of to(). +/// +/// Unlike MatcherFunc, this will always fail if an expectation contains nil. +/// This applies regardless of using to() or toNot(). +/// +/// You may use this when implementing your own custom matchers. +/// +/// Use the Matcher protocol instead of this type to accept custom matchers as +/// input parameters. +/// @see allPass for an example that uses accepts other matchers as input. +public struct NonNilMatcherFunc: Matcher { + public let matcher: (Expression, FailureMessage) throws -> Bool + + public init(_ matcher: (Expression, FailureMessage) throws -> Bool) { + self.matcher = matcher + } + + public func matches(actualExpression: Expression, failureMessage: FailureMessage) throws -> Bool { + let pass = try matcher(actualExpression, failureMessage) + if try attachNilErrorIfNeeded(actualExpression, failureMessage: failureMessage) { + return false + } + return pass + } + + public func doesNotMatch(actualExpression: Expression, failureMessage: FailureMessage) throws -> Bool { + let pass = try !matcher(actualExpression, failureMessage) + if try attachNilErrorIfNeeded(actualExpression, failureMessage: failureMessage) { + return false + } + return pass + } + + internal func attachNilErrorIfNeeded(actualExpression: Expression, failureMessage: FailureMessage) throws -> Bool { + if try actualExpression.evaluate() == nil { + failureMessage.postfixActual = " (use beNil() to match nils)" + return true + } + return false + } +} diff --git a/Pods/Nimble/Sources/Nimble/Wrappers/ObjCMatcher.swift b/Pods/Nimble/Sources/Nimble/Wrappers/ObjCMatcher.swift new file mode 100644 index 0000000..9f31d42 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/Wrappers/ObjCMatcher.swift @@ -0,0 +1,81 @@ +import Foundation + +#if _runtime(_ObjC) + +public typealias MatcherBlock = (actualExpression: Expression, failureMessage: FailureMessage) -> Bool +public typealias FullMatcherBlock = (actualExpression: Expression, failureMessage: FailureMessage, shouldNotMatch: Bool) -> Bool + +public class NMBObjCMatcher : NSObject, NMBMatcher { + let _match: MatcherBlock + let _doesNotMatch: MatcherBlock + let canMatchNil: Bool + + public init(canMatchNil: Bool, matcher: MatcherBlock, notMatcher: MatcherBlock) { + self.canMatchNil = canMatchNil + self._match = matcher + self._doesNotMatch = notMatcher + } + + public convenience init(matcher: MatcherBlock) { + self.init(canMatchNil: true, matcher: matcher) + } + + public convenience init(canMatchNil: Bool, matcher: MatcherBlock) { + self.init(canMatchNil: canMatchNil, matcher: matcher, notMatcher: ({ actualExpression, failureMessage in + return !matcher(actualExpression: actualExpression, failureMessage: failureMessage) + })) + } + + public convenience init(matcher: FullMatcherBlock) { + self.init(canMatchNil: true, matcher: matcher) + } + + public convenience init(canMatchNil: Bool, matcher: FullMatcherBlock) { + self.init(canMatchNil: canMatchNil, matcher: ({ actualExpression, failureMessage in + return matcher(actualExpression: actualExpression, failureMessage: failureMessage, shouldNotMatch: false) + }), notMatcher: ({ actualExpression, failureMessage in + return matcher(actualExpression: actualExpression, failureMessage: failureMessage, shouldNotMatch: true) + })) + } + + private func canMatch(actualExpression: Expression, failureMessage: FailureMessage) -> Bool { + do { + if !canMatchNil { + if try actualExpression.evaluate() == nil { + failureMessage.postfixActual = " (use beNil() to match nils)" + return false + } + } + } catch let error { + failureMessage.actualValue = "an unexpected error thrown: \(error)" + return false + } + return true + } + + public func matches(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { + let expr = Expression(expression: actualBlock, location: location) + let result = _match( + actualExpression: expr, + failureMessage: failureMessage) + if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) { + return result + } else { + return false + } + } + + public func doesNotMatch(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { + let expr = Expression(expression: actualBlock, location: location) + let result = _doesNotMatch( + actualExpression: expr, + failureMessage: failureMessage) + if self.canMatch(Expression(expression: actualBlock, location: location), failureMessage: failureMessage) { + return result + } else { + return false + } + } +} + +#endif diff --git a/Pods/Nimble/Sources/Nimble/objc/CurrentTestCaseTracker.m b/Pods/Nimble/Sources/Nimble/objc/CurrentTestCaseTracker.m new file mode 100644 index 0000000..0d3b4db --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/objc/CurrentTestCaseTracker.m @@ -0,0 +1,18 @@ +#import +#import + +SWIFT_CLASS("_TtC6Nimble22CurrentTestCaseTracker") +@interface CurrentTestCaseTracker : NSObject ++ (CurrentTestCaseTracker *)sharedInstance; +@end + +@interface CurrentTestCaseTracker (Register) @end + +@implementation CurrentTestCaseTracker (Register) + ++ (void)load { + CurrentTestCaseTracker *tracker = [CurrentTestCaseTracker sharedInstance]; + [[XCTestObservationCenter sharedTestObservationCenter] addTestObserver:tracker]; +} + +@end diff --git a/Pods/Nimble/Sources/Nimble/objc/DSL.h b/Pods/Nimble/Sources/Nimble/objc/DSL.h new file mode 100644 index 0000000..a499059 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/objc/DSL.h @@ -0,0 +1,145 @@ +#import + +@class NMBExpectation; +@class NMBObjCBeCloseToMatcher; +@class NMBObjCRaiseExceptionMatcher; +@protocol NMBMatcher; + + +#define NIMBLE_EXPORT FOUNDATION_EXPORT + +#ifdef NIMBLE_DISABLE_SHORT_SYNTAX +#define NIMBLE_SHORT(PROTO, ORIGINAL) +#else +#define NIMBLE_SHORT(PROTO, ORIGINAL) FOUNDATION_STATIC_INLINE PROTO { return (ORIGINAL); } +#endif + +NIMBLE_EXPORT NMBExpectation *NMB_expect(id(^actualBlock)(), NSString *file, NSUInteger line); +NIMBLE_EXPORT NMBExpectation *NMB_expectAction(void(^actualBlock)(), NSString *file, NSUInteger line); + +NIMBLE_EXPORT id NMB_equal(id expectedValue); +NIMBLE_SHORT(id equal(id expectedValue), + NMB_equal(expectedValue)); + +NIMBLE_EXPORT id NMB_haveCount(id expectedValue); +NIMBLE_SHORT(id haveCount(id expectedValue), + NMB_haveCount(expectedValue)); + +NIMBLE_EXPORT NMBObjCBeCloseToMatcher *NMB_beCloseTo(NSNumber *expectedValue); +NIMBLE_SHORT(NMBObjCBeCloseToMatcher *beCloseTo(id expectedValue), + NMB_beCloseTo(expectedValue)); + +NIMBLE_EXPORT id NMB_beAnInstanceOf(Class expectedClass); +NIMBLE_SHORT(id beAnInstanceOf(Class expectedClass), + NMB_beAnInstanceOf(expectedClass)); + +NIMBLE_EXPORT id NMB_beAKindOf(Class expectedClass); +NIMBLE_SHORT(id beAKindOf(Class expectedClass), + NMB_beAKindOf(expectedClass)); + +NIMBLE_EXPORT id NMB_beginWith(id itemElementOrSubstring); +NIMBLE_SHORT(id beginWith(id itemElementOrSubstring), + NMB_beginWith(itemElementOrSubstring)); + +NIMBLE_EXPORT id NMB_beGreaterThan(NSNumber *expectedValue); +NIMBLE_SHORT(id beGreaterThan(NSNumber *expectedValue), + NMB_beGreaterThan(expectedValue)); + +NIMBLE_EXPORT id NMB_beGreaterThanOrEqualTo(NSNumber *expectedValue); +NIMBLE_SHORT(id beGreaterThanOrEqualTo(NSNumber *expectedValue), + NMB_beGreaterThanOrEqualTo(expectedValue)); + +NIMBLE_EXPORT id NMB_beIdenticalTo(id expectedInstance); +NIMBLE_SHORT(id beIdenticalTo(id expectedInstance), + NMB_beIdenticalTo(expectedInstance)); + +NIMBLE_EXPORT id NMB_be(id expectedInstance); +NIMBLE_SHORT(id be(id expectedInstance), + NMB_be(expectedInstance)); + +NIMBLE_EXPORT id NMB_beLessThan(NSNumber *expectedValue); +NIMBLE_SHORT(id beLessThan(NSNumber *expectedValue), + NMB_beLessThan(expectedValue)); + +NIMBLE_EXPORT id NMB_beLessThanOrEqualTo(NSNumber *expectedValue); +NIMBLE_SHORT(id beLessThanOrEqualTo(NSNumber *expectedValue), + NMB_beLessThanOrEqualTo(expectedValue)); + +NIMBLE_EXPORT id NMB_beTruthy(void); +NIMBLE_SHORT(id beTruthy(void), + NMB_beTruthy()); + +NIMBLE_EXPORT id NMB_beFalsy(void); +NIMBLE_SHORT(id beFalsy(void), + NMB_beFalsy()); + +NIMBLE_EXPORT id NMB_beTrue(void); +NIMBLE_SHORT(id beTrue(void), + NMB_beTrue()); + +NIMBLE_EXPORT id NMB_beFalse(void); +NIMBLE_SHORT(id beFalse(void), + NMB_beFalse()); + +NIMBLE_EXPORT id NMB_beNil(void); +NIMBLE_SHORT(id beNil(void), + NMB_beNil()); + +NIMBLE_EXPORT id NMB_beEmpty(void); +NIMBLE_SHORT(id beEmpty(void), + NMB_beEmpty()); + +NIMBLE_EXPORT id NMB_containWithNilTermination(id itemOrSubstring, ...) NS_REQUIRES_NIL_TERMINATION; +#define NMB_contain(...) NMB_containWithNilTermination(__VA_ARGS__, nil) +#ifndef NIMBLE_DISABLE_SHORT_SYNTAX +#define contain(...) NMB_contain(__VA_ARGS__) +#endif + +NIMBLE_EXPORT id NMB_endWith(id itemElementOrSubstring); +NIMBLE_SHORT(id endWith(id itemElementOrSubstring), + NMB_endWith(itemElementOrSubstring)); + +NIMBLE_EXPORT NMBObjCRaiseExceptionMatcher *NMB_raiseException(void); +NIMBLE_SHORT(NMBObjCRaiseExceptionMatcher *raiseException(void), + NMB_raiseException()); + +NIMBLE_EXPORT id NMB_match(id expectedValue); +NIMBLE_SHORT(id match(id expectedValue), + NMB_match(expectedValue)); + +NIMBLE_EXPORT id NMB_allPass(id matcher); +NIMBLE_SHORT(id allPass(id matcher), + NMB_allPass(matcher)); + +NIMBLE_EXPORT id NMB_satisfyAnyOfWithMatchers(id matchers); +#define NMB_satisfyAnyOf(...) NMB_satisfyAnyOfWithMatchers(@[__VA_ARGS__]) +#ifndef NIMBLE_DISABLE_SHORT_SYNTAX +#define satisfyAnyOf(...) NMB_satisfyAnyOf(__VA_ARGS__) +#endif + +// In order to preserve breakpoint behavior despite using macros to fill in __FILE__ and __LINE__, +// define a builder that populates __FILE__ and __LINE__, and returns a block that takes timeout +// and action arguments. See https://github.com/Quick/Quick/pull/185 for details. +typedef void (^NMBWaitUntilTimeoutBlock)(NSTimeInterval timeout, void (^action)(void (^)(void))); +typedef void (^NMBWaitUntilBlock)(void (^action)(void (^)(void))); + +NIMBLE_EXPORT void NMB_failWithMessage(NSString *msg, NSString *file, NSUInteger line); + +NIMBLE_EXPORT NMBWaitUntilTimeoutBlock NMB_waitUntilTimeoutBuilder(NSString *file, NSUInteger line); +NIMBLE_EXPORT NMBWaitUntilBlock NMB_waitUntilBuilder(NSString *file, NSUInteger line); + +NIMBLE_EXPORT void NMB_failWithMessage(NSString *msg, NSString *file, NSUInteger line); + +#define NMB_waitUntilTimeout NMB_waitUntilTimeoutBuilder(@(__FILE__), __LINE__) +#define NMB_waitUntil NMB_waitUntilBuilder(@(__FILE__), __LINE__) + +#ifndef NIMBLE_DISABLE_SHORT_SYNTAX +#define expect(...) NMB_expect(^id{ return (__VA_ARGS__); }, @(__FILE__), __LINE__) +#define expectAction(BLOCK) NMB_expectAction((BLOCK), @(__FILE__), __LINE__) +#define failWithMessage(msg) NMB_failWithMessage(msg, @(__FILE__), __LINE__) +#define fail() failWithMessage(@"fail() always fails") + + +#define waitUntilTimeout NMB_waitUntilTimeout +#define waitUntil NMB_waitUntil +#endif diff --git a/Pods/Nimble/Sources/Nimble/objc/DSL.m b/Pods/Nimble/Sources/Nimble/objc/DSL.m new file mode 100644 index 0000000..2170238 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/objc/DSL.m @@ -0,0 +1,150 @@ +#import +#import + +SWIFT_CLASS("_TtC6Nimble7NMBWait") +@interface NMBWait : NSObject + ++ (void)untilTimeout:(NSTimeInterval)timeout file:(NSString *)file line:(NSUInteger)line action:(void(^)())action; ++ (void)untilFile:(NSString *)file line:(NSUInteger)line action:(void(^)())action; + +@end + +NIMBLE_EXPORT NMBExpectation *NMB_expect(id(^actualBlock)(), NSString *file, NSUInteger line) { + return [[NMBExpectation alloc] initWithActualBlock:actualBlock + negative:NO + file:file + line:line]; +} + +NIMBLE_EXPORT NMBExpectation *NMB_expectAction(void(^actualBlock)(), NSString *file, NSUInteger line) { + return NMB_expect(^id{ + actualBlock(); + return nil; + }, file, line); +} + +NIMBLE_EXPORT void NMB_failWithMessage(NSString *msg, NSString *file, NSUInteger line) { + return [NMBExpectation failWithMessage:msg file:file line:line]; +} + +NIMBLE_EXPORT id NMB_beAnInstanceOf(Class expectedClass) { + return [NMBObjCMatcher beAnInstanceOfMatcher:expectedClass]; +} + +NIMBLE_EXPORT id NMB_beAKindOf(Class expectedClass) { + return [NMBObjCMatcher beAKindOfMatcher:expectedClass]; +} + +NIMBLE_EXPORT NMBObjCBeCloseToMatcher *NMB_beCloseTo(NSNumber *expectedValue) { + return [NMBObjCMatcher beCloseToMatcher:expectedValue within:0.001]; +} + +NIMBLE_EXPORT id NMB_beginWith(id itemElementOrSubstring) { + return [NMBObjCMatcher beginWithMatcher:itemElementOrSubstring]; +} + +NIMBLE_EXPORT id NMB_beGreaterThan(NSNumber *expectedValue) { + return [NMBObjCMatcher beGreaterThanMatcher:expectedValue]; +} + +NIMBLE_EXPORT id NMB_beGreaterThanOrEqualTo(NSNumber *expectedValue) { + return [NMBObjCMatcher beGreaterThanOrEqualToMatcher:expectedValue]; +} + +NIMBLE_EXPORT id NMB_beIdenticalTo(id expectedInstance) { + return [NMBObjCMatcher beIdenticalToMatcher:expectedInstance]; +} + +NIMBLE_EXPORT id NMB_be(id expectedInstance) { + return [NMBObjCMatcher beIdenticalToMatcher:expectedInstance]; +} + +NIMBLE_EXPORT id NMB_beLessThan(NSNumber *expectedValue) { + return [NMBObjCMatcher beLessThanMatcher:expectedValue]; +} + +NIMBLE_EXPORT id NMB_beLessThanOrEqualTo(NSNumber *expectedValue) { + return [NMBObjCMatcher beLessThanOrEqualToMatcher:expectedValue]; +} + +NIMBLE_EXPORT id NMB_beTruthy() { + return [NMBObjCMatcher beTruthyMatcher]; +} + +NIMBLE_EXPORT id NMB_beFalsy() { + return [NMBObjCMatcher beFalsyMatcher]; +} + +NIMBLE_EXPORT id NMB_beTrue() { + return [NMBObjCMatcher beTrueMatcher]; +} + +NIMBLE_EXPORT id NMB_beFalse() { + return [NMBObjCMatcher beFalseMatcher]; +} + +NIMBLE_EXPORT id NMB_beNil() { + return [NMBObjCMatcher beNilMatcher]; +} + +NIMBLE_EXPORT id NMB_beEmpty() { + return [NMBObjCMatcher beEmptyMatcher]; +} + +NIMBLE_EXPORT id NMB_containWithNilTermination(id itemOrSubstring, ...) { + NSMutableArray *itemOrSubstringArray = [NSMutableArray array]; + + if (itemOrSubstring) { + [itemOrSubstringArray addObject:itemOrSubstring]; + + va_list args; + va_start(args, itemOrSubstring); + id next; + while ((next = va_arg(args, id))) { + [itemOrSubstringArray addObject:next]; + } + va_end(args); + } + + return [NMBObjCMatcher containMatcher:itemOrSubstringArray]; +} + +NIMBLE_EXPORT id NMB_endWith(id itemElementOrSubstring) { + return [NMBObjCMatcher endWithMatcher:itemElementOrSubstring]; +} + +NIMBLE_EXPORT id NMB_equal(id expectedValue) { + return [NMBObjCMatcher equalMatcher:expectedValue]; +} + +NIMBLE_EXPORT id NMB_haveCount(id expectedValue) { + return [NMBObjCMatcher haveCountMatcher:expectedValue]; +} + +NIMBLE_EXPORT id NMB_match(id expectedValue) { + return [NMBObjCMatcher matchMatcher:expectedValue]; +} + +NIMBLE_EXPORT id NMB_allPass(id expectedValue) { + return [NMBObjCMatcher allPassMatcher:expectedValue]; +} + +NIMBLE_EXPORT id NMB_satisfyAnyOfWithMatchers(id matchers) { + return [NMBObjCMatcher satisfyAnyOfMatcher:matchers]; +} + +NIMBLE_EXPORT NMBObjCRaiseExceptionMatcher *NMB_raiseException() { + return [NMBObjCMatcher raiseExceptionMatcher]; +} + +NIMBLE_EXPORT NMBWaitUntilTimeoutBlock NMB_waitUntilTimeoutBuilder(NSString *file, NSUInteger line) { + return ^(NSTimeInterval timeout, void (^action)(void (^)(void))) { + [NMBWait untilTimeout:timeout file:file line:line action:action]; + }; +} + +NIMBLE_EXPORT NMBWaitUntilBlock NMB_waitUntilBuilder(NSString *file, NSUInteger line) { + return ^(void (^action)(void (^)(void))) { + [NMBWait untilFile:file line:line action:action]; + }; +} diff --git a/Pods/Nimble/Sources/Nimble/objc/NMBExceptionCapture.h b/Pods/Nimble/Sources/Nimble/objc/NMBExceptionCapture.h new file mode 100644 index 0000000..7e5fb07 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/objc/NMBExceptionCapture.h @@ -0,0 +1,11 @@ +#import +#import + +@interface NMBExceptionCapture : NSObject + +- (id)initWithHandler:(void(^)(NSException *))handler finally:(void(^)())finally; +- (void)tryBlock:(void(^)())unsafeBlock; + +@end + +typedef void(^NMBSourceCallbackBlock)(BOOL successful); diff --git a/Pods/Nimble/Sources/Nimble/objc/NMBExceptionCapture.m b/Pods/Nimble/Sources/Nimble/objc/NMBExceptionCapture.m new file mode 100644 index 0000000..48f5739 --- /dev/null +++ b/Pods/Nimble/Sources/Nimble/objc/NMBExceptionCapture.m @@ -0,0 +1,35 @@ +#import "NMBExceptionCapture.h" + +@interface NMBExceptionCapture () +@property (nonatomic, copy) void(^handler)(NSException *exception); +@property (nonatomic, copy) void(^finally)(); +@end + +@implementation NMBExceptionCapture + +- (id)initWithHandler:(void(^)(NSException *))handler finally:(void(^)())finally { + self = [super init]; + if (self) { + self.handler = handler; + self.finally = finally; + } + return self; +} + +- (void)tryBlock:(void(^)())unsafeBlock { + @try { + unsafeBlock(); + } + @catch (NSException *exception) { + if (self.handler) { + self.handler(exception); + } + } + @finally { + if (self.finally) { + self.finally(); + } + } +} + +@end \ No newline at end of file diff --git a/Pods/Nocilla/LICENSE b/Pods/Nocilla/LICENSE new file mode 100644 index 0000000..c996ca1 --- /dev/null +++ b/Pods/Nocilla/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2012 Luis Solano Bonet +MIT License + +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. \ No newline at end of file diff --git a/Pods/Nocilla/Nocilla/Categories/NSData+Nocilla.h b/Pods/Nocilla/Nocilla/Categories/NSData+Nocilla.h new file mode 100644 index 0000000..92ebbc7 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Categories/NSData+Nocilla.h @@ -0,0 +1,6 @@ +#import +#import "LSHTTPBody.h" + +@interface NSData (Nocilla) + +@end diff --git a/Pods/Nocilla/Nocilla/Categories/NSData+Nocilla.m b/Pods/Nocilla/Nocilla/Categories/NSData+Nocilla.m new file mode 100644 index 0000000..0572aeb --- /dev/null +++ b/Pods/Nocilla/Nocilla/Categories/NSData+Nocilla.m @@ -0,0 +1,9 @@ +#import "NSData+Nocilla.h" + +@implementation NSData (Nocilla) + +- (NSData *)data { + return self; +} + +@end diff --git a/Pods/Nocilla/Nocilla/Categories/NSString+Nocilla.h b/Pods/Nocilla/Nocilla/Categories/NSString+Nocilla.h new file mode 100644 index 0000000..cc0df6d --- /dev/null +++ b/Pods/Nocilla/Nocilla/Categories/NSString+Nocilla.h @@ -0,0 +1,8 @@ +#import +#import "LSHTTPBody.h" + +@interface NSString (Nocilla) + +- (NSRegularExpression *)regex; + +@end diff --git a/Pods/Nocilla/Nocilla/Categories/NSString+Nocilla.m b/Pods/Nocilla/Nocilla/Categories/NSString+Nocilla.m new file mode 100644 index 0000000..be28f78 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Categories/NSString+Nocilla.m @@ -0,0 +1,18 @@ +#import "NSString+Nocilla.h" + +@implementation NSString (Nocilla) + +- (NSRegularExpression *)regex { + NSError *error = nil; + NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:self options:0 error:&error]; + if (error) { + [NSException raise:NSInvalidArgumentException format:@"Invalid regex pattern: %@\nError: %@", self, error]; + } + return regex; +} + +- (NSData *)data { + return [self dataUsingEncoding:NSUTF8StringEncoding]; +} + +@end diff --git a/Pods/Nocilla/Nocilla/DSL/LSHTTPRequestDSLRepresentation.h b/Pods/Nocilla/Nocilla/DSL/LSHTTPRequestDSLRepresentation.h new file mode 100644 index 0000000..6a5fcb1 --- /dev/null +++ b/Pods/Nocilla/Nocilla/DSL/LSHTTPRequestDSLRepresentation.h @@ -0,0 +1,6 @@ +#import +#import "LSHTTPRequest.h" + +@interface LSHTTPRequestDSLRepresentation : NSObject +- (id)initWithRequest:(id)request; +@end diff --git a/Pods/Nocilla/Nocilla/DSL/LSHTTPRequestDSLRepresentation.m b/Pods/Nocilla/Nocilla/DSL/LSHTTPRequestDSLRepresentation.m new file mode 100644 index 0000000..bcfbb96 --- /dev/null +++ b/Pods/Nocilla/Nocilla/DSL/LSHTTPRequestDSLRepresentation.m @@ -0,0 +1,39 @@ +#import "LSHTTPRequestDSLRepresentation.h" + +@interface LSHTTPRequestDSLRepresentation () +@property (nonatomic, strong) id request; +@end + +@implementation LSHTTPRequestDSLRepresentation +- (id)initWithRequest:(id)request { + self = [super init]; + if (self) { + _request = request; + } + return self; +} + +- (NSString *)description { + NSMutableString *result = [NSMutableString stringWithFormat:@"stubRequest(@\"%@\", @\"%@\")", self.request.method, [self.request.url absoluteString]]; + if (self.request.headers.count) { + [result appendString:@".\nwithHeaders(@{ "]; + NSMutableArray *headerElements = [NSMutableArray arrayWithCapacity:self.request.headers.count]; + + NSArray *descriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"" ascending:YES]]; + NSArray * sortedHeaders = [[self.request.headers allKeys] sortedArrayUsingDescriptors:descriptors]; + + for (NSString * header in sortedHeaders) { + NSString *value = [self.request.headers objectForKey:header]; + [headerElements addObject:[NSString stringWithFormat:@"@\"%@\": @\"%@\"", header, value]]; + } + [result appendString:[headerElements componentsJoinedByString:@", "]]; + [result appendString:@" })"]; + } + if (self.request.body.length) { + NSString *escapedBody = [[NSString alloc] initWithData:self.request.body encoding:NSUTF8StringEncoding]; + escapedBody = [escapedBody stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""]; + [result appendFormat:@".\nwithBody(@\"%@\")", escapedBody]; + } + return [NSString stringWithFormat:@"%@;", result]; +} +@end diff --git a/Pods/Nocilla/Nocilla/DSL/LSStubRequestDSL.h b/Pods/Nocilla/Nocilla/DSL/LSStubRequestDSL.h new file mode 100644 index 0000000..d7df743 --- /dev/null +++ b/Pods/Nocilla/Nocilla/DSL/LSStubRequestDSL.h @@ -0,0 +1,39 @@ +#import +#import "NSString+Matcheable.h" +#import "NSRegularExpression+Matcheable.h" +#import "NSData+Matcheable.h" + +@class LSStubRequestDSL; +@class LSStubResponseDSL; +@class LSStubRequest; + +@protocol LSHTTPBody; + +typedef LSStubRequestDSL *(^WithHeaderMethod)(NSString *, NSString *); +typedef LSStubRequestDSL *(^WithHeadersMethod)(NSDictionary *); +typedef LSStubRequestDSL *(^AndBodyMethod)(id); +typedef LSStubResponseDSL *(^AndReturnMethod)(NSInteger); +typedef LSStubResponseDSL *(^AndReturnRawResponseMethod)(NSData *rawResponseData); +typedef void (^AndFailWithErrorMethod)(NSError *error); + +@interface LSStubRequestDSL : NSObject +- (id)initWithRequest:(LSStubRequest *)request; + +@property (nonatomic, strong, readonly) WithHeaderMethod withHeader; +@property (nonatomic, strong, readonly) WithHeadersMethod withHeaders; +@property (nonatomic, strong, readonly) AndBodyMethod withBody; +@property (nonatomic, strong, readonly) AndReturnMethod andReturn; +@property (nonatomic, strong, readonly) AndReturnRawResponseMethod andReturnRawResponse; +@property (nonatomic, strong, readonly) AndFailWithErrorMethod andFailWithError; + +@end + +#ifdef __cplusplus +extern "C" { +#endif + +LSStubRequestDSL * stubRequest(NSString *method, id url); + +#ifdef __cplusplus +} +#endif diff --git a/Pods/Nocilla/Nocilla/DSL/LSStubRequestDSL.m b/Pods/Nocilla/Nocilla/DSL/LSStubRequestDSL.m new file mode 100644 index 0000000..831e0c0 --- /dev/null +++ b/Pods/Nocilla/Nocilla/DSL/LSStubRequestDSL.m @@ -0,0 +1,72 @@ +#import "LSStubRequestDSL.h" +#import "LSStubResponseDSL.h" +#import "LSStubRequest.h" +#import "LSNocilla.h" + +@interface LSStubRequestDSL () +@property (nonatomic, strong) LSStubRequest *request; +@end + +@implementation LSStubRequestDSL + +- (id)initWithRequest:(LSStubRequest *)request { + self = [super init]; + if (self) { + _request = request; + } + return self; +} +- (WithHeadersMethod)withHeaders { + return ^(NSDictionary *headers) { + for (NSString *header in headers) { + NSString *value = [headers objectForKey:header]; + [self.request setHeader:header value:value]; + } + return self; + }; +} + +- (WithHeaderMethod)withHeader { + return ^(NSString * header, NSString * value) { + [self.request setHeader:header value:value]; + return self; + }; +} + +- (AndBodyMethod)withBody { + return ^(id body) { + self.request.body = body.matcher; + return self; + }; +} + +- (AndReturnMethod)andReturn { + return ^(NSInteger statusCode) { + self.request.response = [[LSStubResponse alloc] initWithStatusCode:statusCode]; + LSStubResponseDSL *responseDSL = [[LSStubResponseDSL alloc] initWithResponse:self.request.response]; + return responseDSL; + }; +} + +- (AndReturnRawResponseMethod)andReturnRawResponse { + return ^(NSData *rawResponseData) { + self.request.response = [[LSStubResponse alloc] initWithRawResponse:rawResponseData]; + LSStubResponseDSL *responseDSL = [[LSStubResponseDSL alloc] initWithResponse:self.request.response]; + return responseDSL; + }; +} + +- (AndFailWithErrorMethod)andFailWithError { + return ^(NSError *error) { + self.request.response = [[LSStubResponse alloc] initWithError:error]; + }; +} + +@end + +LSStubRequestDSL * stubRequest(NSString *method, id url) { + LSStubRequest *request = [[LSStubRequest alloc] initWithMethod:method urlMatcher:url.matcher]; + LSStubRequestDSL *dsl = [[LSStubRequestDSL alloc] initWithRequest:request]; + [[LSNocilla sharedInstance] addStubbedRequest:request]; + return dsl; +} diff --git a/Pods/Nocilla/Nocilla/DSL/LSStubResponseDSL.h b/Pods/Nocilla/Nocilla/DSL/LSStubResponseDSL.h new file mode 100644 index 0000000..2ba6b66 --- /dev/null +++ b/Pods/Nocilla/Nocilla/DSL/LSStubResponseDSL.h @@ -0,0 +1,19 @@ +#import + +@class LSStubResponse; +@class LSStubResponseDSL; + +@protocol LSHTTPBody; + +typedef LSStubResponseDSL *(^ResponseWithBodyMethod)(id); +typedef LSStubResponseDSL *(^ResponseWithHeaderMethod)(NSString *, NSString *); +typedef LSStubResponseDSL *(^ResponseWithHeadersMethod)(NSDictionary *); + +@interface LSStubResponseDSL : NSObject +- (id)initWithResponse:(LSStubResponse *)response; + +@property (nonatomic, strong, readonly) ResponseWithHeaderMethod withHeader; +@property (nonatomic, strong, readonly) ResponseWithHeadersMethod withHeaders; +@property (nonatomic, strong, readonly) ResponseWithBodyMethod withBody; + +@end diff --git a/Pods/Nocilla/Nocilla/DSL/LSStubResponseDSL.m b/Pods/Nocilla/Nocilla/DSL/LSStubResponseDSL.m new file mode 100644 index 0000000..06e9786 --- /dev/null +++ b/Pods/Nocilla/Nocilla/DSL/LSStubResponseDSL.m @@ -0,0 +1,40 @@ +#import "LSStubResponseDSL.h" +#import "LSStubResponse.h" +#import "LSHTTPBody.h" + +@interface LSStubResponseDSL () +@property (nonatomic, strong) LSStubResponse *response; +@end + +@implementation LSStubResponseDSL +- (id)initWithResponse:(LSStubResponse *)response { + self = [super init]; + if (self) { + _response = response; + } + return self; +} +- (ResponseWithHeaderMethod)withHeader { + return ^(NSString * header, NSString * value) { + [self.response setHeader:header value:value]; + return self; + }; +} + +- (ResponseWithHeadersMethod)withHeaders; { + return ^(NSDictionary *headers) { + for (NSString *header in headers) { + NSString *value = [headers objectForKey:header]; + [self.response setHeader:header value:value]; + } + return self; + }; +} + +- (ResponseWithBodyMethod)withBody { + return ^(id body) { + self.response.body = [body data]; + return self; + }; +} +@end diff --git a/Pods/Nocilla/Nocilla/Diff/LSHTTPRequestDiff.h b/Pods/Nocilla/Nocilla/Diff/LSHTTPRequestDiff.h new file mode 100644 index 0000000..2f9b8ea --- /dev/null +++ b/Pods/Nocilla/Nocilla/Diff/LSHTTPRequestDiff.h @@ -0,0 +1,8 @@ +#import +#import "LSHTTPRequest.h" + +@interface LSHTTPRequestDiff : NSObject +@property (nonatomic, assign, readonly, getter = isEmpty) BOOL empty; + +- (id)initWithRequest:(id)oneRequest andRequest:(id)anotherRequest; +@end diff --git a/Pods/Nocilla/Nocilla/Diff/LSHTTPRequestDiff.m b/Pods/Nocilla/Nocilla/Diff/LSHTTPRequestDiff.m new file mode 100644 index 0000000..413121d --- /dev/null +++ b/Pods/Nocilla/Nocilla/Diff/LSHTTPRequestDiff.m @@ -0,0 +1,114 @@ +#import "LSHTTPRequestDiff.h" + +@interface LSHTTPRequestDiff () +@property (nonatomic, strong) idoneRequest; +@property (nonatomic, strong) idanotherRequest; + +- (BOOL)isMethodDifferent; +- (BOOL)isUrlDifferent; +- (BOOL)areHeadersDifferent; +- (BOOL)isBodyDifferent; + +- (void)appendMethodDiff:(NSMutableString *)diff; +- (void)appendUrlDiff:(NSMutableString *)diff; +- (void)appendHeadersDiff:(NSMutableString *)diff; +- (void)appendBodyDiff:(NSMutableString *)diff; +@end + +@implementation LSHTTPRequestDiff +- (id)initWithRequest:(id)oneRequest andRequest:(id)anotherRequest { + self = [super init]; + if (self) { + _oneRequest = oneRequest; + _anotherRequest = anotherRequest; + } + return self; +} + +- (BOOL)isEmpty { + if ([self isMethodDifferent] || + [self isUrlDifferent] || + [self areHeadersDifferent] || + [self isBodyDifferent]) { + return NO; + } + return YES; +} + +- (NSString *)description { + NSMutableString *diff = [@"" mutableCopy]; + if ([self isMethodDifferent]) { + [self appendMethodDiff:diff]; + } + if ([self isUrlDifferent]) { + [self appendUrlDiff:diff]; + } + if([self areHeadersDifferent]) { + [self appendHeadersDiff:diff]; + } + if([self isBodyDifferent]) { + [self appendBodyDiff:diff]; + } + return [NSString stringWithString:diff]; +} + +#pragma mark - Private Methods +- (BOOL)isMethodDifferent { + return ![self.oneRequest.method isEqualToString:self.anotherRequest.method]; +} + +- (BOOL)isUrlDifferent { + return ![self.oneRequest.url isEqual:self.anotherRequest.url]; +} + +- (BOOL)areHeadersDifferent { + return ![self.oneRequest.headers isEqual:self.anotherRequest.headers]; +} + +- (BOOL)isBodyDifferent { + return (((self.oneRequest.body) && (![self.oneRequest.body isEqual:self.anotherRequest.body])) || + ((self.anotherRequest.body) && (![self.anotherRequest.body isEqual:self.oneRequest.body]))); +} + +- (void)appendMethodDiff:(NSMutableString *)diff { + [diff appendFormat:@"- Method: %@\n+ Method: %@\n", self.oneRequest.method, self.anotherRequest.method]; +} + +- (void)appendUrlDiff:(NSMutableString *)diff { + [diff appendFormat:@"- URL: %@\n+ URL: %@\n", [self.oneRequest.url absoluteString], [self.anotherRequest.url absoluteString]]; +} + +- (void)appendHeadersDiff:(NSMutableString *)diff { + [diff appendString:@" Headers:\n"]; + NSSet *headersInOneButNotInTheOther = [self.oneRequest.headers keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) { + return ![self.anotherRequest.headers objectForKey:key] || ![obj isEqual:[self.anotherRequest.headers objectForKey:key]]; + }]; + NSSet *headersInTheOtherButNotInOne = [self.anotherRequest.headers keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) { + return ![self.oneRequest.headers objectForKey:key] || ![obj isEqual:[self.oneRequest.headers objectForKey:key]]; + }]; + + NSArray *descriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"" ascending:YES]]; + NSArray * sortedHeadersInOneButNotInTheOther = [headersInOneButNotInTheOther sortedArrayUsingDescriptors:descriptors]; + NSArray * sortedHeadersInTheOtherButNotInOne = [headersInTheOtherButNotInOne sortedArrayUsingDescriptors:descriptors]; + for (NSString *header in sortedHeadersInOneButNotInTheOther) { + NSString *value = [self.oneRequest.headers objectForKey:header]; + [diff appendFormat:@"-\t\"%@\": \"%@\"\n", header, value]; + + } + for (NSString *header in sortedHeadersInTheOtherButNotInOne) { + NSString *value = [self.anotherRequest.headers objectForKey:header]; + [diff appendFormat:@"+\t\"%@\": \"%@\"\n", header, value]; + } +} + +- (void)appendBodyDiff:(NSMutableString *)diff { + NSString *oneBody = [[NSString alloc] initWithData:self.oneRequest.body encoding:NSUTF8StringEncoding]; + if (oneBody.length) { + [diff appendFormat:@"- Body: \"%@\"\n", oneBody]; + } + NSString *anotherBody = [[NSString alloc] initWithData:self.anotherRequest.body encoding:NSUTF8StringEncoding]; + if (anotherBody.length) { + [diff appendFormat:@"+ Body: \"%@\"\n", anotherBody]; + } +} +@end diff --git a/Pods/Nocilla/Nocilla/Hooks/ASIHTTPRequest/ASIHTTPRequestStub.h b/Pods/Nocilla/Nocilla/Hooks/ASIHTTPRequest/ASIHTTPRequestStub.h new file mode 100644 index 0000000..f9ef36a --- /dev/null +++ b/Pods/Nocilla/Nocilla/Hooks/ASIHTTPRequest/ASIHTTPRequestStub.h @@ -0,0 +1,8 @@ +#import + +@interface ASIHTTPRequestStub : NSObject +- (int)stub_responseStatusCode; +- (NSData *)stub_responseData; +- (NSDictionary *)stub_responseHeaders; +- (void)stub_startRequest; +@end diff --git a/Pods/Nocilla/Nocilla/Hooks/ASIHTTPRequest/ASIHTTPRequestStub.m b/Pods/Nocilla/Nocilla/Hooks/ASIHTTPRequest/ASIHTTPRequestStub.m new file mode 100644 index 0000000..712b4c9 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Hooks/ASIHTTPRequest/ASIHTTPRequestStub.m @@ -0,0 +1,52 @@ +#import "ASIHTTPRequestStub.h" +#import "LSStubResponse.h" +#import "LSNocilla.h" +#import "LSASIHTTPRequestAdapter.h" +#import + +@interface ASIHTTPRequestStub () +@property (nonatomic, strong) LSStubResponse *stubResponse; +@end + +@interface ASIHTTPRequestStub (Private) +- (void)failWithError:(NSError *)error; +- (void)requestFinished; +- (void)markAsFinished; +@end + +static void const * ASIHTTPRequestStubResponseKey = &ASIHTTPRequestStubResponseKey; + +@implementation ASIHTTPRequestStub + +- (void)setStubResponse:(LSStubResponse *)stubResponse { + objc_setAssociatedObject(self, ASIHTTPRequestStubResponseKey, stubResponse, OBJC_ASSOCIATION_RETAIN); +} + +- (LSStubResponse *)stubResponse { + return objc_getAssociatedObject(self, ASIHTTPRequestStubResponseKey); +} + +- (int)stub_responseStatusCode { + return (int)self.stubResponse.statusCode; +} + +- (NSData *)stub_responseData { + return self.stubResponse.body; +} + +- (NSDictionary *)stub_responseHeaders { + return self.stubResponse.headers; +} + +- (void)stub_startRequest { + self.stubResponse = [[LSNocilla sharedInstance] responseForRequest:[[LSASIHTTPRequestAdapter alloc] initWithASIHTTPRequest:(id)self]]; + + if (self.stubResponse.shouldFail) { + [self failWithError:self.stubResponse.error]; + } else { + [self requestFinished]; + } + [self markAsFinished]; +} + +@end \ No newline at end of file diff --git a/Pods/Nocilla/Nocilla/Hooks/ASIHTTPRequest/LSASIHTTPRequestAdapter.h b/Pods/Nocilla/Nocilla/Hooks/ASIHTTPRequest/LSASIHTTPRequestAdapter.h new file mode 100644 index 0000000..6cf7b1c --- /dev/null +++ b/Pods/Nocilla/Nocilla/Hooks/ASIHTTPRequest/LSASIHTTPRequestAdapter.h @@ -0,0 +1,10 @@ +#import +#import "LSHTTPRequest.h" + +@class ASIHTTPRequest; + +@interface LSASIHTTPRequestAdapter : NSObject + +- (instancetype)initWithASIHTTPRequest:(ASIHTTPRequest *)request; + +@end diff --git a/Pods/Nocilla/Nocilla/Hooks/ASIHTTPRequest/LSASIHTTPRequestAdapter.m b/Pods/Nocilla/Nocilla/Hooks/ASIHTTPRequest/LSASIHTTPRequestAdapter.m new file mode 100644 index 0000000..91cf791 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Hooks/ASIHTTPRequest/LSASIHTTPRequestAdapter.m @@ -0,0 +1,42 @@ +#import "LSASIHTTPRequestAdapter.h" + +@interface ASIHTTPRequest + +@property (nonatomic, strong, readonly) NSURL *url; +@property (nonatomic, strong, readonly) NSString *requestMethod; +@property (nonatomic, strong, readonly) NSDictionary *requestHeaders; +@property (nonatomic, strong, readonly) NSData *postBody; + +@end + +@interface LSASIHTTPRequestAdapter () +@property (nonatomic, strong) ASIHTTPRequest *request; +@end + +@implementation LSASIHTTPRequestAdapter + +- (instancetype)initWithASIHTTPRequest:(ASIHTTPRequest *)request { + self = [super init]; + if (self) { + _request = request; + } + return self; +} + +- (NSURL *)url { + return self.request.url; +} + +- (NSString *)method { + return self.request.requestMethod; +} + +- (NSDictionary *)headers { + return self.request.requestHeaders; +} + +- (NSData *)body { + return self.request.postBody; +} + +@end diff --git a/Pods/Nocilla/Nocilla/Hooks/ASIHTTPRequest/LSASIHTTPRequestHook.h b/Pods/Nocilla/Nocilla/Hooks/ASIHTTPRequest/LSASIHTTPRequestHook.h new file mode 100644 index 0000000..2450072 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Hooks/ASIHTTPRequest/LSASIHTTPRequestHook.h @@ -0,0 +1,5 @@ +#import "LSHTTPClientHook.h" + +@interface LSASIHTTPRequestHook : LSHTTPClientHook + +@end diff --git a/Pods/Nocilla/Nocilla/Hooks/ASIHTTPRequest/LSASIHTTPRequestHook.m b/Pods/Nocilla/Nocilla/Hooks/ASIHTTPRequest/LSASIHTTPRequestHook.m new file mode 100644 index 0000000..1a32a47 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Hooks/ASIHTTPRequest/LSASIHTTPRequestHook.m @@ -0,0 +1,48 @@ +#import "LSASIHTTPRequestHook.h" +#import "ASIHTTPRequestStub.h" +#import + +@implementation LSASIHTTPRequestHook + +- (void)load { + if (!NSClassFromString(@"ASIHTTPRequest")) return; + [self swizzleASIHTTPRequest]; +} + +- (void)unload { + if (!NSClassFromString(@"ASIHTTPRequest")) return; + [self swizzleASIHTTPRequest]; +} + +#pragma mark - Internal Methods + +- (void)swizzleASIHTTPRequest { + [self swizzleASIHTTPSelector:NSSelectorFromString(@"responseStatusCode") withSelector:@selector(stub_responseStatusCode)]; + [self swizzleASIHTTPSelector:NSSelectorFromString(@"responseData") withSelector:@selector(stub_responseData)]; + [self swizzleASIHTTPSelector:NSSelectorFromString(@"responseHeaders") withSelector:@selector(stub_responseHeaders)]; + [self swizzleASIHTTPSelector:NSSelectorFromString(@"startRequest") withSelector:@selector(stub_startRequest)]; + [self addMethodToASIHTTPRequest:NSSelectorFromString(@"stubResponse")]; + [self addMethodToASIHTTPRequest:NSSelectorFromString(@"setStubResponse:")]; +} + +- (void)swizzleASIHTTPSelector:(SEL)original withSelector:(SEL)stub { + Class asiHttpRequest = NSClassFromString(@"ASIHTTPRequest"); + Method originalMethod = class_getInstanceMethod(asiHttpRequest, original); + Method stubMethod = class_getInstanceMethod([ASIHTTPRequestStub class], stub); + if (!originalMethod || !stubMethod) { + [self fail]; + } + method_exchangeImplementations(originalMethod, stubMethod); +} + +- (void)addMethodToASIHTTPRequest:(SEL)newMethod { + Method method = class_getInstanceMethod([ASIHTTPRequestStub class], newMethod); + const char *types = method_getTypeEncoding(method); + class_addMethod(NSClassFromString(@"ASIHTTPRequest"), newMethod, class_getMethodImplementation([ASIHTTPRequestStub class], newMethod), types); +} + +- (void)fail { + [NSException raise:NSInternalInconsistencyException format:@"Couldn't load ASIHTTPRequest hook."]; +} + +@end diff --git a/Pods/Nocilla/Nocilla/Hooks/LSHTTPClientHook.h b/Pods/Nocilla/Nocilla/Hooks/LSHTTPClientHook.h new file mode 100644 index 0000000..80ddc4c --- /dev/null +++ b/Pods/Nocilla/Nocilla/Hooks/LSHTTPClientHook.h @@ -0,0 +1,6 @@ +#import + +@interface LSHTTPClientHook : NSObject +- (void)load; +- (void)unload; +@end diff --git a/Pods/Nocilla/Nocilla/Hooks/LSHTTPClientHook.m b/Pods/Nocilla/Nocilla/Hooks/LSHTTPClientHook.m new file mode 100644 index 0000000..8256ca6 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Hooks/LSHTTPClientHook.m @@ -0,0 +1,13 @@ +#import "LSHTTPClientHook.h" + +@implementation LSHTTPClientHook +- (void)load { + [NSException raise:NSInternalInconsistencyException + format:@"Method '%@' not implemented. Subclass '%@' and override it", NSStringFromSelector(_cmd), NSStringFromClass([self class])]; +} + +- (void)unload { + [NSException raise:NSInternalInconsistencyException + format:@"Method '%@' not implemented. Subclass '%@' and override it", NSStringFromSelector(_cmd), NSStringFromClass([self class])]; +} +@end diff --git a/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/LSHTTPStubURLProtocol.h b/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/LSHTTPStubURLProtocol.h new file mode 100644 index 0000000..d5a9a1f --- /dev/null +++ b/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/LSHTTPStubURLProtocol.h @@ -0,0 +1,5 @@ +#import + +@interface LSHTTPStubURLProtocol : NSURLProtocol + +@end diff --git a/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/LSHTTPStubURLProtocol.m b/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/LSHTTPStubURLProtocol.m new file mode 100644 index 0000000..06e925d --- /dev/null +++ b/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/LSHTTPStubURLProtocol.m @@ -0,0 +1,67 @@ +#import "LSHTTPStubURLProtocol.h" +#import "LSNocilla.h" +#import "NSURLRequest+LSHTTPRequest.h" +#import "LSStubRequest.h" +#import "NSURLRequest+DSL.h" + +@implementation LSHTTPStubURLProtocol + ++ (BOOL)canInitWithRequest:(NSURLRequest *)request { + return [@[ @"http", @"https" ] containsObject:request.URL.scheme]; +} + ++ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { + return request; +} ++ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b { + return NO; +} + +- (void)startLoading { + NSURLRequest* request = [self request]; + id client = [self client]; + + LSStubResponse* stubbedResponse = [[LSNocilla sharedInstance] responseForRequest:request]; + + NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; + [cookieStorage setCookies:[NSHTTPCookie cookiesWithResponseHeaderFields:stubbedResponse.headers forURL:request.url] + forURL:request.URL mainDocumentURL:request.URL]; + + if (stubbedResponse.shouldFail) { + [client URLProtocol:self didFailWithError:stubbedResponse.error]; + } else { + NSHTTPURLResponse* urlResponse = [[NSHTTPURLResponse alloc] initWithURL:request.URL + statusCode:stubbedResponse.statusCode + HTTPVersion:nil + headerFields:stubbedResponse.headers]; + + if (stubbedResponse.statusCode < 300 || stubbedResponse.statusCode > 399 + || stubbedResponse.statusCode == 304 || stubbedResponse.statusCode == 305 ) { + NSData *body = stubbedResponse.body; + + [client URLProtocol:self didReceiveResponse:urlResponse + cacheStoragePolicy:NSURLCacheStorageNotAllowed]; + [client URLProtocol:self didLoadData:body]; + [client URLProtocolDidFinishLoading:self]; + } else { + + NSURL *newURL = [NSURL URLWithString:[stubbedResponse.headers objectForKey:@"Location"] relativeToURL:request.URL]; + NSMutableURLRequest *redirectRequest = [NSMutableURLRequest requestWithURL:newURL]; + + [redirectRequest setAllHTTPHeaderFields:[NSHTTPCookie requestHeaderFieldsWithCookies:[cookieStorage cookiesForURL:newURL]]]; + + [client URLProtocol:self + wasRedirectedToRequest:redirectRequest + redirectResponse:urlResponse]; + // According to: https://developer.apple.com/library/ios/samplecode/CustomHTTPProtocol/Listings/CustomHTTPProtocol_Core_Code_CustomHTTPProtocol_m.html + // needs to abort the original request + [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil]]; + + } + } +} + +- (void)stopLoading { +} + +@end diff --git a/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/LSNSURLHook.h b/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/LSNSURLHook.h new file mode 100644 index 0000000..abba2cb --- /dev/null +++ b/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/LSNSURLHook.h @@ -0,0 +1,5 @@ +#import "LSHTTPClientHook.h" + +@interface LSNSURLHook : LSHTTPClientHook + +@end diff --git a/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/LSNSURLHook.m b/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/LSNSURLHook.m new file mode 100644 index 0000000..77d7020 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/LSNSURLHook.m @@ -0,0 +1,14 @@ +#import "LSNSURLHook.h" +#import "LSHTTPStubURLProtocol.h" + +@implementation LSNSURLHook + +- (void)load { + [NSURLProtocol registerClass:[LSHTTPStubURLProtocol class]]; +} + +- (void)unload { + [NSURLProtocol unregisterClass:[LSHTTPStubURLProtocol class]]; +} + +@end diff --git a/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/NSURLRequest+DSL.h b/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/NSURLRequest+DSL.h new file mode 100644 index 0000000..e13dbbd --- /dev/null +++ b/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/NSURLRequest+DSL.h @@ -0,0 +1,5 @@ +#import + +@interface NSURLRequest (DSL) +- (NSString *)toNocillaDSL; +@end diff --git a/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/NSURLRequest+DSL.m b/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/NSURLRequest+DSL.m new file mode 100644 index 0000000..73e249b --- /dev/null +++ b/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/NSURLRequest+DSL.m @@ -0,0 +1,9 @@ +#import "NSURLRequest+DSL.h" +#import "LSHTTPRequestDSLRepresentation.h" +#import "NSURLRequest+LSHTTPRequest.h" + +@implementation NSURLRequest (DSL) +- (NSString *)toNocillaDSL { + return [[[LSHTTPRequestDSLRepresentation alloc] initWithRequest:self] description]; +} +@end diff --git a/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/NSURLRequest+LSHTTPRequest.h b/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/NSURLRequest+LSHTTPRequest.h new file mode 100644 index 0000000..0ac96b2 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/NSURLRequest+LSHTTPRequest.h @@ -0,0 +1,6 @@ +#import +#import "LSHTTPRequest.h" + +@interface NSURLRequest (LSHTTPRequest) + +@end diff --git a/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/NSURLRequest+LSHTTPRequest.m b/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/NSURLRequest+LSHTTPRequest.m new file mode 100644 index 0000000..a6c3007 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Hooks/NSURLRequest/NSURLRequest+LSHTTPRequest.m @@ -0,0 +1,47 @@ +#import "NSURLRequest+LSHTTPRequest.h" + +@implementation NSURLRequest (LSHTTPRequest) + +- (NSURL*)url { + return self.URL; +} + +- (NSString *)method { + return self.HTTPMethod; +} + +- (NSDictionary *)headers { + return self.allHTTPHeaderFields; +} + +- (NSData *)body { + if (self.HTTPBodyStream) { + NSInputStream *stream = self.HTTPBodyStream; + NSMutableData *data = [NSMutableData data]; + [stream open]; + size_t bufferSize = 4096; + uint8_t *buffer = malloc(bufferSize); + if (buffer == NULL) { + [NSException raise:@"NocillaMallocFailure" format:@"Could not allocate %zu bytes to read HTTPBodyStream", bufferSize]; + } + while ([stream hasBytesAvailable]) { + NSInteger bytesRead = [stream read:buffer maxLength:bufferSize]; + if (bytesRead > 0) { + NSData *readData = [NSData dataWithBytes:buffer length:bytesRead]; + [data appendData:readData]; + } else if (bytesRead < 0) { + [NSException raise:@"NocillaStreamReadError" format:@"An error occurred while reading HTTPBodyStream (%ld)", (long)bytesRead]; + } else if (bytesRead == 0) { + break; + } + } + free(buffer); + [stream close]; + + return data; + } + + return self.HTTPBody; +} + +@end diff --git a/Pods/Nocilla/Nocilla/Hooks/NSURLSession/LSNSURLSessionHook.h b/Pods/Nocilla/Nocilla/Hooks/NSURLSession/LSNSURLSessionHook.h new file mode 100644 index 0000000..aa6ec8c --- /dev/null +++ b/Pods/Nocilla/Nocilla/Hooks/NSURLSession/LSNSURLSessionHook.h @@ -0,0 +1,15 @@ +// +// LSNSURLSessionHook.h +// Nocilla +// +// Created by Luis Solano Bonet on 08/01/14. +// Copyright (c) 2014 Luis Solano Bonet. All rights reserved. +// + +#import + +#import "LSHTTPClientHook.h" + +@interface LSNSURLSessionHook : LSHTTPClientHook + +@end diff --git a/Pods/Nocilla/Nocilla/Hooks/NSURLSession/LSNSURLSessionHook.m b/Pods/Nocilla/Nocilla/Hooks/NSURLSession/LSNSURLSessionHook.m new file mode 100644 index 0000000..ab584f5 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Hooks/NSURLSession/LSNSURLSessionHook.m @@ -0,0 +1,40 @@ +// +// LSNSURLSessionHook.m +// Nocilla +// +// Created by Luis Solano Bonet on 08/01/14. +// Copyright (c) 2014 Luis Solano Bonet. All rights reserved. +// + +#import "LSNSURLSessionHook.h" +#import "LSHTTPStubURLProtocol.h" +#import + +@implementation LSNSURLSessionHook + +- (void)load { + Class cls = NSClassFromString(@"__NSCFURLSessionConfiguration") ?: NSClassFromString(@"NSURLSessionConfiguration"); + [self swizzleSelector:@selector(protocolClasses) fromClass:cls toClass:[self class]]; +} + +- (void)unload { + Class cls = NSClassFromString(@"__NSCFURLSessionConfiguration") ?: NSClassFromString(@"NSURLSessionConfiguration"); + [self swizzleSelector:@selector(protocolClasses) fromClass:cls toClass:[self class]]; +} + +- (void)swizzleSelector:(SEL)selector fromClass:(Class)original toClass:(Class)stub { + + Method originalMethod = class_getInstanceMethod(original, selector); + Method stubMethod = class_getInstanceMethod(stub, selector); + if (!originalMethod || !stubMethod) { + [NSException raise:NSInternalInconsistencyException format:@"Couldn't load NSURLSession hook."]; + } + method_exchangeImplementations(originalMethod, stubMethod); +} + +- (NSArray *)protocolClasses { + return @[[LSHTTPStubURLProtocol class]]; +} + + +@end diff --git a/Pods/Nocilla/Nocilla/LSNocilla.h b/Pods/Nocilla/Nocilla/LSNocilla.h new file mode 100644 index 0000000..aa85901 --- /dev/null +++ b/Pods/Nocilla/Nocilla/LSNocilla.h @@ -0,0 +1,25 @@ +#import +#import "Nocilla.h" + +@class LSStubRequest; +@class LSStubResponse; +@class LSHTTPClientHook; +@protocol LSHTTPRequest; + +extern NSString * const LSUnexpectedRequest; + +@interface LSNocilla : NSObject ++ (LSNocilla *)sharedInstance; + +@property (nonatomic, strong, readonly) NSArray *stubbedRequests; +@property (nonatomic, assign, readonly, getter = isStarted) BOOL started; + +- (void)start; +- (void)stop; +- (void)addStubbedRequest:(LSStubRequest *)request; +- (void)clearStubs; + +- (void)registerHook:(LSHTTPClientHook *)hook; + +- (LSStubResponse *)responseForRequest:(id)request; +@end diff --git a/Pods/Nocilla/Nocilla/LSNocilla.m b/Pods/Nocilla/Nocilla/LSNocilla.m new file mode 100644 index 0000000..c3e3fb3 --- /dev/null +++ b/Pods/Nocilla/Nocilla/LSNocilla.m @@ -0,0 +1,118 @@ +#import "LSNocilla.h" +#import "LSNSURLHook.h" +#import "LSStubRequest.h" +#import "LSHTTPRequestDSLRepresentation.h" +#import "LSASIHTTPRequestHook.h" +#import "LSNSURLSessionHook.h" +#import "LSASIHTTPRequestHook.h" + +NSString * const LSUnexpectedRequest = @"Unexpected Request"; + +@interface LSNocilla () +@property (nonatomic, strong) NSMutableArray *mutableRequests; +@property (nonatomic, strong) NSMutableArray *hooks; +@property (nonatomic, assign, getter = isStarted) BOOL started; + +- (void)loadHooks; +- (void)unloadHooks; +@end + +static LSNocilla *sharedInstace = nil; + +@implementation LSNocilla + ++ (LSNocilla *)sharedInstance { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedInstace = [[self alloc] init]; + }); + return sharedInstace; +} + +- (id)init { + self = [super init]; + if (self) { + _mutableRequests = [NSMutableArray array]; + _hooks = [NSMutableArray array]; + [self registerHook:[[LSNSURLHook alloc] init]]; + if (NSClassFromString(@"NSURLSession") != nil) { + [self registerHook:[[LSNSURLSessionHook alloc] init]]; + } + [self registerHook:[[LSASIHTTPRequestHook alloc] init]]; + } + return self; +} + +- (NSArray *)stubbedRequests { + return [NSArray arrayWithArray:self.mutableRequests]; +} + +- (void)start { + if (!self.isStarted){ + [self loadHooks]; + self.started = YES; + } +} + +- (void)stop { + [self unloadHooks]; + [self clearStubs]; + self.started = NO; +} + +- (void)addStubbedRequest:(LSStubRequest *)request { + NSUInteger index = [self.mutableRequests indexOfObject:request]; + + if (index == NSNotFound) { + [self.mutableRequests addObject:request]; + return; + } + + [self.mutableRequests replaceObjectAtIndex:index withObject:request]; +} + +- (void)clearStubs { + [self.mutableRequests removeAllObjects]; +} + +- (LSStubResponse *)responseForRequest:(id)actualRequest { + NSArray* requests = [LSNocilla sharedInstance].stubbedRequests; + + for(LSStubRequest *someStubbedRequest in requests) { + if ([someStubbedRequest matchesRequest:actualRequest]) { + return someStubbedRequest.response; + } + } + [NSException raise:@"NocillaUnexpectedRequest" format:@"An unexpected HTTP request was fired.\n\nUse this snippet to stub the request:\n%@\n", [[[LSHTTPRequestDSLRepresentation alloc] initWithRequest:actualRequest] description]]; + + return nil; +} + +- (void)registerHook:(LSHTTPClientHook *)hook { + if (![self hookWasRegistered:hook]) { + [[self hooks] addObject:hook]; + } +} + +- (BOOL)hookWasRegistered:(LSHTTPClientHook *)aHook { + for (LSHTTPClientHook *hook in self.hooks) { + if ([hook isMemberOfClass: [aHook class]]) { + return YES; + } + } + return NO; +} +#pragma mark - Private +- (void)loadHooks { + for (LSHTTPClientHook *hook in self.hooks) { + [hook load]; + } +} + +- (void)unloadHooks { + for (LSHTTPClientHook *hook in self.hooks) { + [hook unload]; + } +} + +@end diff --git a/Pods/Nocilla/Nocilla/Matchers/LSDataMatcher.h b/Pods/Nocilla/Nocilla/Matchers/LSDataMatcher.h new file mode 100644 index 0000000..f935da5 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Matchers/LSDataMatcher.h @@ -0,0 +1,16 @@ +// +// LSDataMatcher.h +// Nocilla +// +// Created by Luis Solano Bonet on 09/11/14. +// Copyright (c) 2014 Luis Solano Bonet. All rights reserved. +// + +#import +#import "LSMatcher.h" + +@interface LSDataMatcher : LSMatcher + +- (instancetype)initWithData:(NSData *)data; + +@end diff --git a/Pods/Nocilla/Nocilla/Matchers/LSDataMatcher.m b/Pods/Nocilla/Nocilla/Matchers/LSDataMatcher.m new file mode 100644 index 0000000..ed8c8d3 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Matchers/LSDataMatcher.m @@ -0,0 +1,51 @@ +// +// LSDataMatcher.m +// Nocilla +// +// Created by Luis Solano Bonet on 09/11/14. +// Copyright (c) 2014 Luis Solano Bonet. All rights reserved. +// + +#import "LSDataMatcher.h" + +@interface LSDataMatcher () + +@property (nonatomic, copy) NSData *data; + +@end + +@implementation LSDataMatcher + +- (instancetype)initWithData:(NSData *)data { + self = [super init]; + + if (self) { + _data = data; + } + return self; +} + +- (BOOL)matchesData:(NSData *)data { + return [self.data isEqualToData:data]; +} + + +#pragma mark - Equality + +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + + if (![object isKindOfClass:[LSDataMatcher class]]) { + return NO; + } + + return [self.data isEqual:((LSDataMatcher *)object).data]; +} + +- (NSUInteger)hash { + return self.data.hash; +} + +@end diff --git a/Pods/Nocilla/Nocilla/Matchers/LSMatcheable.h b/Pods/Nocilla/Nocilla/Matchers/LSMatcheable.h new file mode 100644 index 0000000..db14c6c --- /dev/null +++ b/Pods/Nocilla/Nocilla/Matchers/LSMatcheable.h @@ -0,0 +1,9 @@ +#import + +@class LSMatcher; + +@protocol LSMatcheable + +- (LSMatcher *)matcher; + +@end diff --git a/Pods/Nocilla/Nocilla/Matchers/LSMatcher.h b/Pods/Nocilla/Nocilla/Matchers/LSMatcher.h new file mode 100644 index 0000000..bea8305 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Matchers/LSMatcher.h @@ -0,0 +1,9 @@ +#import + +@interface LSMatcher : NSObject + +- (BOOL)matches:(NSString *)string; + +- (BOOL)matchesData:(NSData *)data; + +@end diff --git a/Pods/Nocilla/Nocilla/Matchers/LSMatcher.m b/Pods/Nocilla/Nocilla/Matchers/LSMatcher.m new file mode 100644 index 0000000..30dddde --- /dev/null +++ b/Pods/Nocilla/Nocilla/Matchers/LSMatcher.m @@ -0,0 +1,24 @@ +#import "LSMatcher.h" + +@implementation LSMatcher + +- (BOOL)matches:(NSString *)string { + @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[LSMatcher matches:] is an abstract method" userInfo:nil]; +} + +- (BOOL)matchesData:(NSData *)data { + return [self matches:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]]; +} + + +#pragma mark - Equality + +- (BOOL)isEqual:(id)object { + @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[LSMatcher isEqual:] is an abstract method" userInfo:nil]; +} + +- (NSUInteger)hash { + @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[LSMatcher hash] an abstract method" userInfo:nil]; +} + +@end diff --git a/Pods/Nocilla/Nocilla/Matchers/LSRegexMatcher.h b/Pods/Nocilla/Nocilla/Matchers/LSRegexMatcher.h new file mode 100644 index 0000000..7111c87 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Matchers/LSRegexMatcher.h @@ -0,0 +1,7 @@ +#import "LSMatcher.h" + +@interface LSRegexMatcher : LSMatcher + +- (instancetype)initWithRegex:(NSRegularExpression *)regex; + +@end diff --git a/Pods/Nocilla/Nocilla/Matchers/LSRegexMatcher.m b/Pods/Nocilla/Nocilla/Matchers/LSRegexMatcher.m new file mode 100644 index 0000000..b59b3c8 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Matchers/LSRegexMatcher.m @@ -0,0 +1,40 @@ +#import "LSRegexMatcher.h" + +@interface LSRegexMatcher () +@property (nonatomic, strong) NSRegularExpression *regex; +@end + +@implementation LSRegexMatcher + +- (instancetype)initWithRegex:(NSRegularExpression *)regex { + self = [super init]; + if (self) { + _regex = regex; + } + return self; +} + +- (BOOL)matches:(NSString *)string { + return [self.regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, string.length)] > 0; +} + + +#pragma mark - Equality + +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + + if (![object isKindOfClass:[LSRegexMatcher class]]) { + return NO; + } + + return [self.regex isEqual:((LSRegexMatcher *)object).regex]; +} + +- (NSUInteger)hash { + return self.regex.hash; +} + +@end diff --git a/Pods/Nocilla/Nocilla/Matchers/LSStringMatcher.h b/Pods/Nocilla/Nocilla/Matchers/LSStringMatcher.h new file mode 100644 index 0000000..56af212 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Matchers/LSStringMatcher.h @@ -0,0 +1,8 @@ +#import +#import "LSMatcher.h" + +@interface LSStringMatcher : LSMatcher + +- (instancetype)initWithString:(NSString *)string; + +@end diff --git a/Pods/Nocilla/Nocilla/Matchers/LSStringMatcher.m b/Pods/Nocilla/Nocilla/Matchers/LSStringMatcher.m new file mode 100644 index 0000000..8f90526 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Matchers/LSStringMatcher.m @@ -0,0 +1,42 @@ +#import "LSStringMatcher.h" + +@interface LSStringMatcher () + +@property (nonatomic, copy) NSString *string; + +@end + +@implementation LSStringMatcher + +- (instancetype)initWithString:(NSString *)string { + self = [super init]; + if (self) { + _string = string; + } + return self; +} + +- (BOOL)matches:(NSString *)string { + return [self.string isEqualToString:string]; +} + + +#pragma mark - Equality + +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + + if (![object isKindOfClass:[LSStringMatcher class]]) { + return NO; + } + + return [self.string isEqualToString:((LSStringMatcher *)object).string]; +} + +- (NSUInteger)hash { + return self.string.hash; +} + +@end diff --git a/Pods/Nocilla/Nocilla/Matchers/NSData+Matcheable.h b/Pods/Nocilla/Nocilla/Matchers/NSData+Matcheable.h new file mode 100644 index 0000000..c3dfef9 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Matchers/NSData+Matcheable.h @@ -0,0 +1,14 @@ +// +// NSData+Matcheable.h +// Nocilla +// +// Created by Luis Solano Bonet on 09/11/14. +// Copyright (c) 2014 Luis Solano Bonet. All rights reserved. +// + +#import +#import "LSMatcheable.h" + +@interface NSData (Matcheable) + +@end diff --git a/Pods/Nocilla/Nocilla/Matchers/NSData+Matcheable.m b/Pods/Nocilla/Nocilla/Matchers/NSData+Matcheable.m new file mode 100644 index 0000000..ab454bc --- /dev/null +++ b/Pods/Nocilla/Nocilla/Matchers/NSData+Matcheable.m @@ -0,0 +1,18 @@ +// +// NSData+Matcheable.m +// Nocilla +// +// Created by Luis Solano Bonet on 09/11/14. +// Copyright (c) 2014 Luis Solano Bonet. All rights reserved. +// + +#import "NSData+Matcheable.h" +#import "LSDataMatcher.h" + +@implementation NSData (Matcheable) + +- (LSMatcher *)matcher { + return [[LSDataMatcher alloc] initWithData:self]; +} + +@end diff --git a/Pods/Nocilla/Nocilla/Matchers/NSRegularExpression+Matcheable.h b/Pods/Nocilla/Nocilla/Matchers/NSRegularExpression+Matcheable.h new file mode 100644 index 0000000..9d9717f --- /dev/null +++ b/Pods/Nocilla/Nocilla/Matchers/NSRegularExpression+Matcheable.h @@ -0,0 +1,6 @@ +#import +#import "LSMatcheable.h" + +@interface NSRegularExpression (Matcheable) + +@end diff --git a/Pods/Nocilla/Nocilla/Matchers/NSRegularExpression+Matcheable.m b/Pods/Nocilla/Nocilla/Matchers/NSRegularExpression+Matcheable.m new file mode 100644 index 0000000..39792c5 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Matchers/NSRegularExpression+Matcheable.m @@ -0,0 +1,10 @@ +#import "NSRegularExpression+Matcheable.h" +#import "LSRegexMatcher.h" + +@implementation NSRegularExpression (Matcheable) + +- (LSMatcher *)matcher { + return [[LSRegexMatcher alloc] initWithRegex:self]; +} + +@end diff --git a/Pods/Nocilla/Nocilla/Matchers/NSString+Matcheable.h b/Pods/Nocilla/Nocilla/Matchers/NSString+Matcheable.h new file mode 100644 index 0000000..ca63ec7 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Matchers/NSString+Matcheable.h @@ -0,0 +1,6 @@ +#import +#import "LSMatcheable.h" + +@interface NSString (Matcheable) + +@end diff --git a/Pods/Nocilla/Nocilla/Matchers/NSString+Matcheable.m b/Pods/Nocilla/Nocilla/Matchers/NSString+Matcheable.m new file mode 100644 index 0000000..67809e0 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Matchers/NSString+Matcheable.m @@ -0,0 +1,10 @@ +#import "NSString+Matcheable.h" +#import "LSStringMatcher.h" + +@implementation NSString (Matcheable) + +- (LSMatcher *)matcher { + return [[LSStringMatcher alloc] initWithString:self]; +} + +@end diff --git a/Pods/Nocilla/Nocilla/Model/LSHTTPBody.h b/Pods/Nocilla/Nocilla/Model/LSHTTPBody.h new file mode 100644 index 0000000..8c26687 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Model/LSHTTPBody.h @@ -0,0 +1,5 @@ +#import + +@protocol LSHTTPBody +- (NSData *)data; +@end diff --git a/Pods/Nocilla/Nocilla/Model/LSHTTPRequest.h b/Pods/Nocilla/Nocilla/Model/LSHTTPRequest.h new file mode 100644 index 0000000..f0e7966 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Model/LSHTTPRequest.h @@ -0,0 +1,10 @@ +#import + +@protocol LSHTTPRequest + +@property (nonatomic, strong, readonly) NSURL *url; +@property (nonatomic, strong, readonly) NSString *method; +@property (nonatomic, strong, readonly) NSDictionary *headers; +@property (nonatomic, strong, readonly) NSData *body; + +@end diff --git a/Pods/Nocilla/Nocilla/Model/LSHTTPResponse.h b/Pods/Nocilla/Nocilla/Model/LSHTTPResponse.h new file mode 100644 index 0000000..db643b7 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Model/LSHTTPResponse.h @@ -0,0 +1,7 @@ +#import + +@protocol LSHTTPResponse +@property (nonatomic, assign, readonly) NSInteger statusCode; +@property (nonatomic, strong, readonly) NSDictionary *headers; +@property (nonatomic, strong, readonly) NSData *body; +@end diff --git a/Pods/Nocilla/Nocilla/Nocilla.h b/Pods/Nocilla/Nocilla/Nocilla.h new file mode 100644 index 0000000..d9cb1ab --- /dev/null +++ b/Pods/Nocilla/Nocilla/Nocilla.h @@ -0,0 +1,27 @@ +// +// Nocilla.h +// Nocilla +// +// Created by Robert Böhnke on 26/03/15. +// Copyright (c) 2015 Luis Solano Bonet. All rights reserved. +// + +#import + +//! Project version number for Nocilla. +FOUNDATION_EXPORT double NocillaVersionNumber; + +//! Project version string for Nocilla. +FOUNDATION_EXPORT const unsigned char NocillaVersionString[]; + +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import diff --git a/Pods/Nocilla/Nocilla/Stubs/LSStubRequest.h b/Pods/Nocilla/Nocilla/Stubs/LSStubRequest.h new file mode 100644 index 0000000..4a2cfe3 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Stubs/LSStubRequest.h @@ -0,0 +1,24 @@ +#import +#import "LSStubResponse.h" +#import "LSHTTPRequest.h" + + +@class LSMatcher; +@class LSStubRequest; +@class LSStubResponse; + +@interface LSStubRequest : NSObject +@property (nonatomic, strong, readonly) NSString *method; +@property (nonatomic, strong, readonly) LSMatcher *urlMatcher; +@property (nonatomic, strong, readonly) NSDictionary *headers; +@property (nonatomic, strong, readwrite) LSMatcher *body; + +@property (nonatomic, strong) LSStubResponse *response; + +- (instancetype)initWithMethod:(NSString *)method url:(NSString *)url; +- (instancetype)initWithMethod:(NSString *)method urlMatcher:(LSMatcher *)urlMatcher; + +- (void)setHeader:(NSString *)header value:(NSString *)value; + +- (BOOL)matchesRequest:(id)request; +@end diff --git a/Pods/Nocilla/Nocilla/Stubs/LSStubRequest.m b/Pods/Nocilla/Nocilla/Stubs/LSStubRequest.m new file mode 100644 index 0000000..1c29769 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Stubs/LSStubRequest.m @@ -0,0 +1,130 @@ +#import "LSStubRequest.h" +#import "LSMatcher.h" +#import "NSString+Matcheable.h" + +@interface LSStubRequest () +@property (nonatomic, strong, readwrite) NSString *method; +@property (nonatomic, strong, readwrite) LSMatcher *urlMatcher; +@property (nonatomic, strong, readwrite) NSMutableDictionary *mutableHeaders; + +-(BOOL)matchesMethod:(id)request; +-(BOOL)matchesURL:(id)request; +-(BOOL)matchesHeaders:(id)request; +-(BOOL)matchesBody:(id)request; +@end + +@implementation LSStubRequest + +- (instancetype)initWithMethod:(NSString *)method url:(NSString *)url { + return [self initWithMethod:method urlMatcher:[url matcher]]; +} + +- (instancetype)initWithMethod:(NSString *)method urlMatcher:(LSMatcher *)urlMatcher; { + self = [super init]; + if (self) { + self.method = method; + self.urlMatcher = urlMatcher; + self.mutableHeaders = [NSMutableDictionary dictionary]; + } + return self; +} + +- (void)setHeader:(NSString *)header value:(NSString *)value { + [self.mutableHeaders setValue:value forKey:header]; +} + +- (NSDictionary *)headers { + return [NSDictionary dictionaryWithDictionary:self.mutableHeaders];; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"StubRequest:\nMethod: %@\nURL: %@\nHeaders: %@\nBody: %@\nResponse: %@", + self.method, + self.urlMatcher, + self.headers, + self.body, + self.response]; +} + +- (LSStubResponse *)response { + if (!_response) { + _response = [[LSStubResponse alloc] initDefaultResponse]; + } + return _response; + +} + +- (BOOL)matchesRequest:(id)request { + if ([self matchesMethod:request] + && [self matchesURL:request] + && [self matchesHeaders:request] + && [self matchesBody:request] + ) { + return YES; + } + return NO; +} + +-(BOOL)matchesMethod:(id)request { + if (!self.method || [self.method isEqualToString:request.method]) { + return YES; + } + return NO; +} + +-(BOOL)matchesURL:(id)request { + return [self.urlMatcher matches:[request.url absoluteString]]; +} + +-(BOOL)matchesHeaders:(id)request { + for (NSString *header in self.headers) { + if (![[request.headers objectForKey:header] isEqualToString:[self.headers objectForKey:header]]) { + return NO; + } + } + return YES; +} + +-(BOOL)matchesBody:(id)request { + NSData *reqBody = request.body; + if (!self.body || [self.body matchesData:reqBody]) { + return YES; + } + return NO; +} + + +#pragma mark - Equality + +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + + if (![object isKindOfClass:[LSStubRequest class]]) { + return NO; + } + + return [self isEqualToStubRequest:object]; +} + +- (BOOL)isEqualToStubRequest:(LSStubRequest *)stubRequest { + if (!stubRequest) { + return NO; + } + + BOOL methodEqual = [self.method isEqualToString:stubRequest.method]; + BOOL urlMatcherEqual = [self.urlMatcher isEqual:stubRequest.urlMatcher]; + BOOL headersEqual = [self.headers isEqual:stubRequest.headers]; + BOOL bodyEqual = (self.body == nil && stubRequest.body == nil) || [self.body isEqual:stubRequest.body]; + + return methodEqual && urlMatcherEqual && headersEqual && bodyEqual; +} + +- (NSUInteger)hash { + return self.method.hash ^ self.urlMatcher.hash ^ self.headers.hash ^ self.body.hash; +} + +@end + + diff --git a/Pods/Nocilla/Nocilla/Stubs/LSStubResponse.h b/Pods/Nocilla/Nocilla/Stubs/LSStubResponse.h new file mode 100644 index 0000000..d0461db --- /dev/null +++ b/Pods/Nocilla/Nocilla/Stubs/LSStubResponse.h @@ -0,0 +1,18 @@ +#import +#import "LSHTTPResponse.h" + +@interface LSStubResponse : NSObject + +@property (nonatomic, assign, readonly) NSInteger statusCode; +@property (nonatomic, strong) NSData *body; +@property (nonatomic, strong, readonly) NSDictionary *headers; + +@property (nonatomic, assign, readonly) BOOL shouldFail; +@property (nonatomic, strong, readonly) NSError *error; + +- (id)initWithError:(NSError *)error; +- (id)initWithStatusCode:(NSInteger)statusCode; +- (id)initWithRawResponse:(NSData *)rawResponseData; +- (id)initDefaultResponse; +- (void)setHeader:(NSString *)header value:(NSString *)value; +@end diff --git a/Pods/Nocilla/Nocilla/Stubs/LSStubResponse.m b/Pods/Nocilla/Nocilla/Stubs/LSStubResponse.m new file mode 100644 index 0000000..06f67c7 --- /dev/null +++ b/Pods/Nocilla/Nocilla/Stubs/LSStubResponse.m @@ -0,0 +1,81 @@ +#import "LSStubResponse.h" + +@interface LSStubResponse () +@property (nonatomic, assign, readwrite) NSInteger statusCode; +@property (nonatomic, strong) NSMutableDictionary *mutableHeaders; +@property (nonatomic, assign) UInt64 offset; +@property (nonatomic, assign, getter = isDone) BOOL done; +@property (nonatomic, assign) BOOL shouldFail; +@property (nonatomic, strong) NSError *error; +@end + +@implementation LSStubResponse + +#pragma Initializers +- (id)initDefaultResponse { + self = [super init]; + if (self) { + self.shouldFail = NO; + + self.statusCode = 200; + self.mutableHeaders = [NSMutableDictionary dictionary]; + self.body = [@"" dataUsingEncoding:NSUTF8StringEncoding]; + } + return self; +} + + +- (id)initWithError:(NSError *)error { + self = [super init]; + if (self) { + self.shouldFail = YES; + self.error = error; + } + return self; +} + +-(id)initWithStatusCode:(NSInteger)statusCode { + self = [super init]; + if (self) { + self.shouldFail = NO; + self.statusCode = statusCode; + self.mutableHeaders = [NSMutableDictionary dictionary]; + self.body = [@"" dataUsingEncoding:NSUTF8StringEncoding]; + } + return self; +} + +- (id)initWithRawResponse:(NSData *)rawResponseData { + self = [self initDefaultResponse]; + if (self) { + CFHTTPMessageRef httpMessage = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, FALSE); + if (httpMessage) { + CFHTTPMessageAppendBytes(httpMessage, [rawResponseData bytes], [rawResponseData length]); + + self.body = rawResponseData; // By default + + if (CFHTTPMessageIsHeaderComplete(httpMessage)) { + self.statusCode = (NSInteger)CFHTTPMessageGetResponseStatusCode(httpMessage); + self.mutableHeaders = [NSMutableDictionary dictionaryWithDictionary:(__bridge_transfer NSDictionary *)CFHTTPMessageCopyAllHeaderFields(httpMessage)]; + self.body = (__bridge_transfer NSData *)CFHTTPMessageCopyBody(httpMessage); + } + CFRelease(httpMessage); + } + } + return self; +} + +- (void)setHeader:(NSString *)header value:(NSString *)value { + [self.mutableHeaders setValue:value forKey:header]; +} +- (NSDictionary *)headers { + return [NSDictionary dictionaryWithDictionary:self.mutableHeaders]; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"StubRequest:\nStatus Code: %ld\nHeaders: %@\nBody: %@", + (long)self.statusCode, + self.mutableHeaders, + self.body]; +} +@end diff --git a/Pods/Nocilla/README.md b/Pods/Nocilla/README.md new file mode 100644 index 0000000..4a9f47e --- /dev/null +++ b/Pods/Nocilla/README.md @@ -0,0 +1,213 @@ +# Nocilla [![CI Status](http://img.shields.io/travis/luisobo/Nocilla.svg?style=flat&branch=master)](https://travis-ci.org/luisobo/Nocilla)[![Version](https://img.shields.io/cocoapods/v/Nocilla.svg?style=flat)](http://cocoadocs.org/docsets/Nocilla)[![License](https://img.shields.io/cocoapods/l/Nocilla.svg?style=flat)](http://cocoadocs.org/docsets/Nocilla)[![Platform](https://img.shields.io/cocoapods/p/Nocilla.svg?style=flat)](http://cocoadocs.org/docsets/Nocilla) + +Stunning HTTP stubbing for iOS and OS X. Testing HTTP requests has never been easier. + +This library was inspired by [WebMock](https://github.com/bblimke/webmock) and it's using [this approach](http://www.infinite-loop.dk/blog/2011/09/using-nsurlprotocol-for-injecting-test-data/) to stub the requests. + +## Features +* Stub HTTP and HTTPS requests in your unit tests. +* Supports NSURLConnection, NSURLSession and ASIHTTPRequest. +* Awesome DSL that will improve the readability and maintainability of your tests. +* Match requests with regular expressions. +* Stub requests with errors. +* Tested. +* Fast. +* Extendable to support more HTTP libraries. + +## Installation +### As a [CocoaPod](http://cocoapods.org/) +Just add this to your Podfile +```ruby +pod 'Nocilla' +``` + +### Other approaches +* You should be able to add Nocilla to you source tree. If you are using git, consider using a `git submodule` + +## Usage +_Yes, the following code is valid Objective-C, or at least, it should be_ + +The following examples are described using [Kiwi](https://github.com/kiwi-bdd/Kiwi) + +### Common parts +Until Nocilla can hook directly into Kiwi, you will have to include the following snippet in the specs you want to use Nocilla: + +```objc +#import "Kiwi.h" +#import "Nocilla.h" +SPEC_BEGIN(ExampleSpec) +beforeAll(^{ + [[LSNocilla sharedInstance] start]; +}); +afterAll(^{ + [[LSNocilla sharedInstance] stop]; +}); +afterEach(^{ + [[LSNocilla sharedInstance] clearStubs]; +}); + +it(@"should do something", ^{ + // Stub here! +}); +SPEC_END +``` + +### Stubbing requests +#### Stubbing a simple request +It will return the default response, which is a 200 and an empty body. + +```objc +stubRequest(@"GET", @"http://www.google.com"); +``` + +#### Stubbing requests with regular expressions +```objc +stubRequest(@"GET", @"^http://(.*?)\\.example\\.com/v1/dogs\\.json".regex); +``` + + +#### Stubbing a request with a particular header + +```objc +stubRequest(@"GET", @"https://api.example.com"). +withHeader(@"Accept", @"application/json"); +``` + +#### Stubbing a request with multiple headers + +Using the `withHeaders` method makes sense with the Objective-C literals, but it accepts an NSDictionary. + +```objc +stubRequest(@"GET", @"https://api.example.com/dogs.json"). +withHeaders(@{@"Accept": @"application/json", @"X-CUSTOM-HEADER": @"abcf2fbc6abgf"}); +``` + +#### Stubbing a request with a particular body + +```objc +stubRequest(@"POST", @"https://api.example.com/dogs.json"). +withHeaders(@{@"Accept": @"application/json", @"X-CUSTOM-HEADER": @"abcf2fbc6abgf"}). +withBody(@"{\"name\":\"foo\"}"); +``` + +You can also use `NSData` for the request body: + +```objc +stubRequest(@"POST", @"https://api.example.com/dogs.json"). +withHeaders(@{@"Accept": @"application/json", @"X-CUSTOM-HEADER": @"abcf2fbc6abgf"}). +withBody([@"foo" dataUsingEncoding:NSUTF8StringEncoding]); +``` + +It even works with regular expressions! + +```objc +stubRequest(@"POST", @"https://api.example.com/dogs.json"). +withHeaders(@{@"Accept": @"application/json", @"X-CUSTOM-HEADER": @"abcf2fbc6abgf"}). +withBody(@"^The body start with this".regex); +``` + +#### Returning a specific status code +```objc +stubRequest(@"GET", @"http://www.google.com").andReturn(404); +``` + +#### Returning a specific status code and header +The same approch here, you can use `withHeader` or `withHeaders` + +```objc +stubRequest(@"POST", @"https://api.example.com/dogs.json"). +andReturn(201). +withHeaders(@{@"Content-Type": @"application/json"}); +``` + +#### Returning a specific status code, headers and body +```objc +stubRequest(@"GET", @"https://api.example.com/dogs.json"). +andReturn(201). +withHeaders(@{@"Content-Type": @"application/json"}). +withBody(@"{\"ok\":true}"); +``` + +You can also use `NSData` for the response body: + +```objc +stubRequest(@"GET", @"https://api.example.com/dogs.json"). +andReturn(201). +withHeaders(@{@"Content-Type": @"application/json"}). +withBody([@"bar" dataUsingEncoding:NSUTF8StringEncoding]); +``` + +#### Returning raw responses recorded with `curl -is` +`curl -is http://api.example.com/dogs.json > /tmp/example_curl_-is_output.txt` + +```objc +stubRequest(@"GET", @"https://api.example.com/dogs.json"). +andReturnRawResponse([NSData dataWithContentsOfFile:@"/tmp/example_curl_-is_output.txt"]); +``` + +#### All together +```objc +stubRequest(@"POST", @"https://api.example.com/dogs.json"). +withHeaders(@{@"Accept": @"application/json", @"X-CUSTOM-HEADER": @"abcf2fbc6abgf"}). +withBody(@"{\"name\":\"foo\"}"). +andReturn(201). +withHeaders(@{@"Content-Type": @"application/json"}). +withBody(@"{\"ok\":true}"); +``` + +#### Making a request fail +This will call the failure handler (callback, delegate... whatever your HTTP client uses) with the specified error. + +```objc +stubRequest(@"POST", @"https://api.example.com/dogs.json"). +withHeaders(@{@"Accept": @"application/json", @"X-CUSTOM-HEADER": @"abcf2fbc6abgf"}). +withBody(@"{\"name\":\"foo\"}"). +andFailWithError([NSError errorWithDomain:@"foo" code:123 userInfo:nil]); +``` + +#### Replacing a request stub + +If you need to change the response of a single request, simply re-stub the request: + +```objc +stubRequest(@"POST", @"https://api.example.com/authorize/"). +andReturn(401); + +// Some test expectation... + +stubRequest(@"POST", @"https://api.example.com/authorize/"). +andReturn(200); +``` + +### Unexpected requests +If some request is made but it wasn't stubbed, Nocilla won't let that request hit the real world. In that case your test should fail. +At this moment Nocilla will raise an exception with a meaningful message about the error and how to solve it, including a snippet of code on how to stub the unexpected request. + +### Testing asynchronous requests +When testing asynchrounous requests your request will be sent on a different thread from the one on which your test is executed. It is important to keep this in mind, and design your test in such a way that is has enough time to finish. For instance ```tearDown()``` when using ```XCTest``` and ```afterEach()``` when using [Quick](https://github.com/Quick/Quick) and [Nimble](https://github.com/Quick/Nimble) will cause the request never to complete. + + +## Who uses Nocilla. + +### Submit a PR to add your company here! + +- [MessageBird](https://www.messagebird.com) +- [Groupon](http://www.groupon.com) +- [Pixable](http://www.pixable.com) +- [Jackthreads](https://www.jackthreads.com) +- [ShopKeep](http://www.shopkeep.com) +- [Venmo](https://www.venmo.com) +- [Lighthouse](http://www.lighthouselabs.co.uk) +- [GE Digital](http://www.ge.com/digital/) + +## Other alternatives +* [ILTesting](https://github.com/InfiniteLoopDK/ILTesting) +* [OHHTTPStubs](https://github.com/AliSoftware/OHHTTPStubs) + +## Contributing + +1. Fork it +2. Create your feature branch +3. Commit your changes +4. Push to the branch +5. Create new Pull Request diff --git a/Pods/Pods.xcodeproj/project.pbxproj b/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 0000000..9cfc267 --- /dev/null +++ b/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,2521 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 0072016FECB4F11D51CF666F71713F9E /* NSString+Nocilla.m in Sources */ = {isa = PBXBuildFile; fileRef = E14458DC858BFCB6F9E80CBC95A1DE10 /* NSString+Nocilla.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 00E8F3031E1B84826D9BE64F0839F209 /* BeCloseTo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FB7DEAF15D7E7DDE899E9D09569708F /* BeCloseTo.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 01FB80B2F451C84E420EF3464F5BA926 /* LSHTTPClientHook.m in Sources */ = {isa = PBXBuildFile; fileRef = F813B762FD46FFE133BE08FBA25199EF /* LSHTTPClientHook.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 02768FD7624F8269944D5B2F6F6FA849 /* Pods-AstroTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 5CB1530548D1D9E85E0CA807FE68F4B5 /* Pods-AstroTests-dummy.m */; }; + 05A6506FFFC7C3D12FD341B6456DA0E1 /* JSONEncodingDetector.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89F15E9D033FC5A11A4ACE1741A56934 /* JSONEncodingDetector.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 0718AC0FCBCC64B3C21761D890ED9705 /* UIView+AstroGadgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1DA4BC7AA452C12ED8B08E83DB465C62 /* UIView+AstroGadgets.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 0A3806CD95128F25EE8B4C806FC19522 /* LSStubResponseDSL.m in Sources */ = {isa = PBXBuildFile; fileRef = A9ECE62FAB6CC87EAE56E9EC7C2533EB /* LSStubResponseDSL.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 0A56DFB216D6CBFDE7D38CC82A56C714 /* Quick-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = A45861F28898647557DF322055128938 /* Quick-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0BC644233E7FC0A53C9BA5EC6B87A206 /* NSRegularExpression+Matcheable.m in Sources */ = {isa = PBXBuildFile; fileRef = D61DFEA183AEE286758C8B5617777825 /* NSRegularExpression+Matcheable.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 0D96C808906230C689C8310AC8E7DF5B /* LSNSURLSessionHook.h in Headers */ = {isa = PBXBuildFile; fileRef = 09369E6621D03C4D8547E467FB8526B3 /* LSNSURLSessionHook.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 0ED93C20ACB41E7260F5EB39152BDB80 /* NimbleEnvironment.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32930ABA04829C715E9309828367451B /* NimbleEnvironment.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 11114986CC066598887F794DDAB40F79 /* SwiftTask-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 7AE15AE95C7899FDFDF008072E2A12D8 /* SwiftTask-dummy.m */; }; + 113AA408C176B305168CEA5953B5010F /* _Atomic.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FAC898952701B46D5209EBB19206322 /* _Atomic.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 128B9A07E9D0F95B28E5F1F3483CB7EA /* LSASIHTTPRequestAdapter.h in Headers */ = {isa = PBXBuildFile; fileRef = 5B700373BAD98857FB8B7D43320BAE6E /* LSASIHTTPRequestAdapter.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 13202614FB4A2465FD5D212AC6393DE6 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D57166DA009DF7F279278E659B83001 /* Request.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 15A7217C749314E8423F3C36A99BAF7A /* LSHTTPStubURLProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 8AEC080634ED245BCD85C53126EE83FC /* LSHTTPStubURLProtocol.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 166F14EC7CAB35D2416D035FA9B46489 /* LayoutLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90C80D0F88F467734DCA9AB2BD6754E5 /* LayoutLabel.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 1910721AF00D699CA600DC76F1DD8931 /* Astro-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = AD7D87EC77CCE2F8C0B6D5BD0C78F808 /* Astro-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1A2025245F64F843C4AB6B5722EAB24D /* Freddy-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = E0F3F1404956E871D7ECA60C378BAA60 /* Freddy-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1ABB56F9E693961F44E26B982755F343 /* BeLogical.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC64FABB231B2528B5FD76A4AC394DB5 /* BeLogical.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 1C46D0414C094C95AD85104D38B72539 /* LSMatcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 6205D5C0FB3D9036F177DEBF76CD96BC /* LSMatcher.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 1D83128B49CF158BA287773A81D4B840 /* _StateMachine.swift in Sources */ = {isa = PBXBuildFile; fileRef = E8A6B56079D4CA08CE38423A96EEF85B /* _StateMachine.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 206541BC9991EE86512D593D96EA83B3 /* Closures.swift in Sources */ = {isa = PBXBuildFile; fileRef = 76152E950AB1F0ECD2EA3B0B2D380365 /* Closures.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 2070701995190A07047F664492D7F156 /* LSNocilla.h in Headers */ = {isa = PBXBuildFile; fileRef = 740A1225FBB93D00E7780C9248E24F10 /* LSNocilla.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 21B9BDF15D08F33883999509AC98847C /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E4D54383DE9F48DD36B48F77E57BF01E /* CFNetwork.framework */; }; + 22E176E365EF446AD2ACADC28199A3DE /* DSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 764D3566600AF08BE9E045AD225DDE34 /* DSL.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 23626BC4DDA1A2E90A155728F57802FF /* DSL.h in Headers */ = {isa = PBXBuildFile; fileRef = 6B93B92F0117AC91DA973DD6FA708339 /* DSL.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 236EB99AF4ED58D8A5B3E9F8B1A0246D /* NSString+QCKSelectorName.m in Sources */ = {isa = PBXBuildFile; fileRef = B360270783ED44EAB36B632CDA94A249 /* NSString+QCKSelectorName.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 245C3CE9E2761F83E4D5E258E2BD3622 /* ExceptionCapture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1FADAF5723E3783E2D2CB736373725B5 /* ExceptionCapture.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 24B569099A40F837596002531AEBBE6C /* Nocilla-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 1BB32E06FD13A42B1754090B64ABA926 /* Nocilla-dummy.m */; }; + 250B90954338EEFB0EBC6DAA23894DDA /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD33E17A1452351E0F9E09CD13FDC6B8 /* Stream.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 27832B2605A37241AF9CD554C9ECB6D0 /* LSASIHTTPRequestHook.h in Headers */ = {isa = PBXBuildFile; fileRef = 1B0BC0D43B557E478A7AC87FC68C3B22 /* LSASIHTTPRequestHook.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 288B407C1861C325D63558155BE51969 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE5E7EF01AC1AFCC9C8519CE17A4B669 /* Notifications.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 2B6556DC8741783CA1F65FA4336F2D3E /* KeychainAccess.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F9C1070A7DA056DC96366DD7AB5D032 /* KeychainAccess.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 2BC2F1D0EDC01B4314095492D16E1AC4 /* LSStubRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 933EED4371DBCE2167B600FC06C24228 /* LSStubRequest.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 2DBDF5B701DC699F0E5A0ADCFF7F3E94 /* NSURLRequest+LSHTTPRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 66CC9B801997F61B96C5719193CA636D /* NSURLRequest+LSHTTPRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 2F2E9CFF89016043EAF1D3885AC7C696 /* QCKDSL.h in Headers */ = {isa = PBXBuildFile; fileRef = 3C8AF1FA9140A19391F57B93E8FBEAC4 /* QCKDSL.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 30A99A47BC4031E7C5677314FDBF61A6 /* Pods-Astro-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 4046EBF9B062ED9B23FAB96D07561CA0 /* Pods-Astro-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 317E3ED277933E30E597B27316D856E9 /* BeginWith.swift in Sources */ = {isa = PBXBuildFile; fileRef = 018EC0A4904E4B088A5A073E648C19B5 /* BeginWith.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 32A4654CFE28CA25FF57109B50458608 /* Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89733119C7341F88D957D4C16F746E25 /* Filter.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 34EBD194EA1085AF68F7670FA9F16DAD /* Nimble-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 73D4F264A8ACC108D2139D0C740EE235 /* Nimble-dummy.m */; }; + 351E7765D3B3ADCA308F5A1844DC6761 /* LSNSURLHook.m in Sources */ = {isa = PBXBuildFile; fileRef = 57BCDA3FA7A78B29FC1010111712059F /* LSNSURLHook.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 3785C751B37F631F158EA4CCCB942A9E /* FailureMessage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 246E55C5423DE0296BF8B2E2283F8451 /* FailureMessage.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 383F4AF6C46AA6AC9F9217AF905FB7D8 /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = C92A12C07271BFC6F6C83EDC7DC1F6C7 /* Timeline.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 39E1878913C1AD8669DA18845D2BC218 /* LSRegexMatcher.m in Sources */ = {isa = PBXBuildFile; fileRef = BDCD7A584251A05E7546A8C30B112AD0 /* LSRegexMatcher.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 3B4F15B3D4EBB8580874CFA87CAAB437 /* LSDataMatcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 08EBF5E98850CE0D59CD4790AE4E05A9 /* LSDataMatcher.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 3B588A1AD8E3D88B70EF1A8D3CF519ED /* LSHTTPRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 0E5CF2AB8A1768830A16697E65455D4A /* LSHTTPRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 3BA67C86ED6B34936485F11775AB6847 /* LSASIHTTPRequestAdapter.m in Sources */ = {isa = PBXBuildFile; fileRef = F598CC4E191ADFF7C8DF93B4B9A22F13 /* LSASIHTTPRequestAdapter.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 3C380C634D63206648B6D947901FF88D /* NSData+Nocilla.h in Headers */ = {isa = PBXBuildFile; fileRef = 8A08012C92D3BEB87C3BAF924DF17BA0 /* NSData+Nocilla.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 40B6973E8E5464C0C97726DC08D36735 /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = E99A028ACF5FC3336D388BD40CF620DB /* Manager.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 4253F20907FA7DA4F0CF6E404BC9C15B /* NSURLRequest+LSHTTPRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 2B3E454647835A4B7F4C78D3958A9F1A /* NSURLRequest+LSHTTPRequest.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 4741FF4EC5B93F91C3E08226094965F8 /* Cancellable.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4B872C6EE9A742550A25D71A7BEAC5C /* Cancellable.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 47449108E9477D61EB43B0D39602B4C6 /* EnumCountable.swift in Sources */ = {isa = PBXBuildFile; fileRef = F511D0AF6267ABF4691C1EDE99FB659D /* EnumCountable.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 47CBCE8837CE75AE1B7484A63CE387ED /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4BC8039B74D4913DB1E703B667824C32 /* Foundation.framework */; }; + 49E22CBCE875C080D24BC37F234A510D /* NetworkService.swift in Sources */ = {isa = PBXBuildFile; fileRef = FBBBDB2DA9151DCA301BF0A6E773F9FF /* NetworkService.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 4A98AA6B071BEB79642C94C5F58E0D5C /* AssertionDispatcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4BCE60758BD208F904264B1F4A110801 /* AssertionDispatcher.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 4A99D0FD16A6B1386D175E720B3CE84F /* JSONParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1E27637BAEF011157068373797A74D3 /* JSONParser.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 4B0FACF86699832CB060706698EEDA62 /* LSRegexMatcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 6360E2524B77978580F6B83A3067E9B3 /* LSRegexMatcher.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 4F2873EB618D3BB1893CA07D711F70A5 /* BeAnInstanceOf.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED9D4484D8A9B8DCBFDDE991EC024DD0 /* BeAnInstanceOf.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 4FF8A2C2644173400B8E4CC7BE4D6D77 /* LSHTTPRequestDSLRepresentation.m in Sources */ = {isa = PBXBuildFile; fileRef = EEBD54710A06AEF2A841D76C5D103DCA /* LSHTTPRequestDSLRepresentation.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 514A09BBB819F361E14EA3435507C489 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70D64846E5ED48505B235794D511C710 /* ServerTrustPolicy.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 51F46241DBFA48BE6840E89B60B5C761 /* LSNocilla.m in Sources */ = {isa = PBXBuildFile; fileRef = 5A1C175C7A891D63E146044DF96BD727 /* LSNocilla.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 52695B80D42DFB4C48D7A906478509EB /* ASIHTTPRequestStub.h in Headers */ = {isa = PBXBuildFile; fileRef = F1CDA5C29F4226AB151CCB0A717465AA /* ASIHTTPRequestStub.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 526A4F774F884C5AD7218959ABC26F85 /* DSL.m in Sources */ = {isa = PBXBuildFile; fileRef = 01B684422F9A68DB967394EAC091E627 /* DSL.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 535D3135B94BEAB04C06E35B082E903E /* QuickTestSuite.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4B423AF51FEE630622404ABCA692786 /* QuickTestSuite.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 5546B5D9DA48D039B6AA3267D7B6EAE5 /* LSHTTPRequestDiff.m in Sources */ = {isa = PBXBuildFile; fileRef = 2E84C95072B0D268B49E3983BA78D64F /* LSHTTPRequestDiff.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 576E5BF23D4A2AF6752939D87C211DDD /* DSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6ACE15C16D148D217BDB20FFEFFCF02F /* DSL.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 57F4598D24E6102AC980D15E2071E622 /* SwiftTask.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FDE84FF0D7B9663C062BD966122BCA44 /* SwiftTask.framework */; }; + 58CEC650377EB4317EA70FF0120977AE /* UIColor+AstroGadgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = A52A75DB7A7E8D5ABD5E0A8677F3C487 /* UIColor+AstroGadgets.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 5B4D445D893A387017723FFC687F7DFB /* ObjCMatcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = DFC4284902E1C186D4B5C7BBFCD91B84 /* ObjCMatcher.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 5BF59C189F6C80B4D28AF7C62DDFC814 /* BeGreaterThan.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB8028483A380281298717B363ED326E /* BeGreaterThan.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 5C50D4DC86334599B9967449D88C8449 /* LSDataMatcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 215B768C828ACF6EDCAD625F7A57F60A /* LSDataMatcher.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 617FB9A348751ECB4250ABA0316403AC /* QuickConfiguration.h in Headers */ = {isa = PBXBuildFile; fileRef = 850C70E03DB4FE8DE70A33C20FA18FDE /* QuickConfiguration.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6192D80DE5F8072E50F8AD94DB6BA606 /* BeGreaterThanOrEqualTo.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC2B2BF86C08224CC0CA71E6FFEB075B /* BeGreaterThanOrEqualTo.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 620573B34B510155CC9431432ECE0F38 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D97CC484A2DBEFEC771C1025EBC41CCE /* UIKit.framework */; }; + 66C66EF805856C9D32E51795F595052B /* NMBExceptionCapture.m in Sources */ = {isa = PBXBuildFile; fileRef = CAB0BDFFF1C8029048D89A3BF0057285 /* NMBExceptionCapture.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 683D42CCDBA04DEAA5927130555865FB /* LSStringMatcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 037D5199F69F8288CA074CDE9981C835 /* LSStringMatcher.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 684CCDCA3C79B9A4CFE267558B6384C8 /* Contain.swift in Sources */ = {isa = PBXBuildFile; fileRef = B53C5ACBAE69917D3C14246F861DF751 /* Contain.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 6AAD3EF28C1C2DA026B93AD8D814F64D /* Nocilla-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 376A62A3AEF587E01593F5D415550697 /* Nocilla-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6B8050E7370748D1CB6031A31CD45791 /* JSONSerializing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 85F553423E820BBA7AFF070E59F8F811 /* JSONSerializing.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 6CA4041059696980C1FFD83079432504 /* BeLessThan.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2674300CB730134EDCAD3694E9665CB1 /* BeLessThan.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 6D895AA3CD19AA14FC8B6D0AA11FD213 /* SwiftTask.h in Headers */ = {isa = PBXBuildFile; fileRef = 718746D488FF4E2AEB19CEAEFC5596A1 /* SwiftTask.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6F9AC619478339681794CFB2FFF49EA3 /* LSStubRequestDSL.h in Headers */ = {isa = PBXBuildFile; fileRef = 24EB686A9187237EC0D542A4A26881AF /* LSStubRequestDSL.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7071128811148914D1738564C0EEAD5E /* Expression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D6A308350139622BAE6ACB0FECD59AA /* Expression.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 71E52833B614749DD58941AB12CDFBBB /* Pods-Astro-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 6CA7B27079A3AE437FFB717B6CEB7766 /* Pods-Astro-dummy.m */; }; + 73000FB0D08D09BCAFF0052F746E2749 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4BC8039B74D4913DB1E703B667824C32 /* Foundation.framework */; }; + 734D4E9CBF9F977A8B62365C32ED517B /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A70FC1773E4B74A1B01208EEB34131B /* MultipartFormData.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 73C671D884BB1EBC50D22264C30ACBF0 /* LSNSURLSessionHook.m in Sources */ = {isa = PBXBuildFile; fileRef = 8E019C411893B8E5CC125BDB3D9C356B /* LSNSURLSessionHook.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 746762DD022722AA0783532E872ACCC0 /* LSHTTPBody.h in Headers */ = {isa = PBXBuildFile; fileRef = 1C7E74E409C0A0FF82091CE470CC633D /* LSHTTPBody.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 781A3371065498563238D5E4E7F7BC49 /* LSStubResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 8A50386EDB40911FEABEAED0E4BB975B /* LSStubResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 7A3FEC3C8303482043DB7C0A6184BF08 /* ASIHTTPRequestStub.m in Sources */ = {isa = PBXBuildFile; fileRef = 21E6E306A222BB7B4910F4381D552E4A /* ASIHTTPRequestStub.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 7A692287BA635EFE6ECB63A1CB023E8F /* BeIdenticalTo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08557293038B060E63351D04FAA3661B /* BeIdenticalTo.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 7B58011958B21BE947D3AB53CC88EAEC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4BC8039B74D4913DB1E703B667824C32 /* Foundation.framework */; }; + 7BA96342CEA620B4EDDD7C5D42B8446B /* Example.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB748F8E3291D161137C48DABBCDBE4D /* Example.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 7CD46F6BA12D86D277CF97DF472C6BF3 /* JSONEncodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08503275A881C4B454DE98666EC4042D /* JSONEncodable.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 7CF0F6A48A0677DE2908A8D931A99ADC /* Quick.h in Headers */ = {isa = PBXBuildFile; fileRef = 46F5790BDF2B23727CBEED623FA4B790 /* Quick.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7E8EBE325AE2D649132EC27CBF0C7A3F /* BeEmpty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44538300F5802FC65969BBF566DFB619 /* BeEmpty.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 7EED0AB84822BB4A0C3F059E3AC0901B /* JSONDecodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7A349A616F16796BBF0F5C63AD4A0D1 /* JSONDecodable.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 805A1E05545888A4E807D5835B5D1D0E /* Functional.swift in Sources */ = {isa = PBXBuildFile; fileRef = E21EAC014ECB332659AE5CE74500EC21 /* Functional.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 80C451D6026B1C2BF6EF917B4F5BF98B /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4BC8039B74D4913DB1E703B667824C32 /* Foundation.framework */; }; + 818AFDAE110D05038CAA1229DAA195F8 /* SwiftTask.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5FB155AAF1F83A98BD9205C317F51C6 /* SwiftTask.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 826517FF4AF1F646EE0FDC01B6C82722 /* ExampleHooks.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC772B3FDB7176368B55A892D4C5226C /* ExampleHooks.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 82D1A45C067C46EA182F5271C7CF8398 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = C38CF09F3C3B8CF308264F6D6E482788 /* Alamofire.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 82EB4519BD169631C09074DFC535E4B6 /* QCKDSL.m in Sources */ = {isa = PBXBuildFile; fileRef = AF9CB0DF1DAF7BC0001D68009B77DAEC /* QCKDSL.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 83275420D9F49327728E1560D2995196 /* AsyncMatcherWrapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07D74A91BCFD69C9E1C3F3BBF9CC777B /* AsyncMatcherWrapper.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 863E32885CF961E10C349860B945D58C /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE1DED67D6DF1F164F02F3F1476DFA5A /* Error.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 86FB708FCFE6121A82BB09E5ADD84554 /* NMBExceptionCapture.h in Headers */ = {isa = PBXBuildFile; fileRef = C9DEBF825D7E53BF5C8D0F265A9A1AE5 /* NMBExceptionCapture.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8901F90279DCCB94E2281EB8F8C19CB4 /* Expectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F3C0C399D268AA91831AE634921FDF4 /* Expectation.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 8927C37DD5750B9F6409C3EA80623A16 /* NSURLRequest+DSL.h in Headers */ = {isa = PBXBuildFile; fileRef = CD81E565DFBCD23784D4A379ADF1815F /* NSURLRequest+DSL.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 8F83B5ED706BFAA72FC788835E165942 /* ExampleMetadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3375C76C22C797C8327948D959CE686D /* ExampleMetadata.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 8F86133FD6D0F537A52D317518115BC5 /* QuickSpec.h in Headers */ = {isa = PBXBuildFile; fileRef = 25A9215971B7F9942A388AFF5A7F225C /* QuickSpec.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 907B0A62D05C5C9EF8DCDCBA7F8868B7 /* Match.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E203099AEBFA89BB26866928B47B729 /* Match.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 91A0D6340157F6B4741AC14CC07CE36A /* JSONParsing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 355843C6E194A70E0B6A53BB4ED12699 /* JSONParsing.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 91C09AC2A52ED69A27C8D923139A006F /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4BC8039B74D4913DB1E703B667824C32 /* Foundation.framework */; }; + 924BB4EFA04157C8C446B30422705105 /* World+DSL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1DAF602663993CD69CB887EFF206A219 /* World+DSL.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 929FE93E64765FF5AE1BFBA880F12F4C /* ErrorUtility.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B210588090C1A8615A7263069ACF6F9 /* ErrorUtility.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 9383E5B09D57567485DE04EF035356D9 /* Equal.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE61F544EA1DEB7394D1DB26182F1849 /* Equal.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 7FD0E7B25D8D24C9A657D2405566EC54 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9590790CA8C71CFF36DBF303367C65BE /* String+FileName.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F91823DE328E0C3D6BDE74B168C5414 /* String+FileName.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 96B3C342BDC597A6B683D356BFC7BB59 /* DSL+Wait.swift in Sources */ = {isa = PBXBuildFile; fileRef = F897256CD08EAEADC4CF349C4A56D98D /* DSL+Wait.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 98448E68F706C3077F402B1F1B64520E /* NSData+Matcheable.h in Headers */ = {isa = PBXBuildFile; fileRef = B24FBEF8AB502215F26A19C54552E53D /* NSData+Matcheable.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9B078190829C71BDE57F32CA21580BF0 /* LSHTTPStubURLProtocol.m in Sources */ = {isa = PBXBuildFile; fileRef = 935CB3CC8195F22FBF8955E2FD8A07BB /* LSHTTPStubURLProtocol.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 9B27F32E5D611571AF5233DCEF8CB00C /* QuickSelectedTestSuiteBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = E019BD16B087EDC3E10B12C2D5466294 /* QuickSelectedTestSuiteBuilder.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 9BC56CBFF66FE0AC478DA745EEAE8871 /* Log.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40766F0C467159B985AA2723FF099609 /* Log.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 9C5DF5EA387519C5C1B8FA73FBE0014E /* XCTestSuite+QuickTestSuiteBuilder.m in Sources */ = {isa = PBXBuildFile; fileRef = B3C64DCAF1544AC0A8D47DE543C5DFD7 /* XCTestSuite+QuickTestSuiteBuilder.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 9D6237C3E43CDB3EC681C88CBE3229E3 /* PostNotification.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C7DE601C7FCC67C58CFF4B7F6509262 /* PostNotification.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + A13F241863C06A82E01A3486274BAA3B /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B6175C0F07945B33BA87785C28C9912 /* Download.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + A1B364D6ACB3B19F7ED2AF7989BB3197 /* Freddy.h in Headers */ = {isa = PBXBuildFile; fileRef = 07DCDEDF9C00CC7D1C61D1D38C722EBD /* Freddy.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A434C8CB0F23A35DA222105C7B11300D /* LSHTTPRequestDiff.h in Headers */ = {isa = PBXBuildFile; fileRef = 99BA98371CC71CBBD02B1C626F309DCD /* LSHTTPRequestDiff.h */; settings = {ATTRIBUTES = (Project, ); }; }; + A460983620B3719092C5217CCC57A699 /* LSHTTPRequestDSLRepresentation.h in Headers */ = {isa = PBXBuildFile; fileRef = 2C6D3290D1DBF2130A57A59FDF56617D /* LSHTTPRequestDSLRepresentation.h */; settings = {ATTRIBUTES = (Project, ); }; }; + A4EBAF74EB6135EB10930E2FC120B6CE /* Stringers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 580685080BA8A710801E892C91D930A0 /* Stringers.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + A6A54F64F620A12FB4845FAA238206A7 /* NSData+Nocilla.m in Sources */ = {isa = PBXBuildFile; fileRef = 2B34E178970B70AF83F2D0104154B4C6 /* NSData+Nocilla.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + A7BCB78230139B58161146365F858C78 /* BeNil.swift in Sources */ = {isa = PBXBuildFile; fileRef = 49E1B592BED6BB90BB6F2F89FA3E989E /* BeNil.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + A8F7B821E99BED8460534AD85FD1F269 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4BC8039B74D4913DB1E703B667824C32 /* Foundation.framework */; }; + AB6DD25D9C52C34F62068EB8635763F6 /* HooksPhase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D267E39340A0E1533C5C6BB5559E9FE /* HooksPhase.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + ABD57ABE0CA2D5E9EDDB246A64C1AD1D /* Callsite.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB1A413A673529FE4EA52BC8ADD3F528 /* Callsite.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + AC0BD0F23C2A8C8F350899F45DB4F91F /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2A80AABF30E3F90F8BE459718464BF9 /* Validation.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + AC0F9DEB7167B144AD3A2175E0D48B8B /* NSBundle+CurrentTestBundle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B9DDD2E2D087DE41FE10BBE3FB84940 /* NSBundle+CurrentTestBundle.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + ACF38EF4EB8775D8AC246D7CCBFB441F /* AssertionRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFA756C9D950245A5366DD0A0EC267EC /* AssertionRecorder.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + AEF2C12D4B021FEE2401595457B23CBE /* SwiftTask-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 18EA6F2FCD99D7DD985FCAEA6EC626DC /* SwiftTask-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B0BD13A01F667B129F4F5F167088A024 /* Nocilla.h in Headers */ = {isa = PBXBuildFile; fileRef = 1DB921FDEB8F795C32706D42D10E99AD /* Nocilla.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B0C70D84FFA2025CCA0A741F2999B6FE /* CurrentTestCaseTracker.m in Sources */ = {isa = PBXBuildFile; fileRef = 5C73A1245CDA974F563837D844547617 /* CurrentTestCaseTracker.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + B0CA346E3898D1F58F2ED08B9A06DF80 /* ThrowError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 20DECE4687279E305EE363109B2CEAF4 /* ThrowError.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + B30D380B5EFCD54FEE04D3C4F1988262 /* NSString+Nocilla.h in Headers */ = {isa = PBXBuildFile; fileRef = AF89FEF1C7D784E5CAB83C46017149C3 /* NSString+Nocilla.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B4907351FF7E7AEEAC1F6DADB3ABED1F /* NSURLRequest+DSL.m in Sources */ = {isa = PBXBuildFile; fileRef = EFA45F884E74D416A2CB94D83F76A11A /* NSURLRequest+DSL.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + B7B6C386D18C61D236CE7B92C62DC4F4 /* LSHTTPResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 666499CBBC4996DE397CA1CCF1689947 /* LSHTTPResponse.h */; settings = {ATTRIBUTES = (Project, ); }; }; + B7BAA1610C192270DE28D6F9ACE95542 /* LSStubResponseDSL.h in Headers */ = {isa = PBXBuildFile; fileRef = 486AD68885FD024FAA1DE18E7B99E032 /* LSStubResponseDSL.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B8C5A113F98D10AE527D439BD26EE33F /* LSStubResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = CA7F9F2D3BC0D743DB62F65F771E6E96 /* LSStubResponse.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + BAA7AFC5CBADB79878E29A8A77903260 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4BC8039B74D4913DB1E703B667824C32 /* Foundation.framework */; }; + BAB651A8F623A6E827FC716A62B9F74D /* LSStringMatcher.m in Sources */ = {isa = PBXBuildFile; fileRef = E2993F8A9771156E121C62FFBEBBEB2D /* LSStringMatcher.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + BAE69CD22A7C90828180D3664DED8E1A /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC549157357F78725756BA1D794D8956 /* Result.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + BB4CE418BA5B88DA624FA3373A34A236 /* HTTPStatusCode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7AB33573A133A91BFBE2D06A0EEA0ADF /* HTTPStatusCode.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + BC59A31255D804C8B2FD3144B4138B67 /* HaveCount.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDFD96BF70CDC200784A60185BE056A8 /* HaveCount.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + BE2859F1F4050BADFDDF76A557CF0FE7 /* World.h in Headers */ = {isa = PBXBuildFile; fileRef = B79754ADC53CA9E03EA5250AAF1BD4FF /* World.h */; settings = {ATTRIBUTES = (Project, ); }; }; + BE5AF0662CD8B472503A8E996260B213 /* QuickSpec.m in Sources */ = {isa = PBXBuildFile; fileRef = 2D8D24CBFA077EE8C5F66870B269186B /* QuickSpec.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + BFA5019B45418DEBAD3D0BE9E85609E5 /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FF14E7E64D23B07812BAF0C10D193605 /* Alamofire.framework */; }; + C375CF1D80C1EDAF7A59CF55A204A1EA /* LSASIHTTPRequestHook.m in Sources */ = {isa = PBXBuildFile; fileRef = C3BBBE6BD192BF863A94377B37488914 /* LSASIHTTPRequestHook.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + C3DF7DC84C3889C096A32E13A862BD32 /* SatisfyAnyOf.swift in Sources */ = {isa = PBXBuildFile; fileRef = B118A954E3CE6751BEDDA7A3621C8B1B /* SatisfyAnyOf.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + C4F4C8EF4A764C0FDEB5789F9207FFF2 /* LSNSURLHook.h in Headers */ = {isa = PBXBuildFile; fileRef = AB051FCF80CC7C2B73C825DBEF35252A /* LSNSURLHook.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C67CC9B37557A88C14D320B410CBA00A /* AdapterProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 556FA88DC471542F2CB2B5EB084A211A /* AdapterProtocols.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + C86923E3A6648C9DE493F465644EE071 /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48BE2756E789DA180A9EE1D5BE1874A4 /* Upload.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + CA00C21F8A03E237E579CD6DA42B0DF0 /* LSMatcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 62A18C9C05326332D45658DF26A5DC52 /* LSMatcher.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CA303CF6D30D41F05C81DF35576B6C34 /* LSMatcheable.h in Headers */ = {isa = PBXBuildFile; fileRef = BEF4A9B34EFBF0E5660D27C57A2C9605 /* LSMatcheable.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CAFBD098436FD07E8838B47730DCF021 /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6BCA294AF3615B183F578E3E71D213E3 /* XCTest.framework */; }; + CCDFB6611155BB0F4831F06A1A8E63C2 /* NSString+Matcheable.m in Sources */ = {isa = PBXBuildFile; fileRef = EC36B20C01662C337AE1E1B9182A9989 /* NSString+Matcheable.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + CD9B0515D509AA0282FFD6B7336C92CB /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4BC8039B74D4913DB1E703B667824C32 /* Foundation.framework */; }; + CDE064156886F92A4E4D64FCFED5772C /* JSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 959709CD9AA3DCA94FEA572CDFCF1BB2 /* JSON.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + CDEDC8DAA0C457292D808100B8B8F60B /* UIViewController+AstroGadgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4D2A6077533A721DD33F24F8F498E62 /* UIViewController+AstroGadgets.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + CFE6E0DA62CC3C0AA51C460558431C28 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = F06A779758B1FCB858DFC3BFB2C04DBC /* Response.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + D017DC2887E3EF5201451BAF25519567 /* ExampleGroup.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16CEA0DF7B1B801C54BACC2F3D36A070 /* ExampleGroup.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + D1FF865FECBBEC7089ACA994F1C0AA48 /* LSStubRequestDSL.m in Sources */ = {isa = PBXBuildFile; fileRef = B20551A59697BD87AB5FDE5C7A0A30B4 /* LSStubRequestDSL.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + D2B3B8A5532F9F084D2855970798CB82 /* LSHTTPClientHook.h in Headers */ = {isa = PBXBuildFile; fileRef = 9773F594CFB512CB7A612BDA2242D868 /* LSHTTPClientHook.h */; settings = {ATTRIBUTES = (Project, ); }; }; + D41F628A81153A978EB209E4FE925700 /* Nimble.h in Headers */ = {isa = PBXBuildFile; fileRef = D1237ED721CA0F3952D47B10622A617E /* Nimble.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D46EE039B0C89E37A1895D5A51F4CEDA /* Freddy.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 41D136DE7AD7FCE83428ECEF04EDC1F7 /* Freddy.framework */; }; + D531E95431F3763DF1ECE65C1954FB34 /* Freddy-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = AFF88D60EB7A5E61E3734F53E9B81D84 /* Freddy-dummy.m */; }; + D679FCA415584395E56144D07AF01DD7 /* JSONSubscripting.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83840C4A29C6F945D5B4BD089A6D603F /* JSONSubscripting.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + D97D6F06A67D170DBF191FDFD82E1410 /* JSONLiteralConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D1D7FA44480B220CEAE13AEECEF15B8 /* JSONLiteralConvertible.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + DBB0527ADF9440FEF442BE39801F8585 /* Quick-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 02E57745B7D20C38D8B99FE50F65C377 /* Quick-dummy.m */; }; + DD8764F9B4466802952AA0ED464DB0EC /* SourceLocation.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC985E6776F0DC8A00AD86967C1FAE73 /* SourceLocation.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + DD8F58A14A5415877CAFE43679DB33D7 /* MatcherFunc.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2C85A809276C7CF7C77A8F526F48948 /* MatcherFunc.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + DE94765732B7FBCD78E56173F4A782ED /* LSStubRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 88606CFF78D8FA2F735FBE083CE15272 /* LSStubRequest.h */; settings = {ATTRIBUTES = (Project, ); }; }; + DFED6A187A8641FD5552C127E3A77AEF /* EndWith.swift in Sources */ = {isa = PBXBuildFile; fileRef = D432E948A3B1245ABDB9E2355EFB85AD /* EndWith.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + E02B058C8A6E0AC405CAF7F54C65852A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4BC8039B74D4913DB1E703B667824C32 /* Foundation.framework */; }; + E07A45CD453CFC98DE69AA370E5780F9 /* NSRegularExpression+Matcheable.h in Headers */ = {isa = PBXBuildFile; fileRef = A383F9C5E5B3240445EC799443DFBE48 /* NSRegularExpression+Matcheable.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E08122859DE3AE6BEA6079C4BA6A758D /* QuickConfiguration.m in Sources */ = {isa = PBXBuildFile; fileRef = AD8BF00170DCE12439E001B878408769 /* QuickConfiguration.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + E3DABC8D10B7297AEEC0DD259EB8BDD8 /* ObjCExpectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC244876ABA22AA03CED8927B2CDF2E5 /* ObjCExpectation.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + E42A03C03AF789E657C8A1D228A725C2 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C529BFE5644828353B7A79D9E41E228 /* ParameterEncoding.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + E5257C3F4110DEEA78306240DEB2333F /* World+DSL.h in Headers */ = {isa = PBXBuildFile; fileRef = 4F026309ABF704D83EB6B37ECC300575 /* World+DSL.h */; settings = {ATTRIBUTES = (Project, ); }; }; + E7CD4D0D590E6491FD61FDB44EA334C2 /* AllPass.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56ED0B19C40FFF7EDD9CAAE9262402CD /* AllPass.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + E864F07E13F0CBB3F691DD8F8580B236 /* Async.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF6998F96251AA400D2CB350EC25BAB9 /* Async.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + E8BE058CC4FF369E6AE3777374AB3A66 /* NimbleXCTestHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA401D928A2174F298834E21A3B2AB12 /* NimbleXCTestHandler.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + E909D0D33037F3C642BBB8D47FC642B3 /* Nimble-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = C4E3EF118161C2D530B2D7F8BA62F259 /* Nimble-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EBE70D5715F0880918FF30B587E617D1 /* Astro-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 1CF059E9D75DEFA1FC51BA89F96FCD54 /* Astro-dummy.m */; }; + EC336944FCF11CEC2C298BFD54B1B863 /* NSData+Matcheable.m in Sources */ = {isa = PBXBuildFile; fileRef = 00C8CC16BD4B806E48B1374B566F4CD9 /* NSData+Matcheable.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0 -w -Xanalyzer -analyzer-disable-all-checks"; }; }; + EDB7BCD432FD07A284C407A4B1F5C0A1 /* World.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EF82508859CC525834813881F6D1B77 /* World.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + EDBD0FB0C34E68F787748DED462CAE6D /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD040DF2D5579CF2DF4A1A521BB6CCEC /* ResponseSerialization.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + F0153EAD01D147292F0DD10A1A61766F /* Queue.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB517BF9DAFFCA1BBCC5A0BBCB5B1A73 /* Queue.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + F2096C950FB8A9662DF8BD15AC7E8BBB /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F90DE596DC3117F88CEE01B3B85B587 /* Configuration.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + F215EE98D2DBCF42218FC69D28500843 /* MatcherProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8204BE5D1FE8224508DE7C846BD1B2A2 /* MatcherProtocols.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + F4FB5ED9614E6F9838BC0037675F5010 /* Pods-AstroTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F1012B82C8E2EB174EC08743BCE9146E /* Pods-AstroTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F51FDBE0B58714B7CCFC263E262B0842 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = D522CC6D5DFC8CDA09D6831C940906B1 /* Alamofire-dummy.m */; }; + F55A763428632B5FD7DC96B3850F3B9F /* RaisesException.swift in Sources */ = {isa = PBXBuildFile; fileRef = 96859D1DF2FBE1631D680809FCE58575 /* RaisesException.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + F5E6CD1CF874ECF35CF44B0AF7FD8005 /* BeLessThanOrEqual.swift in Sources */ = {isa = PBXBuildFile; fileRef = D19CF36C5FE6F4001B9167BA9C8A28A5 /* BeLessThanOrEqual.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + F6299CD7B9C9B0E1D83DF4E3CFA6AA54 /* BeAKindOf.swift in Sources */ = {isa = PBXBuildFile; fileRef = C6F587C4B92886F7BB1A4A2F88D600F3 /* BeAKindOf.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + F76FAD73B802B3FA5D61EB667A79BC83 /* SuiteHooks.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E779502250CE3D994F3080B1989AEF9 /* SuiteHooks.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + FB1EB3B52DD7D60898C88F31CDAC7F67 /* Route.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3DED6207BC66EC19693CBBB8E70F983 /* Route.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + FB921E2C31223EFB30816D7DB741889B /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1BB1B584B2D9EB110E04D032D2FC6353 /* NetworkReachabilityManager.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + FCFC2208684969E5BDF9F439AEE58162 /* NSString+Matcheable.h in Headers */ = {isa = PBXBuildFile; fileRef = 0E1C201B58EAF7F53ED9FDB2DE77D696 /* NSString+Matcheable.h */; settings = {ATTRIBUTES = (Public, ); }; }; + FD31EB5C092198491AFA59C0AA80E33F /* NSString+QCKSelectorName.h in Headers */ = {isa = PBXBuildFile; fileRef = 63DD1B1F48BE14CDD17AC94D8E025D3B /* NSString+QCKSelectorName.h */; settings = {ATTRIBUTES = (Project, ); }; }; + FF15CD2B5E145B3EBE8B00574F5E790D /* _RecursiveLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 59172979F51F694E2A92AF967A65E854 /* _RecursiveLock.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + FFCDEF1F24D714002E543D2F634CC077 /* BeVoid.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD7ADBE040B34288DEF642C059297546 /* BeVoid.swift */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 092F98FBAB35E78D80635DC286DE6135 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = FBC498C9743D0DFCE3F099202D9534DC; + remoteInfo = Astro; + }; + 1C54C7E54A1BE7D68920E9D73B1357A3 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 79C040AFDDCE1BCBF6D8B5EB0B85887F; + remoteInfo = Alamofire; + }; + 28C8609FA1466917DCEC3D46AC819CCD /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 393E0E1A41299C44C63DBB766A243010; + remoteInfo = Nocilla; + }; + 28E66F9C467517BDD111A676DF6BAFB8 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 2DED8F1D97AD7B11107A2DF5C2FEBCD7; + remoteInfo = SwiftTask; + }; + 44EE941BAC2FB6F90477DA65C72BFFED /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 18F2F1BE1B1A39484B66A0C0D41D55C6; + remoteInfo = Freddy; + }; + 4EADF7783FF5A64433DB52605C00B2FD /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 2DED8F1D97AD7B11107A2DF5C2FEBCD7; + remoteInfo = SwiftTask; + }; + 683066C568219244AEA91F2E2AB5065E /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = FF61C7C740C1B196A3B33F37B77DBC68; + remoteInfo = Nimble; + }; + 6C69E40802B58122DBB0A67FBA0169FB /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 79C040AFDDCE1BCBF6D8B5EB0B85887F; + remoteInfo = Alamofire; + }; + 9AC142B18F4D42F065666B4445B18163 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = A806B96D9DEB1A4DB63C09048B2EF00E; + remoteInfo = Quick; + }; + A9887DC134EC0A03A91DF0523BD67FF9 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 18F2F1BE1B1A39484B66A0C0D41D55C6; + remoteInfo = Freddy; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 0014D967034D35F957148B768101D8F4 /* Pods-AstroTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-AstroTests-resources.sh"; sourceTree = ""; }; + 00351519C4E7E45AB67C9AE54E9BC5FF /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 00C8CC16BD4B806E48B1374B566F4CD9 /* NSData+Matcheable.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSData+Matcheable.m"; path = "Nocilla/Matchers/NSData+Matcheable.m"; sourceTree = ""; }; + 018EC0A4904E4B088A5A073E648C19B5 /* BeginWith.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BeginWith.swift; path = Sources/Nimble/Matchers/BeginWith.swift; sourceTree = ""; }; + 01B684422F9A68DB967394EAC091E627 /* DSL.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = DSL.m; path = Sources/Nimble/objc/DSL.m; sourceTree = ""; }; + 02C475E83572D471A01BFD104587CDB7 /* Pods-Astro-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-Astro-resources.sh"; sourceTree = ""; }; + 02E57745B7D20C38D8B99FE50F65C377 /* Quick-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Quick-dummy.m"; sourceTree = ""; }; + 037D5199F69F8288CA074CDE9981C835 /* LSStringMatcher.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSStringMatcher.h; path = Nocilla/Matchers/LSStringMatcher.h; sourceTree = ""; }; + 07D74A91BCFD69C9E1C3F3BBF9CC777B /* AsyncMatcherWrapper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsyncMatcherWrapper.swift; path = Sources/Nimble/Wrappers/AsyncMatcherWrapper.swift; sourceTree = ""; }; + 07DCDEDF9C00CC7D1C61D1D38C722EBD /* Freddy.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Freddy.h; path = Sources/Freddy.h; sourceTree = ""; }; + 08503275A881C4B454DE98666EC4042D /* JSONEncodable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONEncodable.swift; path = Sources/JSONEncodable.swift; sourceTree = ""; }; + 08557293038B060E63351D04FAA3661B /* BeIdenticalTo.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BeIdenticalTo.swift; path = Sources/Nimble/Matchers/BeIdenticalTo.swift; sourceTree = ""; }; + 08EBF5E98850CE0D59CD4790AE4E05A9 /* LSDataMatcher.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSDataMatcher.h; path = Nocilla/Matchers/LSDataMatcher.h; sourceTree = ""; }; + 09369E6621D03C4D8547E467FB8526B3 /* LSNSURLSessionHook.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSNSURLSessionHook.h; path = Nocilla/Hooks/NSURLSession/LSNSURLSessionHook.h; sourceTree = ""; }; + 0979C227E7552D43BEF6C85C5E418766 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 0AB1D855C50B7605DF675B33356E70FF /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + 0E1C201B58EAF7F53ED9FDB2DE77D696 /* NSString+Matcheable.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSString+Matcheable.h"; path = "Nocilla/Matchers/NSString+Matcheable.h"; sourceTree = ""; }; + 0E30C666974AFD8AE1D15D77D6FAE0D4 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 0E5CF2AB8A1768830A16697E65455D4A /* LSHTTPRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSHTTPRequest.h; path = Nocilla/Model/LSHTTPRequest.h; sourceTree = ""; }; + 0FAC898952701B46D5209EBB19206322 /* _Atomic.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = _Atomic.swift; path = SwiftTask/_Atomic.swift; sourceTree = ""; }; + 0FD350C81335B2D7E13DBA6A353DB0A0 /* Astro-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Astro-prefix.pch"; sourceTree = ""; }; + 1640764CAB261E1814B1BA7709848F58 /* Pods-Astro.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Astro.release.xcconfig"; sourceTree = ""; }; + 16CEA0DF7B1B801C54BACC2F3D36A070 /* ExampleGroup.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ExampleGroup.swift; path = Sources/Quick/ExampleGroup.swift; sourceTree = ""; }; + 18894A3E151905AB3BB2BEB1A15E9977 /* Pods-AstroTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-AstroTests.modulemap"; sourceTree = ""; }; + 18EA6F2FCD99D7DD985FCAEA6EC626DC /* SwiftTask-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftTask-umbrella.h"; sourceTree = ""; }; + 19B5EF8C24AF289FEC3DEFDCADC7B12C /* Nocilla-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Nocilla-prefix.pch"; sourceTree = ""; }; + 1B0BC0D43B557E478A7AC87FC68C3B22 /* LSASIHTTPRequestHook.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSASIHTTPRequestHook.h; path = Nocilla/Hooks/ASIHTTPRequest/LSASIHTTPRequestHook.h; sourceTree = ""; }; + 1B6175C0F07945B33BA87785C28C9912 /* Download.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Download.swift; path = Source/Download.swift; sourceTree = ""; }; + 1BB1B584B2D9EB110E04D032D2FC6353 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; + 1BB32E06FD13A42B1754090B64ABA926 /* Nocilla-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Nocilla-dummy.m"; sourceTree = ""; }; + 1C7E74E409C0A0FF82091CE470CC633D /* LSHTTPBody.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSHTTPBody.h; path = Nocilla/Model/LSHTTPBody.h; sourceTree = ""; }; + 1CD70AE2B4CBC113F7A546EC5365B93E /* SwiftTask.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftTask.xcconfig; sourceTree = ""; }; + 1CF059E9D75DEFA1FC51BA89F96FCD54 /* Astro-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Astro-dummy.m"; sourceTree = ""; }; + 1D267E39340A0E1533C5C6BB5559E9FE /* HooksPhase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HooksPhase.swift; path = Sources/Quick/Hooks/HooksPhase.swift; sourceTree = ""; }; + 1D57166DA009DF7F279278E659B83001 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + 1D6A308350139622BAE6ACB0FECD59AA /* Expression.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Expression.swift; path = Sources/Nimble/Expression.swift; sourceTree = ""; }; + 1DA4BC7AA452C12ED8B08E83DB465C62 /* UIView+AstroGadgets.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "UIView+AstroGadgets.swift"; sourceTree = ""; }; + 1DAF602663993CD69CB887EFF206A219 /* World+DSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "World+DSL.swift"; path = "Sources/Quick/DSL/World+DSL.swift"; sourceTree = ""; }; + 1DB921FDEB8F795C32706D42D10E99AD /* Nocilla.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Nocilla.h; path = Nocilla/Nocilla.h; sourceTree = ""; }; + 1FADAF5723E3783E2D2CB736373725B5 /* ExceptionCapture.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ExceptionCapture.swift; path = Sources/Nimble/Utils/ExceptionCapture.swift; sourceTree = ""; }; + 20DECE4687279E305EE363109B2CEAF4 /* ThrowError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ThrowError.swift; path = Sources/Nimble/Matchers/ThrowError.swift; sourceTree = ""; }; + 215B768C828ACF6EDCAD625F7A57F60A /* LSDataMatcher.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LSDataMatcher.m; path = Nocilla/Matchers/LSDataMatcher.m; sourceTree = ""; }; + 21E6E306A222BB7B4910F4381D552E4A /* ASIHTTPRequestStub.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = ASIHTTPRequestStub.m; path = Nocilla/Hooks/ASIHTTPRequest/ASIHTTPRequestStub.m; sourceTree = ""; }; + 246E55C5423DE0296BF8B2E2283F8451 /* FailureMessage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FailureMessage.swift; path = Sources/Nimble/FailureMessage.swift; sourceTree = ""; }; + 24EB686A9187237EC0D542A4A26881AF /* LSStubRequestDSL.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSStubRequestDSL.h; path = Nocilla/DSL/LSStubRequestDSL.h; sourceTree = ""; }; + 25A9215971B7F9942A388AFF5A7F225C /* QuickSpec.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = QuickSpec.h; path = Sources/Quick/QuickSpec.h; sourceTree = ""; }; + 2674300CB730134EDCAD3694E9665CB1 /* BeLessThan.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BeLessThan.swift; path = Sources/Nimble/Matchers/BeLessThan.swift; sourceTree = ""; }; + 2B210588090C1A8615A7263069ACF6F9 /* ErrorUtility.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ErrorUtility.swift; path = Sources/Quick/ErrorUtility.swift; sourceTree = ""; }; + 2B34E178970B70AF83F2D0104154B4C6 /* NSData+Nocilla.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSData+Nocilla.m"; path = "Nocilla/Categories/NSData+Nocilla.m"; sourceTree = ""; }; + 2B3E454647835A4B7F4C78D3958A9F1A /* NSURLRequest+LSHTTPRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSURLRequest+LSHTTPRequest.m"; path = "Nocilla/Hooks/NSURLRequest/NSURLRequest+LSHTTPRequest.m"; sourceTree = ""; }; + 2C6D3290D1DBF2130A57A59FDF56617D /* LSHTTPRequestDSLRepresentation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSHTTPRequestDSLRepresentation.h; path = Nocilla/DSL/LSHTTPRequestDSLRepresentation.h; sourceTree = ""; }; + 2D8D24CBFA077EE8C5F66870B269186B /* QuickSpec.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = QuickSpec.m; path = Sources/Quick/QuickSpec.m; sourceTree = ""; }; + 2E71D1C2D2314E373416420A365F7368 /* Pods-AstroTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-AstroTests-acknowledgements.plist"; sourceTree = ""; }; + 2E84C95072B0D268B49E3983BA78D64F /* LSHTTPRequestDiff.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LSHTTPRequestDiff.m; path = Nocilla/Diff/LSHTTPRequestDiff.m; sourceTree = ""; }; + 32930ABA04829C715E9309828367451B /* NimbleEnvironment.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NimbleEnvironment.swift; path = Sources/Nimble/Adapters/NimbleEnvironment.swift; sourceTree = ""; }; + 3375C76C22C797C8327948D959CE686D /* ExampleMetadata.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ExampleMetadata.swift; path = Sources/Quick/ExampleMetadata.swift; sourceTree = ""; }; + 355843C6E194A70E0B6A53BB4ED12699 /* JSONParsing.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONParsing.swift; path = Sources/JSONParsing.swift; sourceTree = ""; }; + 376A62A3AEF587E01593F5D415550697 /* Nocilla-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Nocilla-umbrella.h"; sourceTree = ""; }; + 37AE78B97CFBB07F50E06240AB090DF5 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 38C7DFE274B7201CF938B4C39C143127 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; + 3A53526BFF3C6D5B366DA4066B49DD74 /* Pods-Astro.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-Astro.modulemap"; sourceTree = ""; }; + 3C7DE601C7FCC67C58CFF4B7F6509262 /* PostNotification.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PostNotification.swift; path = Sources/Nimble/Matchers/PostNotification.swift; sourceTree = ""; }; + 3C8AF1FA9140A19391F57B93E8FBEAC4 /* QCKDSL.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = QCKDSL.h; path = Sources/Quick/DSL/QCKDSL.h; sourceTree = ""; }; + 3E779502250CE3D994F3080B1989AEF9 /* SuiteHooks.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SuiteHooks.swift; path = Sources/Quick/Hooks/SuiteHooks.swift; sourceTree = ""; }; + 3F91823DE328E0C3D6BDE74B168C5414 /* String+FileName.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+FileName.swift"; path = "Sources/Quick/String+FileName.swift"; sourceTree = ""; }; + 4046EBF9B062ED9B23FAB96D07561CA0 /* Pods-Astro-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-Astro-umbrella.h"; sourceTree = ""; }; + 40766F0C467159B985AA2723FF099609 /* Log.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Log.swift; sourceTree = ""; }; + 410C6A2BACECF4513F82EA7EBC0D1BFB /* Pods-Astro-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Astro-acknowledgements.plist"; sourceTree = ""; }; + 41D136DE7AD7FCE83428ECEF04EDC1F7 /* Freddy.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Freddy.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 44538300F5802FC65969BBF566DFB619 /* BeEmpty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BeEmpty.swift; path = Sources/Nimble/Matchers/BeEmpty.swift; sourceTree = ""; }; + 45BF6CC47BA8AE2AE5510EA0CBD7D844 /* Freddy-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Freddy-prefix.pch"; sourceTree = ""; }; + 46ED4872452785F7C1ADB1AEC089FFEB /* Quick-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Quick-prefix.pch"; sourceTree = ""; }; + 46F5790BDF2B23727CBEED623FA4B790 /* Quick.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Quick.h; path = Sources/Quick/Quick.h; sourceTree = ""; }; + 478795D7B64F9DBB6E9B622BAF78A351 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 486AD68885FD024FAA1DE18E7B99E032 /* LSStubResponseDSL.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSStubResponseDSL.h; path = Nocilla/DSL/LSStubResponseDSL.h; sourceTree = ""; }; + 48BE2756E789DA180A9EE1D5BE1874A4 /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = ""; }; + 49E1B592BED6BB90BB6F2F89FA3E989E /* BeNil.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BeNil.swift; path = Sources/Nimble/Matchers/BeNil.swift; sourceTree = ""; }; + 4B41E2C6F9BDDB8E500A76ACD24DC2A6 /* Pods-AstroTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-AstroTests.release.xcconfig"; sourceTree = ""; }; + 4BC8039B74D4913DB1E703B667824C32 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 4BCE60758BD208F904264B1F4A110801 /* AssertionDispatcher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AssertionDispatcher.swift; path = Sources/Nimble/Adapters/AssertionDispatcher.swift; sourceTree = ""; }; + 4F026309ABF704D83EB6B37ECC300575 /* World+DSL.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "World+DSL.h"; path = "Sources/Quick/DSL/World+DSL.h"; sourceTree = ""; }; + 4F9C1070A7DA056DC96366DD7AB5D032 /* KeychainAccess.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = KeychainAccess.swift; sourceTree = ""; }; + 50C0E4DFCA69C34F7ABBBA680A7BB9AD /* Freddy.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Freddy.modulemap; sourceTree = ""; }; + 5130E6C4B0648E65F27B4B60E917F4D9 /* Astro.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Astro.modulemap; sourceTree = ""; }; + 556FA88DC471542F2CB2B5EB084A211A /* AdapterProtocols.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AdapterProtocols.swift; path = Sources/Nimble/Adapters/AdapterProtocols.swift; sourceTree = ""; }; + 561DCE42AA14EE97B88C05205E6B2FFD /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 56ED0B19C40FFF7EDD9CAAE9262402CD /* AllPass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AllPass.swift; path = Sources/Nimble/Matchers/AllPass.swift; sourceTree = ""; }; + 57BCDA3FA7A78B29FC1010111712059F /* LSNSURLHook.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LSNSURLHook.m; path = Nocilla/Hooks/NSURLRequest/LSNSURLHook.m; sourceTree = ""; }; + 580685080BA8A710801E892C91D930A0 /* Stringers.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stringers.swift; path = Sources/Nimble/Utils/Stringers.swift; sourceTree = ""; }; + 59172979F51F694E2A92AF967A65E854 /* _RecursiveLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = _RecursiveLock.swift; path = SwiftTask/_RecursiveLock.swift; sourceTree = ""; }; + 5964854B7B2C56E2165DC9FA19616273 /* Quick.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Quick.modulemap; sourceTree = ""; }; + 5A1C175C7A891D63E146044DF96BD727 /* LSNocilla.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LSNocilla.m; path = Nocilla/LSNocilla.m; sourceTree = ""; }; + 5A70FC1773E4B74A1B01208EEB34131B /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + 5B700373BAD98857FB8B7D43320BAE6E /* LSASIHTTPRequestAdapter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSASIHTTPRequestAdapter.h; path = Nocilla/Hooks/ASIHTTPRequest/LSASIHTTPRequestAdapter.h; sourceTree = ""; }; + 5B9479BA6CA341455D32AC3F2A470434 /* Pods-AstroTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-AstroTests-frameworks.sh"; sourceTree = ""; }; + 5B9DDD2E2D087DE41FE10BBE3FB84940 /* NSBundle+CurrentTestBundle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSBundle+CurrentTestBundle.swift"; path = "Sources/Quick/NSBundle+CurrentTestBundle.swift"; sourceTree = ""; }; + 5C529BFE5644828353B7A79D9E41E228 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + 5C73A1245CDA974F563837D844547617 /* CurrentTestCaseTracker.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = CurrentTestCaseTracker.m; path = Sources/Nimble/objc/CurrentTestCaseTracker.m; sourceTree = ""; }; + 5CB1530548D1D9E85E0CA807FE68F4B5 /* Pods-AstroTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-AstroTests-dummy.m"; sourceTree = ""; }; + 5E7BB1DBF75BF7FD15FA74553EF663EF /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 5F08970D8469F6AC8EFF70AEF946205D /* Nimble.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Nimble.xcconfig; sourceTree = ""; }; + 6205D5C0FB3D9036F177DEBF76CD96BC /* LSMatcher.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LSMatcher.m; path = Nocilla/Matchers/LSMatcher.m; sourceTree = ""; }; + 62A18C9C05326332D45658DF26A5DC52 /* LSMatcher.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSMatcher.h; path = Nocilla/Matchers/LSMatcher.h; sourceTree = ""; }; + 6360E2524B77978580F6B83A3067E9B3 /* LSRegexMatcher.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSRegexMatcher.h; path = Nocilla/Matchers/LSRegexMatcher.h; sourceTree = ""; }; + 63DD1B1F48BE14CDD17AC94D8E025D3B /* NSString+QCKSelectorName.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSString+QCKSelectorName.h"; path = "Sources/Quick/NSString+QCKSelectorName.h"; sourceTree = ""; }; + 666499CBBC4996DE397CA1CCF1689947 /* LSHTTPResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSHTTPResponse.h; path = Nocilla/Model/LSHTTPResponse.h; sourceTree = ""; }; + 66CC9B801997F61B96C5719193CA636D /* NSURLRequest+LSHTTPRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSURLRequest+LSHTTPRequest.h"; path = "Nocilla/Hooks/NSURLRequest/NSURLRequest+LSHTTPRequest.h"; sourceTree = ""; }; + 6802180060568B48E5AA39180D643845 /* Pods-Astro.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Astro.debug.xcconfig"; sourceTree = ""; }; + 6A48017A94FCEF5694E75BD283E6D2C4 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 6ACE15C16D148D217BDB20FFEFFCF02F /* DSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DSL.swift; path = Sources/Nimble/DSL.swift; sourceTree = ""; }; + 6B8987186092FEE2E6BFB40BB4C40B82 /* Nimble.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Nimble.modulemap; sourceTree = ""; }; + 6B93B92F0117AC91DA973DD6FA708339 /* DSL.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = DSL.h; path = Sources/Nimble/objc/DSL.h; sourceTree = ""; }; + 6BCA294AF3615B183F578E3E71D213E3 /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = XCTest.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/XCTest.framework; sourceTree = DEVELOPER_DIR; }; + 6CA7B27079A3AE437FFB717B6CEB7766 /* Pods-Astro-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-Astro-dummy.m"; sourceTree = ""; }; + 6E203099AEBFA89BB26866928B47B729 /* Match.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Match.swift; path = Sources/Nimble/Matchers/Match.swift; sourceTree = ""; }; + 6F3C0C399D268AA91831AE634921FDF4 /* Expectation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Expectation.swift; path = Sources/Nimble/Expectation.swift; sourceTree = ""; }; + 6FCBC236F707B2863121FD75A2B783A7 /* Nocilla.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Nocilla.xcconfig; sourceTree = ""; }; + 70D64846E5ED48505B235794D511C710 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + 718746D488FF4E2AEB19CEAEFC5596A1 /* SwiftTask.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SwiftTask.h; path = SwiftTask/SwiftTask.h; sourceTree = ""; }; + 73D4F264A8ACC108D2139D0C740EE235 /* Nimble-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Nimble-dummy.m"; sourceTree = ""; }; + 740A1225FBB93D00E7780C9248E24F10 /* LSNocilla.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSNocilla.h; path = Nocilla/LSNocilla.h; sourceTree = ""; }; + 748EA67BCFF48DE8E76C6F13965EE8E6 /* Astro.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Astro.xcconfig; sourceTree = ""; }; + 76152E950AB1F0ECD2EA3B0B2D380365 /* Closures.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Closures.swift; path = Sources/Quick/Hooks/Closures.swift; sourceTree = ""; }; + 764D3566600AF08BE9E045AD225DDE34 /* DSL.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DSL.swift; path = Sources/Quick/DSL/DSL.swift; sourceTree = ""; }; + 79BCBBE911B763D6036063E7D32BF5D0 /* Pods_Astro.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Astro.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 7A4A3ECEB9A900D640EF1635D4313478 /* Quick.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Quick.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 7AB33573A133A91BFBE2D06A0EEA0ADF /* HTTPStatusCode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HTTPStatusCode.swift; sourceTree = ""; }; + 7AE15AE95C7899FDFDF008072E2A12D8 /* SwiftTask-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SwiftTask-dummy.m"; sourceTree = ""; }; + 7F90DE596DC3117F88CEE01B3B85B587 /* Configuration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Configuration.swift; path = Sources/Quick/Configuration/Configuration.swift; sourceTree = ""; }; + 7FB7DEAF15D7E7DDE899E9D09569708F /* BeCloseTo.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BeCloseTo.swift; path = Sources/Nimble/Matchers/BeCloseTo.swift; sourceTree = ""; }; + 7FD0E7B25D8D24C9A657D2405566EC54 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + 8204BE5D1FE8224508DE7C846BD1B2A2 /* MatcherProtocols.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MatcherProtocols.swift; path = Sources/Nimble/Matchers/MatcherProtocols.swift; sourceTree = ""; }; + 83840C4A29C6F945D5B4BD089A6D603F /* JSONSubscripting.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONSubscripting.swift; path = Sources/JSONSubscripting.swift; sourceTree = ""; }; + 850C70E03DB4FE8DE70A33C20FA18FDE /* QuickConfiguration.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = QuickConfiguration.h; path = Sources/Quick/Configuration/QuickConfiguration.h; sourceTree = ""; }; + 85F553423E820BBA7AFF070E59F8F811 /* JSONSerializing.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONSerializing.swift; path = Sources/JSONSerializing.swift; sourceTree = ""; }; + 88606CFF78D8FA2F735FBE083CE15272 /* LSStubRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSStubRequest.h; path = Nocilla/Stubs/LSStubRequest.h; sourceTree = ""; }; + 89733119C7341F88D957D4C16F746E25 /* Filter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Filter.swift; path = Sources/Quick/Filter.swift; sourceTree = ""; }; + 89F15E9D033FC5A11A4ACE1741A56934 /* JSONEncodingDetector.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONEncodingDetector.swift; path = Sources/JSONEncodingDetector.swift; sourceTree = ""; }; + 8A08012C92D3BEB87C3BAF924DF17BA0 /* NSData+Nocilla.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSData+Nocilla.h"; path = "Nocilla/Categories/NSData+Nocilla.h"; sourceTree = ""; }; + 8A50386EDB40911FEABEAED0E4BB975B /* LSStubResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSStubResponse.h; path = Nocilla/Stubs/LSStubResponse.h; sourceTree = ""; }; + 8AEC080634ED245BCD85C53126EE83FC /* LSHTTPStubURLProtocol.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSHTTPStubURLProtocol.h; path = Nocilla/Hooks/NSURLRequest/LSHTTPStubURLProtocol.h; sourceTree = ""; }; + 8E019C411893B8E5CC125BDB3D9C356B /* LSNSURLSessionHook.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LSNSURLSessionHook.m; path = Nocilla/Hooks/NSURLSession/LSNSURLSessionHook.m; sourceTree = ""; }; + 8EF82508859CC525834813881F6D1B77 /* World.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = World.swift; path = Sources/Quick/World.swift; sourceTree = ""; }; + 90C80D0F88F467734DCA9AB2BD6754E5 /* LayoutLabel.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LayoutLabel.swift; sourceTree = ""; }; + 933EED4371DBCE2167B600FC06C24228 /* LSStubRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LSStubRequest.m; path = Nocilla/Stubs/LSStubRequest.m; sourceTree = ""; }; + 935CB3CC8195F22FBF8955E2FD8A07BB /* LSHTTPStubURLProtocol.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LSHTTPStubURLProtocol.m; path = Nocilla/Hooks/NSURLRequest/LSHTTPStubURLProtocol.m; sourceTree = ""; }; + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 959709CD9AA3DCA94FEA572CDFCF1BB2 /* JSON.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSON.swift; path = Sources/JSON.swift; sourceTree = ""; }; + 96859D1DF2FBE1631D680809FCE58575 /* RaisesException.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RaisesException.swift; path = Sources/Nimble/Matchers/RaisesException.swift; sourceTree = ""; }; + 975DEA98C31CF3D29E771F478017AFED /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 9773F594CFB512CB7A612BDA2242D868 /* LSHTTPClientHook.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSHTTPClientHook.h; path = Nocilla/Hooks/LSHTTPClientHook.h; sourceTree = ""; }; + 978B87B6A0E09CFE16BB8AFDF35C7524 /* Astro.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Astro.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 99BA98371CC71CBBD02B1C626F309DCD /* LSHTTPRequestDiff.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSHTTPRequestDiff.h; path = Nocilla/Diff/LSHTTPRequestDiff.h; sourceTree = ""; }; + 9AA1D1F085FBA836D99BB30907F537F7 /* Pods-Astro-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-Astro-frameworks.sh"; sourceTree = ""; }; + 9D1D7FA44480B220CEAE13AEECEF15B8 /* JSONLiteralConvertible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONLiteralConvertible.swift; path = Sources/JSONLiteralConvertible.swift; sourceTree = ""; }; + 9F5C636F6C5EA27DBCB9C6C3CA680826 /* Freddy.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Freddy.xcconfig; sourceTree = ""; }; + A2C85A809276C7CF7C77A8F526F48948 /* MatcherFunc.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MatcherFunc.swift; path = Sources/Nimble/Wrappers/MatcherFunc.swift; sourceTree = ""; }; + A35FF701553483D20C02D7FBAF1B8855 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + A383F9C5E5B3240445EC799443DFBE48 /* NSRegularExpression+Matcheable.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSRegularExpression+Matcheable.h"; path = "Nocilla/Matchers/NSRegularExpression+Matcheable.h"; sourceTree = ""; }; + A45861F28898647557DF322055128938 /* Quick-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Quick-umbrella.h"; sourceTree = ""; }; + A4D2A6077533A721DD33F24F8F498E62 /* UIViewController+AstroGadgets.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "UIViewController+AstroGadgets.swift"; sourceTree = ""; }; + A52A75DB7A7E8D5ABD5E0A8677F3C487 /* UIColor+AstroGadgets.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "UIColor+AstroGadgets.swift"; sourceTree = ""; }; + A5FB155AAF1F83A98BD9205C317F51C6 /* SwiftTask.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwiftTask.swift; path = SwiftTask/SwiftTask.swift; sourceTree = ""; }; + A76279FC16BEF9EAD9C89D44AD1CA184 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A7A349A616F16796BBF0F5C63AD4A0D1 /* JSONDecodable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONDecodable.swift; path = Sources/JSONDecodable.swift; sourceTree = ""; }; + A87B16568F2E92E55610317821E0FECE /* Nocilla.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Nocilla.modulemap; sourceTree = ""; }; + A9ECE62FAB6CC87EAE56E9EC7C2533EB /* LSStubResponseDSL.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LSStubResponseDSL.m; path = Nocilla/DSL/LSStubResponseDSL.m; sourceTree = ""; }; + AA19CB4E19DEAE4E69AE7CEF7A4BB65A /* Nimble-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Nimble-prefix.pch"; sourceTree = ""; }; + AB051FCF80CC7C2B73C825DBEF35252A /* LSNSURLHook.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSNSURLHook.h; path = Nocilla/Hooks/NSURLRequest/LSNSURLHook.h; sourceTree = ""; }; + AB517BF9DAFFCA1BBCC5A0BBCB5B1A73 /* Queue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Queue.swift; sourceTree = ""; }; + AC985E6776F0DC8A00AD86967C1FAE73 /* SourceLocation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SourceLocation.swift; path = Sources/Nimble/Utils/SourceLocation.swift; sourceTree = ""; }; + AD7D87EC77CCE2F8C0B6D5BD0C78F808 /* Astro-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Astro-umbrella.h"; sourceTree = ""; }; + AD8BF00170DCE12439E001B878408769 /* QuickConfiguration.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = QuickConfiguration.m; path = Sources/Quick/Configuration/QuickConfiguration.m; sourceTree = ""; }; + AF89FEF1C7D784E5CAB83C46017149C3 /* NSString+Nocilla.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSString+Nocilla.h"; path = "Nocilla/Categories/NSString+Nocilla.h"; sourceTree = ""; }; + AF9CB0DF1DAF7BC0001D68009B77DAEC /* QCKDSL.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = QCKDSL.m; path = Sources/Quick/DSL/QCKDSL.m; sourceTree = ""; }; + AFF88D60EB7A5E61E3734F53E9B81D84 /* Freddy-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Freddy-dummy.m"; sourceTree = ""; }; + B118A954E3CE6751BEDDA7A3621C8B1B /* SatisfyAnyOf.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SatisfyAnyOf.swift; path = Sources/Nimble/Matchers/SatisfyAnyOf.swift; sourceTree = ""; }; + B1E27637BAEF011157068373797A74D3 /* JSONParser.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONParser.swift; path = Sources/JSONParser.swift; sourceTree = ""; }; + B20551A59697BD87AB5FDE5C7A0A30B4 /* LSStubRequestDSL.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LSStubRequestDSL.m; path = Nocilla/DSL/LSStubRequestDSL.m; sourceTree = ""; }; + B24FBEF8AB502215F26A19C54552E53D /* NSData+Matcheable.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSData+Matcheable.h"; path = "Nocilla/Matchers/NSData+Matcheable.h"; sourceTree = ""; }; + B360270783ED44EAB36B632CDA94A249 /* NSString+QCKSelectorName.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSString+QCKSelectorName.m"; path = "Sources/Quick/NSString+QCKSelectorName.m"; sourceTree = ""; }; + B3C64DCAF1544AC0A8D47DE543C5DFD7 /* XCTestSuite+QuickTestSuiteBuilder.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "XCTestSuite+QuickTestSuiteBuilder.m"; path = "Sources/Quick/XCTestSuite+QuickTestSuiteBuilder.m"; sourceTree = ""; }; + B3DED6207BC66EC19693CBBB8E70F983 /* Route.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Route.swift; sourceTree = ""; }; + B53C5ACBAE69917D3C14246F861DF751 /* Contain.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Contain.swift; path = Sources/Nimble/Matchers/Contain.swift; sourceTree = ""; }; + B79754ADC53CA9E03EA5250AAF1BD4FF /* World.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = World.h; path = Sources/Quick/World.h; sourceTree = ""; }; + BA3DC2ADF554F5AA1C3D8026782FCDD6 /* Nocilla.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Nocilla.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + BC2B2BF86C08224CC0CA71E6FFEB075B /* BeGreaterThanOrEqualTo.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BeGreaterThanOrEqualTo.swift; path = Sources/Nimble/Matchers/BeGreaterThanOrEqualTo.swift; sourceTree = ""; }; + BD10223C5A57996E0DFA3EEA8DF3A111 /* SwiftTask.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = SwiftTask.modulemap; sourceTree = ""; }; + BD7ADBE040B34288DEF642C059297546 /* BeVoid.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BeVoid.swift; path = Sources/Nimble/Matchers/BeVoid.swift; sourceTree = ""; }; + BDCD7A584251A05E7546A8C30B112AD0 /* LSRegexMatcher.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LSRegexMatcher.m; path = Nocilla/Matchers/LSRegexMatcher.m; sourceTree = ""; }; + BE1DED67D6DF1F164F02F3F1476DFA5A /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Source/Error.swift; sourceTree = ""; }; + BE61F544EA1DEB7394D1DB26182F1849 /* Equal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Equal.swift; path = Sources/Nimble/Matchers/Equal.swift; sourceTree = ""; }; + BEF4A9B34EFBF0E5660D27C57A2C9605 /* LSMatcheable.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LSMatcheable.h; path = Nocilla/Matchers/LSMatcheable.h; sourceTree = ""; }; + C2A80AABF30E3F90F8BE459718464BF9 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + C38CF09F3C3B8CF308264F6D6E482788 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + C3BBBE6BD192BF863A94377B37488914 /* LSASIHTTPRequestHook.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LSASIHTTPRequestHook.m; path = Nocilla/Hooks/ASIHTTPRequest/LSASIHTTPRequestHook.m; sourceTree = ""; }; + C4A303959AA23940B44A630C103DD53B /* SwiftTask.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftTask.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + C4E3EF118161C2D530B2D7F8BA62F259 /* Nimble-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Nimble-umbrella.h"; sourceTree = ""; }; + C58B78530AECACCE9C0F19AA30F62370 /* Quick.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Quick.xcconfig; sourceTree = ""; }; + C6F587C4B92886F7BB1A4A2F88D600F3 /* BeAKindOf.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BeAKindOf.swift; path = Sources/Nimble/Matchers/BeAKindOf.swift; sourceTree = ""; }; + C92A12C07271BFC6F6C83EDC7DC1F6C7 /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; + C9DEBF825D7E53BF5C8D0F265A9A1AE5 /* NMBExceptionCapture.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = NMBExceptionCapture.h; path = Sources/Nimble/objc/NMBExceptionCapture.h; sourceTree = ""; }; + CA7F9F2D3BC0D743DB62F65F771E6E96 /* LSStubResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LSStubResponse.m; path = Nocilla/Stubs/LSStubResponse.m; sourceTree = ""; }; + CAB0BDFFF1C8029048D89A3BF0057285 /* NMBExceptionCapture.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = NMBExceptionCapture.m; path = Sources/Nimble/objc/NMBExceptionCapture.m; sourceTree = ""; }; + CB1A413A673529FE4EA52BC8ADD3F528 /* Callsite.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Callsite.swift; path = Sources/Quick/Callsite.swift; sourceTree = ""; }; + CB748F8E3291D161137C48DABBCDBE4D /* Example.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Example.swift; path = Sources/Quick/Example.swift; sourceTree = ""; }; + CD040DF2D5579CF2DF4A1A521BB6CCEC /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + CD81E565DFBCD23784D4A379ADF1815F /* NSURLRequest+DSL.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSURLRequest+DSL.h"; path = "Nocilla/Hooks/NSURLRequest/NSURLRequest+DSL.h"; sourceTree = ""; }; + D1237ED721CA0F3952D47B10622A617E /* Nimble.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Nimble.h; path = Sources/Nimble/Nimble.h; sourceTree = ""; }; + D19CF36C5FE6F4001B9167BA9C8A28A5 /* BeLessThanOrEqual.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BeLessThanOrEqual.swift; path = Sources/Nimble/Matchers/BeLessThanOrEqual.swift; sourceTree = ""; }; + D1F318A61A9ABA6904BC70BCB14E8965 /* Freddy.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Freddy.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + D432E948A3B1245ABDB9E2355EFB85AD /* EndWith.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EndWith.swift; path = Sources/Nimble/Matchers/EndWith.swift; sourceTree = ""; }; + D4B872C6EE9A742550A25D71A7BEAC5C /* Cancellable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cancellable.swift; path = SwiftTask/Cancellable.swift; sourceTree = ""; }; + D522CC6D5DFC8CDA09D6831C940906B1 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + D61DFEA183AEE286758C8B5617777825 /* NSRegularExpression+Matcheable.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSRegularExpression+Matcheable.m"; path = "Nocilla/Matchers/NSRegularExpression+Matcheable.m"; sourceTree = ""; }; + D97CC484A2DBEFEC771C1025EBC41CCE /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; + DA401D928A2174F298834E21A3B2AB12 /* NimbleXCTestHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NimbleXCTestHandler.swift; path = Sources/Nimble/Adapters/NimbleXCTestHandler.swift; sourceTree = ""; }; + DB8028483A380281298717B363ED326E /* BeGreaterThan.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BeGreaterThan.swift; path = Sources/Nimble/Matchers/BeGreaterThan.swift; sourceTree = ""; }; + DC244876ABA22AA03CED8927B2CDF2E5 /* ObjCExpectation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObjCExpectation.swift; path = Sources/Nimble/ObjCExpectation.swift; sourceTree = ""; }; + DD33E17A1452351E0F9E09CD13FDC6B8 /* Stream.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stream.swift; path = Source/Stream.swift; sourceTree = ""; }; + DF6998F96251AA400D2CB350EC25BAB9 /* Async.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Async.swift; path = Sources/Nimble/Utils/Async.swift; sourceTree = ""; }; + DFC4284902E1C186D4B5C7BBFCD91B84 /* ObjCMatcher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObjCMatcher.swift; path = Sources/Nimble/Wrappers/ObjCMatcher.swift; sourceTree = ""; }; + E019BD16B087EDC3E10B12C2D5466294 /* QuickSelectedTestSuiteBuilder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = QuickSelectedTestSuiteBuilder.swift; path = Sources/Quick/QuickSelectedTestSuiteBuilder.swift; sourceTree = ""; }; + E0F3F1404956E871D7ECA60C378BAA60 /* Freddy-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Freddy-umbrella.h"; sourceTree = ""; }; + E14458DC858BFCB6F9E80CBC95A1DE10 /* NSString+Nocilla.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSString+Nocilla.m"; path = "Nocilla/Categories/NSString+Nocilla.m"; sourceTree = ""; }; + E21EAC014ECB332659AE5CE74500EC21 /* Functional.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Functional.swift; path = Sources/Nimble/Utils/Functional.swift; sourceTree = ""; }; + E2993F8A9771156E121C62FFBEBBEB2D /* LSStringMatcher.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LSStringMatcher.m; path = Nocilla/Matchers/LSStringMatcher.m; sourceTree = ""; }; + E4B423AF51FEE630622404ABCA692786 /* QuickTestSuite.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = QuickTestSuite.swift; path = Sources/Quick/QuickTestSuite.swift; sourceTree = ""; }; + E4D54383DE9F48DD36B48F77E57BF01E /* CFNetwork.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/CFNetwork.framework; sourceTree = DEVELOPER_DIR; }; + E6CF0B57AF80A3163EEA409C7757D730 /* SwiftTask-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftTask-prefix.pch"; sourceTree = ""; }; + E8A6B56079D4CA08CE38423A96EEF85B /* _StateMachine.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = _StateMachine.swift; path = SwiftTask/_StateMachine.swift; sourceTree = ""; }; + E95A97D962711156B3B673A517C02090 /* Pods-Astro-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-Astro-acknowledgements.markdown"; sourceTree = ""; }; + E99A028ACF5FC3336D388BD40CF620DB /* Manager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Manager.swift; path = Source/Manager.swift; sourceTree = ""; }; + E9D00D8B2A0D78B2B486894AD785D781 /* Pods-AstroTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-AstroTests-acknowledgements.markdown"; sourceTree = ""; }; + EC36B20C01662C337AE1E1B9182A9989 /* NSString+Matcheable.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSString+Matcheable.m"; path = "Nocilla/Matchers/NSString+Matcheable.m"; sourceTree = ""; }; + EC64FABB231B2528B5FD76A4AC394DB5 /* BeLogical.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BeLogical.swift; path = Sources/Nimble/Matchers/BeLogical.swift; sourceTree = ""; }; + ED9D4484D8A9B8DCBFDDE991EC024DD0 /* BeAnInstanceOf.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BeAnInstanceOf.swift; path = Sources/Nimble/Matchers/BeAnInstanceOf.swift; sourceTree = ""; }; + EDFD96BF70CDC200784A60185BE056A8 /* HaveCount.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HaveCount.swift; path = Sources/Nimble/Matchers/HaveCount.swift; sourceTree = ""; }; + EE5E7EF01AC1AFCC9C8519CE17A4B669 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + EEBD54710A06AEF2A841D76C5D103DCA /* LSHTTPRequestDSLRepresentation.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LSHTTPRequestDSLRepresentation.m; path = Nocilla/DSL/LSHTTPRequestDSLRepresentation.m; sourceTree = ""; }; + EFA45F884E74D416A2CB94D83F76A11A /* NSURLRequest+DSL.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSURLRequest+DSL.m"; path = "Nocilla/Hooks/NSURLRequest/NSURLRequest+DSL.m"; sourceTree = ""; }; + F06A779758B1FCB858DFC3BFB2C04DBC /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + F1012B82C8E2EB174EC08743BCE9146E /* Pods-AstroTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-AstroTests-umbrella.h"; sourceTree = ""; }; + F1CDA5C29F4226AB151CCB0A717465AA /* ASIHTTPRequestStub.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ASIHTTPRequestStub.h; path = Nocilla/Hooks/ASIHTTPRequest/ASIHTTPRequestStub.h; sourceTree = ""; }; + F511D0AF6267ABF4691C1EDE99FB659D /* EnumCountable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = EnumCountable.swift; sourceTree = ""; }; + F598CC4E191ADFF7C8DF93B4B9A22F13 /* LSASIHTTPRequestAdapter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LSASIHTTPRequestAdapter.m; path = Nocilla/Hooks/ASIHTTPRequest/LSASIHTTPRequestAdapter.m; sourceTree = ""; }; + F63DCD4CFAFE4F7967822B5A4D971100 /* Pods-AstroTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-AstroTests.debug.xcconfig"; sourceTree = ""; }; + F813B762FD46FFE133BE08FBA25199EF /* LSHTTPClientHook.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LSHTTPClientHook.m; path = Nocilla/Hooks/LSHTTPClientHook.m; sourceTree = ""; }; + F897256CD08EAEADC4CF349C4A56D98D /* DSL+Wait.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DSL+Wait.swift"; path = "Sources/Nimble/DSL+Wait.swift"; sourceTree = ""; }; + F89A3E458EC43DC935269FB7DD771D86 /* Pods_AstroTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_AstroTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + FBBBDB2DA9151DCA301BF0A6E773F9FF /* NetworkService.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = NetworkService.swift; sourceTree = ""; }; + FC549157357F78725756BA1D794D8956 /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + FC772B3FDB7176368B55A892D4C5226C /* ExampleHooks.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ExampleHooks.swift; path = Sources/Quick/Hooks/ExampleHooks.swift; sourceTree = ""; }; + FCE3C6A2429004B3D14090204CC6CC53 /* Nimble.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Nimble.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + FDE84FF0D7B9663C062BD966122BCA44 /* SwiftTask.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftTask.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + FF14E7E64D23B07812BAF0C10D193605 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + FFA756C9D950245A5366DD0A0EC267EC /* AssertionRecorder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AssertionRecorder.swift; path = Sources/Nimble/Adapters/AssertionRecorder.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 1CFB8EC27F7DFF390441337C21B67AB8 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 7B58011958B21BE947D3AB53CC88EAEC /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 21B8AC554E0DA6E686465542DD732B35 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 73000FB0D08D09BCAFF0052F746E2749 /* Foundation.framework in Frameworks */, + CAFBD098436FD07E8838B47730DCF021 /* XCTest.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5F40817F9BD61376555E224A54C77911 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 21B9BDF15D08F33883999509AC98847C /* CFNetwork.framework in Frameworks */, + 80C451D6026B1C2BF6EF917B4F5BF98B /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9DAB5651A4C32B38474F4CEFFEDE40AD /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + CD9B0515D509AA0282FFD6B7336C92CB /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B1729F851F648EC60EE93CDB3C8BAEAD /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 91C09AC2A52ED69A27C8D923139A006F /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BAECFED1DCB8D9AD70B0EC59A43164F3 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + BFA5019B45418DEBAD3D0BE9E85609E5 /* Alamofire.framework in Frameworks */, + BAA7AFC5CBADB79878E29A8A77903260 /* Foundation.framework in Frameworks */, + D46EE039B0C89E37A1895D5A51F4CEDA /* Freddy.framework in Frameworks */, + 57F4598D24E6102AC980D15E2071E622 /* SwiftTask.framework in Frameworks */, + 620573B34B510155CC9431432ECE0F38 /* UIKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C3D112ED059987A190832F596B320C15 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + E02B058C8A6E0AC405CAF7F54C65852A /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F7A69B59BD2D2E33F10C1DAB631CC926 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A8F7B821E99BED8460534AD85FD1F269 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FEF785D316E836E93C09637D3A3082CA /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 47CBCE8837CE75AE1B7484A63CE387ED /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 04BFEDE7A2E235BC7AC856979F0B7AB3 /* Utils */ = { + isa = PBXGroup; + children = ( + F511D0AF6267ABF4691C1EDE99FB659D /* EnumCountable.swift */, + AB517BF9DAFFCA1BBCC5A0BBCB5B1A73 /* Queue.swift */, + ); + path = Utils; + sourceTree = ""; + }; + 07A9C83AA1D418009E21ED330F4BE40F /* Security */ = { + isa = PBXGroup; + children = ( + 4F9C1070A7DA056DC96366DD7AB5D032 /* KeychainAccess.swift */, + ); + path = Security; + sourceTree = ""; + }; + 106194991891EBCB4DDC3E7B69FE5D75 /* Frameworks */ = { + isa = PBXGroup; + children = ( + FF14E7E64D23B07812BAF0C10D193605 /* Alamofire.framework */, + 41D136DE7AD7FCE83428ECEF04EDC1F7 /* Freddy.framework */, + FDE84FF0D7B9663C062BD966122BCA44 /* SwiftTask.framework */, + 90A500996396D7E31F4E8EA49E545E3F /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 18D0A69B94DF53ACB59D40A786D7FDFA /* Logging */ = { + isa = PBXGroup; + children = ( + 40766F0C467159B985AA2723FF099609 /* Log.swift */, + ); + path = Logging; + sourceTree = ""; + }; + 281D4731416EA0C2BBE8052BE78008CD /* Astro */ = { + isa = PBXGroup; + children = ( + 38A0860C5FA72618CDBFD9DD2947E101 /* UI */, + ); + path = Astro; + sourceTree = ""; + }; + 31FA8BF1EA224E8F7C9217F2852FB262 /* Alamofire */ = { + isa = PBXGroup; + children = ( + C38CF09F3C3B8CF308264F6D6E482788 /* Alamofire.swift */, + 1B6175C0F07945B33BA87785C28C9912 /* Download.swift */, + BE1DED67D6DF1F164F02F3F1476DFA5A /* Error.swift */, + E99A028ACF5FC3336D388BD40CF620DB /* Manager.swift */, + 5A70FC1773E4B74A1B01208EEB34131B /* MultipartFormData.swift */, + 1BB1B584B2D9EB110E04D032D2FC6353 /* NetworkReachabilityManager.swift */, + EE5E7EF01AC1AFCC9C8519CE17A4B669 /* Notifications.swift */, + 5C529BFE5644828353B7A79D9E41E228 /* ParameterEncoding.swift */, + 1D57166DA009DF7F279278E659B83001 /* Request.swift */, + F06A779758B1FCB858DFC3BFB2C04DBC /* Response.swift */, + CD040DF2D5579CF2DF4A1A521BB6CCEC /* ResponseSerialization.swift */, + FC549157357F78725756BA1D794D8956 /* Result.swift */, + 70D64846E5ED48505B235794D511C710 /* ServerTrustPolicy.swift */, + DD33E17A1452351E0F9E09CD13FDC6B8 /* Stream.swift */, + C92A12C07271BFC6F6C83EDC7DC1F6C7 /* Timeline.swift */, + 48BE2756E789DA180A9EE1D5BE1874A4 /* Upload.swift */, + C2A80AABF30E3F90F8BE459718464BF9 /* Validation.swift */, + 7B70D6FB1D913BC9732223742802F1AD /* Support Files */, + ); + path = Alamofire; + sourceTree = ""; + }; + 349551D5BC8FCB15D04980F64473FF69 /* Astro */ = { + isa = PBXGroup; + children = ( + DE7D5630863DFCBD5C464BD22A392512 /* Logging */, + 553B9FEDDC912F69E8DB79B8A37EBF20 /* Networking */, + 653776701E21D26AEC22777B5FE9672B /* Security */, + DD6A520257E2DA1470283635103EB06B /* Support Files */, + 9595737B7BA1965179CF6E08B70ABCD2 /* UI */, + F3C19A259960EAF1D1A32522546E3D1F /* Utils */, + ); + name = Astro; + path = ..; + sourceTree = ""; + }; + 38A0860C5FA72618CDBFD9DD2947E101 /* UI */ = { + isa = PBXGroup; + children = ( + 90C80D0F88F467734DCA9AB2BD6754E5 /* LayoutLabel.swift */, + A52A75DB7A7E8D5ABD5E0A8677F3C487 /* UIColor+AstroGadgets.swift */, + 1DA4BC7AA452C12ED8B08E83DB465C62 /* UIView+AstroGadgets.swift */, + A4D2A6077533A721DD33F24F8F498E62 /* UIViewController+AstroGadgets.swift */, + ); + path = UI; + sourceTree = ""; + }; + 412A7D978A4C92CD7D2A9E0B7C28476D /* Astro */ = { + isa = PBXGroup; + children = ( + 18D0A69B94DF53ACB59D40A786D7FDFA /* Logging */, + ); + path = Astro; + sourceTree = ""; + }; + 52B3B58AEB142FBB7485C07B02A992B0 /* Networking */ = { + isa = PBXGroup; + children = ( + 7AB33573A133A91BFBE2D06A0EEA0ADF /* HTTPStatusCode.swift */, + FBBBDB2DA9151DCA301BF0A6E773F9FF /* NetworkService.swift */, + B3DED6207BC66EC19693CBBB8E70F983 /* Route.swift */, + ); + path = Networking; + sourceTree = ""; + }; + 553B9FEDDC912F69E8DB79B8A37EBF20 /* Networking */ = { + isa = PBXGroup; + children = ( + B629C708086DB4A8E35AF3FF2F7B3B70 /* Astro */, + ); + name = Networking; + sourceTree = ""; + }; + 56936B1EF8E2D08825EA4C01EDFAFA98 /* Astro */ = { + isa = PBXGroup; + children = ( + 04BFEDE7A2E235BC7AC856979F0B7AB3 /* Utils */, + ); + path = Astro; + sourceTree = ""; + }; + 59DE3BC645E215DE0E2DF6D6DE378574 /* Nocilla */ = { + isa = PBXGroup; + children = ( + F1CDA5C29F4226AB151CCB0A717465AA /* ASIHTTPRequestStub.h */, + 21E6E306A222BB7B4910F4381D552E4A /* ASIHTTPRequestStub.m */, + 5B700373BAD98857FB8B7D43320BAE6E /* LSASIHTTPRequestAdapter.h */, + F598CC4E191ADFF7C8DF93B4B9A22F13 /* LSASIHTTPRequestAdapter.m */, + 1B0BC0D43B557E478A7AC87FC68C3B22 /* LSASIHTTPRequestHook.h */, + C3BBBE6BD192BF863A94377B37488914 /* LSASIHTTPRequestHook.m */, + 08EBF5E98850CE0D59CD4790AE4E05A9 /* LSDataMatcher.h */, + 215B768C828ACF6EDCAD625F7A57F60A /* LSDataMatcher.m */, + 1C7E74E409C0A0FF82091CE470CC633D /* LSHTTPBody.h */, + 9773F594CFB512CB7A612BDA2242D868 /* LSHTTPClientHook.h */, + F813B762FD46FFE133BE08FBA25199EF /* LSHTTPClientHook.m */, + 0E5CF2AB8A1768830A16697E65455D4A /* LSHTTPRequest.h */, + 99BA98371CC71CBBD02B1C626F309DCD /* LSHTTPRequestDiff.h */, + 2E84C95072B0D268B49E3983BA78D64F /* LSHTTPRequestDiff.m */, + 2C6D3290D1DBF2130A57A59FDF56617D /* LSHTTPRequestDSLRepresentation.h */, + EEBD54710A06AEF2A841D76C5D103DCA /* LSHTTPRequestDSLRepresentation.m */, + 666499CBBC4996DE397CA1CCF1689947 /* LSHTTPResponse.h */, + 8AEC080634ED245BCD85C53126EE83FC /* LSHTTPStubURLProtocol.h */, + 935CB3CC8195F22FBF8955E2FD8A07BB /* LSHTTPStubURLProtocol.m */, + BEF4A9B34EFBF0E5660D27C57A2C9605 /* LSMatcheable.h */, + 62A18C9C05326332D45658DF26A5DC52 /* LSMatcher.h */, + 6205D5C0FB3D9036F177DEBF76CD96BC /* LSMatcher.m */, + 740A1225FBB93D00E7780C9248E24F10 /* LSNocilla.h */, + 5A1C175C7A891D63E146044DF96BD727 /* LSNocilla.m */, + AB051FCF80CC7C2B73C825DBEF35252A /* LSNSURLHook.h */, + 57BCDA3FA7A78B29FC1010111712059F /* LSNSURLHook.m */, + 09369E6621D03C4D8547E467FB8526B3 /* LSNSURLSessionHook.h */, + 8E019C411893B8E5CC125BDB3D9C356B /* LSNSURLSessionHook.m */, + 6360E2524B77978580F6B83A3067E9B3 /* LSRegexMatcher.h */, + BDCD7A584251A05E7546A8C30B112AD0 /* LSRegexMatcher.m */, + 037D5199F69F8288CA074CDE9981C835 /* LSStringMatcher.h */, + E2993F8A9771156E121C62FFBEBBEB2D /* LSStringMatcher.m */, + 88606CFF78D8FA2F735FBE083CE15272 /* LSStubRequest.h */, + 933EED4371DBCE2167B600FC06C24228 /* LSStubRequest.m */, + 24EB686A9187237EC0D542A4A26881AF /* LSStubRequestDSL.h */, + B20551A59697BD87AB5FDE5C7A0A30B4 /* LSStubRequestDSL.m */, + 8A50386EDB40911FEABEAED0E4BB975B /* LSStubResponse.h */, + CA7F9F2D3BC0D743DB62F65F771E6E96 /* LSStubResponse.m */, + 486AD68885FD024FAA1DE18E7B99E032 /* LSStubResponseDSL.h */, + A9ECE62FAB6CC87EAE56E9EC7C2533EB /* LSStubResponseDSL.m */, + 1DB921FDEB8F795C32706D42D10E99AD /* Nocilla.h */, + B24FBEF8AB502215F26A19C54552E53D /* NSData+Matcheable.h */, + 00C8CC16BD4B806E48B1374B566F4CD9 /* NSData+Matcheable.m */, + 8A08012C92D3BEB87C3BAF924DF17BA0 /* NSData+Nocilla.h */, + 2B34E178970B70AF83F2D0104154B4C6 /* NSData+Nocilla.m */, + A383F9C5E5B3240445EC799443DFBE48 /* NSRegularExpression+Matcheable.h */, + D61DFEA183AEE286758C8B5617777825 /* NSRegularExpression+Matcheable.m */, + 0E1C201B58EAF7F53ED9FDB2DE77D696 /* NSString+Matcheable.h */, + EC36B20C01662C337AE1E1B9182A9989 /* NSString+Matcheable.m */, + AF89FEF1C7D784E5CAB83C46017149C3 /* NSString+Nocilla.h */, + E14458DC858BFCB6F9E80CBC95A1DE10 /* NSString+Nocilla.m */, + CD81E565DFBCD23784D4A379ADF1815F /* NSURLRequest+DSL.h */, + EFA45F884E74D416A2CB94D83F76A11A /* NSURLRequest+DSL.m */, + 66CC9B801997F61B96C5719193CA636D /* NSURLRequest+LSHTTPRequest.h */, + 2B3E454647835A4B7F4C78D3958A9F1A /* NSURLRequest+LSHTTPRequest.m */, + 6BF9A70AD6FF603F5E7A705FEAE3B79D /* Support Files */, + ); + path = Nocilla; + sourceTree = ""; + }; + 5BB43D1DAE69005125BBCAC6D0518623 /* Nimble */ = { + isa = PBXGroup; + children = ( + 556FA88DC471542F2CB2B5EB084A211A /* AdapterProtocols.swift */, + 56ED0B19C40FFF7EDD9CAAE9262402CD /* AllPass.swift */, + 4BCE60758BD208F904264B1F4A110801 /* AssertionDispatcher.swift */, + FFA756C9D950245A5366DD0A0EC267EC /* AssertionRecorder.swift */, + DF6998F96251AA400D2CB350EC25BAB9 /* Async.swift */, + 07D74A91BCFD69C9E1C3F3BBF9CC777B /* AsyncMatcherWrapper.swift */, + C6F587C4B92886F7BB1A4A2F88D600F3 /* BeAKindOf.swift */, + ED9D4484D8A9B8DCBFDDE991EC024DD0 /* BeAnInstanceOf.swift */, + 7FB7DEAF15D7E7DDE899E9D09569708F /* BeCloseTo.swift */, + 44538300F5802FC65969BBF566DFB619 /* BeEmpty.swift */, + 018EC0A4904E4B088A5A073E648C19B5 /* BeginWith.swift */, + DB8028483A380281298717B363ED326E /* BeGreaterThan.swift */, + BC2B2BF86C08224CC0CA71E6FFEB075B /* BeGreaterThanOrEqualTo.swift */, + 08557293038B060E63351D04FAA3661B /* BeIdenticalTo.swift */, + 2674300CB730134EDCAD3694E9665CB1 /* BeLessThan.swift */, + D19CF36C5FE6F4001B9167BA9C8A28A5 /* BeLessThanOrEqual.swift */, + EC64FABB231B2528B5FD76A4AC394DB5 /* BeLogical.swift */, + 49E1B592BED6BB90BB6F2F89FA3E989E /* BeNil.swift */, + BD7ADBE040B34288DEF642C059297546 /* BeVoid.swift */, + B53C5ACBAE69917D3C14246F861DF751 /* Contain.swift */, + 5C73A1245CDA974F563837D844547617 /* CurrentTestCaseTracker.m */, + 6B93B92F0117AC91DA973DD6FA708339 /* DSL.h */, + 01B684422F9A68DB967394EAC091E627 /* DSL.m */, + 6ACE15C16D148D217BDB20FFEFFCF02F /* DSL.swift */, + F897256CD08EAEADC4CF349C4A56D98D /* DSL+Wait.swift */, + D432E948A3B1245ABDB9E2355EFB85AD /* EndWith.swift */, + BE61F544EA1DEB7394D1DB26182F1849 /* Equal.swift */, + 1FADAF5723E3783E2D2CB736373725B5 /* ExceptionCapture.swift */, + 6F3C0C399D268AA91831AE634921FDF4 /* Expectation.swift */, + 1D6A308350139622BAE6ACB0FECD59AA /* Expression.swift */, + 246E55C5423DE0296BF8B2E2283F8451 /* FailureMessage.swift */, + E21EAC014ECB332659AE5CE74500EC21 /* Functional.swift */, + EDFD96BF70CDC200784A60185BE056A8 /* HaveCount.swift */, + 6E203099AEBFA89BB26866928B47B729 /* Match.swift */, + A2C85A809276C7CF7C77A8F526F48948 /* MatcherFunc.swift */, + 8204BE5D1FE8224508DE7C846BD1B2A2 /* MatcherProtocols.swift */, + D1237ED721CA0F3952D47B10622A617E /* Nimble.h */, + 32930ABA04829C715E9309828367451B /* NimbleEnvironment.swift */, + DA401D928A2174F298834E21A3B2AB12 /* NimbleXCTestHandler.swift */, + C9DEBF825D7E53BF5C8D0F265A9A1AE5 /* NMBExceptionCapture.h */, + CAB0BDFFF1C8029048D89A3BF0057285 /* NMBExceptionCapture.m */, + DC244876ABA22AA03CED8927B2CDF2E5 /* ObjCExpectation.swift */, + DFC4284902E1C186D4B5C7BBFCD91B84 /* ObjCMatcher.swift */, + 3C7DE601C7FCC67C58CFF4B7F6509262 /* PostNotification.swift */, + 96859D1DF2FBE1631D680809FCE58575 /* RaisesException.swift */, + B118A954E3CE6751BEDDA7A3621C8B1B /* SatisfyAnyOf.swift */, + AC985E6776F0DC8A00AD86967C1FAE73 /* SourceLocation.swift */, + 580685080BA8A710801E892C91D930A0 /* Stringers.swift */, + 20DECE4687279E305EE363109B2CEAF4 /* ThrowError.swift */, + B7349244242F10863A7B840AEA64A99C /* Support Files */, + ); + path = Nimble; + sourceTree = ""; + }; + 653776701E21D26AEC22777B5FE9672B /* Security */ = { + isa = PBXGroup; + children = ( + F240F06DDE8FDA03B0AEB863E1C33825 /* Astro */, + ); + name = Security; + sourceTree = ""; + }; + 6BF9A70AD6FF603F5E7A705FEAE3B79D /* Support Files */ = { + isa = PBXGroup; + children = ( + A76279FC16BEF9EAD9C89D44AD1CA184 /* Info.plist */, + A87B16568F2E92E55610317821E0FECE /* Nocilla.modulemap */, + 6FCBC236F707B2863121FD75A2B783A7 /* Nocilla.xcconfig */, + 1BB32E06FD13A42B1754090B64ABA926 /* Nocilla-dummy.m */, + 19B5EF8C24AF289FEC3DEFDCADC7B12C /* Nocilla-prefix.pch */, + 376A62A3AEF587E01593F5D415550697 /* Nocilla-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/Nocilla"; + sourceTree = ""; + }; + 7ACA5C36D4C114F9D9BDE8A0220636D6 /* Products */ = { + isa = PBXGroup; + children = ( + 0E30C666974AFD8AE1D15D77D6FAE0D4 /* Alamofire.framework */, + 978B87B6A0E09CFE16BB8AFDF35C7524 /* Astro.framework */, + D1F318A61A9ABA6904BC70BCB14E8965 /* Freddy.framework */, + FCE3C6A2429004B3D14090204CC6CC53 /* Nimble.framework */, + BA3DC2ADF554F5AA1C3D8026782FCDD6 /* Nocilla.framework */, + 79BCBBE911B763D6036063E7D32BF5D0 /* Pods_Astro.framework */, + F89A3E458EC43DC935269FB7DD771D86 /* Pods_AstroTests.framework */, + 7A4A3ECEB9A900D640EF1635D4313478 /* Quick.framework */, + C4A303959AA23940B44A630C103DD53B /* SwiftTask.framework */, + ); + name = Products; + sourceTree = ""; + }; + 7B70D6FB1D913BC9732223742802F1AD /* Support Files */ = { + isa = PBXGroup; + children = ( + 38C7DFE274B7201CF938B4C39C143127 /* Alamofire.modulemap */, + 0AB1D855C50B7605DF675B33356E70FF /* Alamofire.xcconfig */, + D522CC6D5DFC8CDA09D6831C940906B1 /* Alamofire-dummy.m */, + A35FF701553483D20C02D7FBAF1B8855 /* Alamofire-prefix.pch */, + 7FD0E7B25D8D24C9A657D2405566EC54 /* Alamofire-umbrella.h */, + 975DEA98C31CF3D29E771F478017AFED /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + 7B827A32682726DD5523CB798361BE12 /* Freddy */ = { + isa = PBXGroup; + children = ( + 07DCDEDF9C00CC7D1C61D1D38C722EBD /* Freddy.h */, + 959709CD9AA3DCA94FEA572CDFCF1BB2 /* JSON.swift */, + A7A349A616F16796BBF0F5C63AD4A0D1 /* JSONDecodable.swift */, + 08503275A881C4B454DE98666EC4042D /* JSONEncodable.swift */, + 89F15E9D033FC5A11A4ACE1741A56934 /* JSONEncodingDetector.swift */, + 9D1D7FA44480B220CEAE13AEECEF15B8 /* JSONLiteralConvertible.swift */, + B1E27637BAEF011157068373797A74D3 /* JSONParser.swift */, + 355843C6E194A70E0B6A53BB4ED12699 /* JSONParsing.swift */, + 85F553423E820BBA7AFF070E59F8F811 /* JSONSerializing.swift */, + 83840C4A29C6F945D5B4BD089A6D603F /* JSONSubscripting.swift */, + D80012796F7C118A9CC76A1CCA967463 /* Support Files */, + ); + path = Freddy; + sourceTree = ""; + }; + 7DB346D0F39D3F0E887471402A8071AB = { + isa = PBXGroup; + children = ( + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, + CA5C3BEA446A9E8B0831F4A0D9FD9AFD /* Development Pods */, + 106194991891EBCB4DDC3E7B69FE5D75 /* Frameworks */, + 96B5DDE8106E242154A26860035EA56C /* Pods */, + 7ACA5C36D4C114F9D9BDE8A0220636D6 /* Products */, + 96FA14425713E2D6E893C6DB91BB7FAC /* Targets Support Files */, + ); + sourceTree = ""; + }; + 90A500996396D7E31F4E8EA49E545E3F /* iOS */ = { + isa = PBXGroup; + children = ( + E4D54383DE9F48DD36B48F77E57BF01E /* CFNetwork.framework */, + 4BC8039B74D4913DB1E703B667824C32 /* Foundation.framework */, + D97CC484A2DBEFEC771C1025EBC41CCE /* UIKit.framework */, + 6BCA294AF3615B183F578E3E71D213E3 /* XCTest.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 91CC38F7A2B94554873C38076D58DDBB /* SwiftTask */ = { + isa = PBXGroup; + children = ( + 0FAC898952701B46D5209EBB19206322 /* _Atomic.swift */, + 59172979F51F694E2A92AF967A65E854 /* _RecursiveLock.swift */, + E8A6B56079D4CA08CE38423A96EEF85B /* _StateMachine.swift */, + D4B872C6EE9A742550A25D71A7BEAC5C /* Cancellable.swift */, + 718746D488FF4E2AEB19CEAEFC5596A1 /* SwiftTask.h */, + A5FB155AAF1F83A98BD9205C317F51C6 /* SwiftTask.swift */, + CE13BF8EA465404642C8311D976594F5 /* Support Files */, + ); + path = SwiftTask; + sourceTree = ""; + }; + 9595737B7BA1965179CF6E08B70ABCD2 /* UI */ = { + isa = PBXGroup; + children = ( + 281D4731416EA0C2BBE8052BE78008CD /* Astro */, + ); + name = UI; + sourceTree = ""; + }; + 96B5DDE8106E242154A26860035EA56C /* Pods */ = { + isa = PBXGroup; + children = ( + 31FA8BF1EA224E8F7C9217F2852FB262 /* Alamofire */, + 7B827A32682726DD5523CB798361BE12 /* Freddy */, + 5BB43D1DAE69005125BBCAC6D0518623 /* Nimble */, + 59DE3BC645E215DE0E2DF6D6DE378574 /* Nocilla */, + EB4561C2642852B9ABBB3571BC3C32C7 /* Quick */, + 91CC38F7A2B94554873C38076D58DDBB /* SwiftTask */, + ); + name = Pods; + sourceTree = ""; + }; + 96FA14425713E2D6E893C6DB91BB7FAC /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + FAED6ED99000380BF515D69999E019F0 /* Pods-Astro */, + E40524808528E67524E1B4CB66F35588 /* Pods-AstroTests */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + A0F29DF58F48BB2250F8D3390D5C6C99 /* Support Files */ = { + isa = PBXGroup; + children = ( + 37AE78B97CFBB07F50E06240AB090DF5 /* Info.plist */, + 5964854B7B2C56E2165DC9FA19616273 /* Quick.modulemap */, + C58B78530AECACCE9C0F19AA30F62370 /* Quick.xcconfig */, + 02E57745B7D20C38D8B99FE50F65C377 /* Quick-dummy.m */, + 46ED4872452785F7C1ADB1AEC089FFEB /* Quick-prefix.pch */, + A45861F28898647557DF322055128938 /* Quick-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/Quick"; + sourceTree = ""; + }; + B629C708086DB4A8E35AF3FF2F7B3B70 /* Astro */ = { + isa = PBXGroup; + children = ( + 52B3B58AEB142FBB7485C07B02A992B0 /* Networking */, + ); + path = Astro; + sourceTree = ""; + }; + B7349244242F10863A7B840AEA64A99C /* Support Files */ = { + isa = PBXGroup; + children = ( + 5E7BB1DBF75BF7FD15FA74553EF663EF /* Info.plist */, + 6B8987186092FEE2E6BFB40BB4C40B82 /* Nimble.modulemap */, + 5F08970D8469F6AC8EFF70AEF946205D /* Nimble.xcconfig */, + 73D4F264A8ACC108D2139D0C740EE235 /* Nimble-dummy.m */, + AA19CB4E19DEAE4E69AE7CEF7A4BB65A /* Nimble-prefix.pch */, + C4E3EF118161C2D530B2D7F8BA62F259 /* Nimble-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/Nimble"; + sourceTree = ""; + }; + CA5C3BEA446A9E8B0831F4A0D9FD9AFD /* Development Pods */ = { + isa = PBXGroup; + children = ( + 349551D5BC8FCB15D04980F64473FF69 /* Astro */, + ); + name = "Development Pods"; + sourceTree = ""; + }; + CE13BF8EA465404642C8311D976594F5 /* Support Files */ = { + isa = PBXGroup; + children = ( + 561DCE42AA14EE97B88C05205E6B2FFD /* Info.plist */, + BD10223C5A57996E0DFA3EEA8DF3A111 /* SwiftTask.modulemap */, + 1CD70AE2B4CBC113F7A546EC5365B93E /* SwiftTask.xcconfig */, + 7AE15AE95C7899FDFDF008072E2A12D8 /* SwiftTask-dummy.m */, + E6CF0B57AF80A3163EEA409C7757D730 /* SwiftTask-prefix.pch */, + 18EA6F2FCD99D7DD985FCAEA6EC626DC /* SwiftTask-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/SwiftTask"; + sourceTree = ""; + }; + D80012796F7C118A9CC76A1CCA967463 /* Support Files */ = { + isa = PBXGroup; + children = ( + 50C0E4DFCA69C34F7ABBBA680A7BB9AD /* Freddy.modulemap */, + 9F5C636F6C5EA27DBCB9C6C3CA680826 /* Freddy.xcconfig */, + AFF88D60EB7A5E61E3734F53E9B81D84 /* Freddy-dummy.m */, + 45BF6CC47BA8AE2AE5510EA0CBD7D844 /* Freddy-prefix.pch */, + E0F3F1404956E871D7ECA60C378BAA60 /* Freddy-umbrella.h */, + 478795D7B64F9DBB6E9B622BAF78A351 /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/Freddy"; + sourceTree = ""; + }; + DD6A520257E2DA1470283635103EB06B /* Support Files */ = { + isa = PBXGroup; + children = ( + 5130E6C4B0648E65F27B4B60E917F4D9 /* Astro.modulemap */, + 748EA67BCFF48DE8E76C6F13965EE8E6 /* Astro.xcconfig */, + 1CF059E9D75DEFA1FC51BA89F96FCD54 /* Astro-dummy.m */, + 0FD350C81335B2D7E13DBA6A353DB0A0 /* Astro-prefix.pch */, + AD7D87EC77CCE2F8C0B6D5BD0C78F808 /* Astro-umbrella.h */, + 00351519C4E7E45AB67C9AE54E9BC5FF /* Info.plist */, + ); + name = "Support Files"; + path = "Pods/Target Support Files/Astro"; + sourceTree = ""; + }; + DE7D5630863DFCBD5C464BD22A392512 /* Logging */ = { + isa = PBXGroup; + children = ( + 412A7D978A4C92CD7D2A9E0B7C28476D /* Astro */, + ); + name = Logging; + sourceTree = ""; + }; + E40524808528E67524E1B4CB66F35588 /* Pods-AstroTests */ = { + isa = PBXGroup; + children = ( + 6A48017A94FCEF5694E75BD283E6D2C4 /* Info.plist */, + 18894A3E151905AB3BB2BEB1A15E9977 /* Pods-AstroTests.modulemap */, + E9D00D8B2A0D78B2B486894AD785D781 /* Pods-AstroTests-acknowledgements.markdown */, + 2E71D1C2D2314E373416420A365F7368 /* Pods-AstroTests-acknowledgements.plist */, + 5CB1530548D1D9E85E0CA807FE68F4B5 /* Pods-AstroTests-dummy.m */, + 5B9479BA6CA341455D32AC3F2A470434 /* Pods-AstroTests-frameworks.sh */, + 0014D967034D35F957148B768101D8F4 /* Pods-AstroTests-resources.sh */, + F1012B82C8E2EB174EC08743BCE9146E /* Pods-AstroTests-umbrella.h */, + F63DCD4CFAFE4F7967822B5A4D971100 /* Pods-AstroTests.debug.xcconfig */, + 4B41E2C6F9BDDB8E500A76ACD24DC2A6 /* Pods-AstroTests.release.xcconfig */, + ); + name = "Pods-AstroTests"; + path = "Target Support Files/Pods-AstroTests"; + sourceTree = ""; + }; + EB4561C2642852B9ABBB3571BC3C32C7 /* Quick */ = { + isa = PBXGroup; + children = ( + CB1A413A673529FE4EA52BC8ADD3F528 /* Callsite.swift */, + 76152E950AB1F0ECD2EA3B0B2D380365 /* Closures.swift */, + 7F90DE596DC3117F88CEE01B3B85B587 /* Configuration.swift */, + 764D3566600AF08BE9E045AD225DDE34 /* DSL.swift */, + 2B210588090C1A8615A7263069ACF6F9 /* ErrorUtility.swift */, + CB748F8E3291D161137C48DABBCDBE4D /* Example.swift */, + 16CEA0DF7B1B801C54BACC2F3D36A070 /* ExampleGroup.swift */, + FC772B3FDB7176368B55A892D4C5226C /* ExampleHooks.swift */, + 3375C76C22C797C8327948D959CE686D /* ExampleMetadata.swift */, + 89733119C7341F88D957D4C16F746E25 /* Filter.swift */, + 1D267E39340A0E1533C5C6BB5559E9FE /* HooksPhase.swift */, + 5B9DDD2E2D087DE41FE10BBE3FB84940 /* NSBundle+CurrentTestBundle.swift */, + 63DD1B1F48BE14CDD17AC94D8E025D3B /* NSString+QCKSelectorName.h */, + B360270783ED44EAB36B632CDA94A249 /* NSString+QCKSelectorName.m */, + 3C8AF1FA9140A19391F57B93E8FBEAC4 /* QCKDSL.h */, + AF9CB0DF1DAF7BC0001D68009B77DAEC /* QCKDSL.m */, + 46F5790BDF2B23727CBEED623FA4B790 /* Quick.h */, + 850C70E03DB4FE8DE70A33C20FA18FDE /* QuickConfiguration.h */, + AD8BF00170DCE12439E001B878408769 /* QuickConfiguration.m */, + E019BD16B087EDC3E10B12C2D5466294 /* QuickSelectedTestSuiteBuilder.swift */, + 25A9215971B7F9942A388AFF5A7F225C /* QuickSpec.h */, + 2D8D24CBFA077EE8C5F66870B269186B /* QuickSpec.m */, + E4B423AF51FEE630622404ABCA692786 /* QuickTestSuite.swift */, + 3F91823DE328E0C3D6BDE74B168C5414 /* String+FileName.swift */, + 3E779502250CE3D994F3080B1989AEF9 /* SuiteHooks.swift */, + B79754ADC53CA9E03EA5250AAF1BD4FF /* World.h */, + 8EF82508859CC525834813881F6D1B77 /* World.swift */, + 4F026309ABF704D83EB6B37ECC300575 /* World+DSL.h */, + 1DAF602663993CD69CB887EFF206A219 /* World+DSL.swift */, + B3C64DCAF1544AC0A8D47DE543C5DFD7 /* XCTestSuite+QuickTestSuiteBuilder.m */, + A0F29DF58F48BB2250F8D3390D5C6C99 /* Support Files */, + ); + path = Quick; + sourceTree = ""; + }; + F240F06DDE8FDA03B0AEB863E1C33825 /* Astro */ = { + isa = PBXGroup; + children = ( + 07A9C83AA1D418009E21ED330F4BE40F /* Security */, + ); + path = Astro; + sourceTree = ""; + }; + F3C19A259960EAF1D1A32522546E3D1F /* Utils */ = { + isa = PBXGroup; + children = ( + 56936B1EF8E2D08825EA4C01EDFAFA98 /* Astro */, + ); + name = Utils; + sourceTree = ""; + }; + FAED6ED99000380BF515D69999E019F0 /* Pods-Astro */ = { + isa = PBXGroup; + children = ( + 0979C227E7552D43BEF6C85C5E418766 /* Info.plist */, + 3A53526BFF3C6D5B366DA4066B49DD74 /* Pods-Astro.modulemap */, + E95A97D962711156B3B673A517C02090 /* Pods-Astro-acknowledgements.markdown */, + 410C6A2BACECF4513F82EA7EBC0D1BFB /* Pods-Astro-acknowledgements.plist */, + 6CA7B27079A3AE437FFB717B6CEB7766 /* Pods-Astro-dummy.m */, + 9AA1D1F085FBA836D99BB30907F537F7 /* Pods-Astro-frameworks.sh */, + 02C475E83572D471A01BFD104587CDB7 /* Pods-Astro-resources.sh */, + 4046EBF9B062ED9B23FAB96D07561CA0 /* Pods-Astro-umbrella.h */, + 6802180060568B48E5AA39180D643845 /* Pods-Astro.debug.xcconfig */, + 1640764CAB261E1814B1BA7709848F58 /* Pods-Astro.release.xcconfig */, + ); + name = "Pods-Astro"; + path = "Target Support Files/Pods-Astro"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 11199B6564676458F0D9EE06D026F377 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 1910721AF00D699CA600DC76F1DD8931 /* Astro-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2892402090ED2D6AF2641AD4B3C96F65 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 52695B80D42DFB4C48D7A906478509EB /* ASIHTTPRequestStub.h in Headers */, + 128B9A07E9D0F95B28E5F1F3483CB7EA /* LSASIHTTPRequestAdapter.h in Headers */, + 27832B2605A37241AF9CD554C9ECB6D0 /* LSASIHTTPRequestHook.h in Headers */, + 3B4F15B3D4EBB8580874CFA87CAAB437 /* LSDataMatcher.h in Headers */, + 746762DD022722AA0783532E872ACCC0 /* LSHTTPBody.h in Headers */, + D2B3B8A5532F9F084D2855970798CB82 /* LSHTTPClientHook.h in Headers */, + 3B588A1AD8E3D88B70EF1A8D3CF519ED /* LSHTTPRequest.h in Headers */, + A434C8CB0F23A35DA222105C7B11300D /* LSHTTPRequestDiff.h in Headers */, + A460983620B3719092C5217CCC57A699 /* LSHTTPRequestDSLRepresentation.h in Headers */, + B7B6C386D18C61D236CE7B92C62DC4F4 /* LSHTTPResponse.h in Headers */, + 15A7217C749314E8423F3C36A99BAF7A /* LSHTTPStubURLProtocol.h in Headers */, + CA303CF6D30D41F05C81DF35576B6C34 /* LSMatcheable.h in Headers */, + CA00C21F8A03E237E579CD6DA42B0DF0 /* LSMatcher.h in Headers */, + 2070701995190A07047F664492D7F156 /* LSNocilla.h in Headers */, + C4F4C8EF4A764C0FDEB5789F9207FFF2 /* LSNSURLHook.h in Headers */, + 0D96C808906230C689C8310AC8E7DF5B /* LSNSURLSessionHook.h in Headers */, + 4B0FACF86699832CB060706698EEDA62 /* LSRegexMatcher.h in Headers */, + 683D42CCDBA04DEAA5927130555865FB /* LSStringMatcher.h in Headers */, + DE94765732B7FBCD78E56173F4A782ED /* LSStubRequest.h in Headers */, + 6F9AC619478339681794CFB2FFF49EA3 /* LSStubRequestDSL.h in Headers */, + 781A3371065498563238D5E4E7F7BC49 /* LSStubResponse.h in Headers */, + B7BAA1610C192270DE28D6F9ACE95542 /* LSStubResponseDSL.h in Headers */, + 6AAD3EF28C1C2DA026B93AD8D814F64D /* Nocilla-umbrella.h in Headers */, + B0BD13A01F667B129F4F5F167088A024 /* Nocilla.h in Headers */, + 98448E68F706C3077F402B1F1B64520E /* NSData+Matcheable.h in Headers */, + 3C380C634D63206648B6D947901FF88D /* NSData+Nocilla.h in Headers */, + E07A45CD453CFC98DE69AA370E5780F9 /* NSRegularExpression+Matcheable.h in Headers */, + FCFC2208684969E5BDF9F439AEE58162 /* NSString+Matcheable.h in Headers */, + B30D380B5EFCD54FEE04D3C4F1988262 /* NSString+Nocilla.h in Headers */, + 8927C37DD5750B9F6409C3EA80623A16 /* NSURLRequest+DSL.h in Headers */, + 2DBDF5B701DC699F0E5A0ADCFF7F3E94 /* NSURLRequest+LSHTTPRequest.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2DA46295FF2F3A78D76A7AEFBB6A9328 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 1A2025245F64F843C4AB6B5722EAB24D /* Freddy-umbrella.h in Headers */, + A1B364D6ACB3B19F7ED2AF7989BB3197 /* Freddy.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4B93756C8652F7BAFAE950C53F4D5A79 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + FD31EB5C092198491AFA59C0AA80E33F /* NSString+QCKSelectorName.h in Headers */, + 2F2E9CFF89016043EAF1D3885AC7C696 /* QCKDSL.h in Headers */, + 0A56DFB216D6CBFDE7D38CC82A56C714 /* Quick-umbrella.h in Headers */, + 7CF0F6A48A0677DE2908A8D931A99ADC /* Quick.h in Headers */, + 617FB9A348751ECB4250ABA0316403AC /* QuickConfiguration.h in Headers */, + 8F86133FD6D0F537A52D317518115BC5 /* QuickSpec.h in Headers */, + E5257C3F4110DEEA78306240DEB2333F /* World+DSL.h in Headers */, + BE2859F1F4050BADFDDF76A557CF0FE7 /* World.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4F71E0A16A6747419DAB8EEE7A3352BD /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 30A99A47BC4031E7C5677314FDBF61A6 /* Pods-Astro-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 56651AC7E3F7B2CDCFEEB8325476F8A3 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 23626BC4DDA1A2E90A155728F57802FF /* DSL.h in Headers */, + E909D0D33037F3C642BBB8D47FC642B3 /* Nimble-umbrella.h in Headers */, + D41F628A81153A978EB209E4FE925700 /* Nimble.h in Headers */, + 86FB708FCFE6121A82BB09E5ADD84554 /* NMBExceptionCapture.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + AB0736636DEF472CEB6CDE0ED67B2528 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + F4FB5ED9614E6F9838BC0037675F5010 /* Pods-AstroTests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EFDF3B631BBB965A372347705CA14854 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F2861365E5921B53A263336FA6FD5B01 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + AEF2C12D4B021FEE2401595457B23CBE /* SwiftTask-umbrella.h in Headers */, + 6D895AA3CD19AA14FC8B6D0AA11FD213 /* SwiftTask.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 18F2F1BE1B1A39484B66A0C0D41D55C6 /* Freddy */ = { + isa = PBXNativeTarget; + buildConfigurationList = 12855E5E26887CD66AAB75AF9E177911 /* Build configuration list for PBXNativeTarget "Freddy" */; + buildPhases = ( + D7E44F47754710CB8C026109C4FB52EC /* Sources */, + C3D112ED059987A190832F596B320C15 /* Frameworks */, + 2DA46295FF2F3A78D76A7AEFBB6A9328 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Freddy; + productName = Freddy; + productReference = D1F318A61A9ABA6904BC70BCB14E8965 /* Freddy.framework */; + productType = "com.apple.product-type.framework"; + }; + 2DED8F1D97AD7B11107A2DF5C2FEBCD7 /* SwiftTask */ = { + isa = PBXNativeTarget; + buildConfigurationList = A7D59FB4DC5C8227173E53A060B244C9 /* Build configuration list for PBXNativeTarget "SwiftTask" */; + buildPhases = ( + 5CE27B38F2E6E092035857A77A16730F /* Sources */, + 9DAB5651A4C32B38474F4CEFFEDE40AD /* Frameworks */, + F2861365E5921B53A263336FA6FD5B01 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SwiftTask; + productName = SwiftTask; + productReference = C4A303959AA23940B44A630C103DD53B /* SwiftTask.framework */; + productType = "com.apple.product-type.framework"; + }; + 393E0E1A41299C44C63DBB766A243010 /* Nocilla */ = { + isa = PBXNativeTarget; + buildConfigurationList = CFC1B17C6D2D8BA2E80A422D19324095 /* Build configuration list for PBXNativeTarget "Nocilla" */; + buildPhases = ( + 5111908BA704400FC15A80EF8AFD7E0F /* Sources */, + 5F40817F9BD61376555E224A54C77911 /* Frameworks */, + 2892402090ED2D6AF2641AD4B3C96F65 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Nocilla; + productName = Nocilla; + productReference = BA3DC2ADF554F5AA1C3D8026782FCDD6 /* Nocilla.framework */; + productType = "com.apple.product-type.framework"; + }; + 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = 3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + 5FEED44A5909604CBB444B6BE51B815D /* Sources */, + B1729F851F648EC60EE93CDB3C8BAEAD /* Frameworks */, + EFDF3B631BBB965A372347705CA14854 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Alamofire; + productName = Alamofire; + productReference = 0E30C666974AFD8AE1D15D77D6FAE0D4 /* Alamofire.framework */; + productType = "com.apple.product-type.framework"; + }; + A806B96D9DEB1A4DB63C09048B2EF00E /* Quick */ = { + isa = PBXNativeTarget; + buildConfigurationList = 4655531C845E8D36877301C76982FD46 /* Build configuration list for PBXNativeTarget "Quick" */; + buildPhases = ( + 5A2B024904235D1442DC49E1C77C43F5 /* Sources */, + 21B8AC554E0DA6E686465542DD732B35 /* Frameworks */, + 4B93756C8652F7BAFAE950C53F4D5A79 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Quick; + productName = Quick; + productReference = 7A4A3ECEB9A900D640EF1635D4313478 /* Quick.framework */; + productType = "com.apple.product-type.framework"; + }; + B025A060E6A35B16AB1D07BA4F9DD3DB /* Pods-AstroTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 8F3DD3BC50DF7C47C729F63BC1A9400A /* Build configuration list for PBXNativeTarget "Pods-AstroTests" */; + buildPhases = ( + 9BDBD44EAD2CFF6A51CC96C708A3EFEA /* Sources */, + F7A69B59BD2D2E33F10C1DAB631CC926 /* Frameworks */, + AB0736636DEF472CEB6CDE0ED67B2528 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + 8C61511C7F16907EDD83B51428CB689B /* PBXTargetDependency */, + 5A9FBE1476ECAA5F653CEB42C3741EBB /* PBXTargetDependency */, + 63A9FA5468BC49D26EB9EF614CCB0BCB /* PBXTargetDependency */, + ); + name = "Pods-AstroTests"; + productName = "Pods-AstroTests"; + productReference = F89A3E458EC43DC935269FB7DD771D86 /* Pods_AstroTests.framework */; + productType = "com.apple.product-type.framework"; + }; + ED668473F669DFBA756C8C69A8DA8ABA /* Pods-Astro */ = { + isa = PBXNativeTarget; + buildConfigurationList = 846A64A59C7983583040AD4BF0DD2601 /* Build configuration list for PBXNativeTarget "Pods-Astro" */; + buildPhases = ( + 7498A3CE01C6B367ABCBE01EF6A5D3C4 /* Sources */, + 1CFB8EC27F7DFF390441337C21B67AB8 /* Frameworks */, + 4F71E0A16A6747419DAB8EEE7A3352BD /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + 6152C2CDE3F65E00B48323F2C3B1A26A /* PBXTargetDependency */, + 1E46036FCF2A6D78855E341827A463B9 /* PBXTargetDependency */, + DCF118E47792B1D75EFAD11D249DC840 /* PBXTargetDependency */, + 96A446CA9840C9BD82FAD02405E2E22C /* PBXTargetDependency */, + ); + name = "Pods-Astro"; + productName = "Pods-Astro"; + productReference = 79BCBBE911B763D6036063E7D32BF5D0 /* Pods_Astro.framework */; + productType = "com.apple.product-type.framework"; + }; + FBC498C9743D0DFCE3F099202D9534DC /* Astro */ = { + isa = PBXNativeTarget; + buildConfigurationList = B7A6539B2C98DBC6CF1353F53ED33581 /* Build configuration list for PBXNativeTarget "Astro" */; + buildPhases = ( + 76DE823386D36E684024670DAA367745 /* Sources */, + BAECFED1DCB8D9AD70B0EC59A43164F3 /* Frameworks */, + 11199B6564676458F0D9EE06D026F377 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + 6C2B5AF75E7EFDBB96B95BA26960729B /* PBXTargetDependency */, + DF0599A3C561D2C98B9C76C00120EB06 /* PBXTargetDependency */, + 4F7FDA146503F1934FD44FF77C947009 /* PBXTargetDependency */, + ); + name = Astro; + productName = Astro; + productReference = 978B87B6A0E09CFE16BB8AFDF35C7524 /* Astro.framework */; + productType = "com.apple.product-type.framework"; + }; + FF61C7C740C1B196A3B33F37B77DBC68 /* Nimble */ = { + isa = PBXNativeTarget; + buildConfigurationList = 5FE57A1C8E467D246D7D1BCB203A09DC /* Build configuration list for PBXNativeTarget "Nimble" */; + buildPhases = ( + 1652C1155B38FCDBB222954CB5A96914 /* Sources */, + FEF785D316E836E93C09637D3A3082CA /* Frameworks */, + 56651AC7E3F7B2CDCFEEB8325476F8A3 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Nimble; + productName = Nimble; + productReference = FCE3C6A2429004B3D14090204CC6CC53 /* Nimble.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0730; + LastUpgradeCheck = 0700; + }; + buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 7DB346D0F39D3F0E887471402A8071AB; + productRefGroup = 7ACA5C36D4C114F9D9BDE8A0220636D6 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */, + FBC498C9743D0DFCE3F099202D9534DC /* Astro */, + 18F2F1BE1B1A39484B66A0C0D41D55C6 /* Freddy */, + FF61C7C740C1B196A3B33F37B77DBC68 /* Nimble */, + 393E0E1A41299C44C63DBB766A243010 /* Nocilla */, + ED668473F669DFBA756C8C69A8DA8ABA /* Pods-Astro */, + B025A060E6A35B16AB1D07BA4F9DD3DB /* Pods-AstroTests */, + A806B96D9DEB1A4DB63C09048B2EF00E /* Quick */, + 2DED8F1D97AD7B11107A2DF5C2FEBCD7 /* SwiftTask */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + 1652C1155B38FCDBB222954CB5A96914 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C67CC9B37557A88C14D320B410CBA00A /* AdapterProtocols.swift in Sources */, + E7CD4D0D590E6491FD61FDB44EA334C2 /* AllPass.swift in Sources */, + 4A98AA6B071BEB79642C94C5F58E0D5C /* AssertionDispatcher.swift in Sources */, + ACF38EF4EB8775D8AC246D7CCBFB441F /* AssertionRecorder.swift in Sources */, + E864F07E13F0CBB3F691DD8F8580B236 /* Async.swift in Sources */, + 83275420D9F49327728E1560D2995196 /* AsyncMatcherWrapper.swift in Sources */, + F6299CD7B9C9B0E1D83DF4E3CFA6AA54 /* BeAKindOf.swift in Sources */, + 4F2873EB618D3BB1893CA07D711F70A5 /* BeAnInstanceOf.swift in Sources */, + 00E8F3031E1B84826D9BE64F0839F209 /* BeCloseTo.swift in Sources */, + 7E8EBE325AE2D649132EC27CBF0C7A3F /* BeEmpty.swift in Sources */, + 317E3ED277933E30E597B27316D856E9 /* BeginWith.swift in Sources */, + 5BF59C189F6C80B4D28AF7C62DDFC814 /* BeGreaterThan.swift in Sources */, + 6192D80DE5F8072E50F8AD94DB6BA606 /* BeGreaterThanOrEqualTo.swift in Sources */, + 7A692287BA635EFE6ECB63A1CB023E8F /* BeIdenticalTo.swift in Sources */, + 6CA4041059696980C1FFD83079432504 /* BeLessThan.swift in Sources */, + F5E6CD1CF874ECF35CF44B0AF7FD8005 /* BeLessThanOrEqual.swift in Sources */, + 1ABB56F9E693961F44E26B982755F343 /* BeLogical.swift in Sources */, + A7BCB78230139B58161146365F858C78 /* BeNil.swift in Sources */, + FFCDEF1F24D714002E543D2F634CC077 /* BeVoid.swift in Sources */, + 684CCDCA3C79B9A4CFE267558B6384C8 /* Contain.swift in Sources */, + B0C70D84FFA2025CCA0A741F2999B6FE /* CurrentTestCaseTracker.m in Sources */, + 96B3C342BDC597A6B683D356BFC7BB59 /* DSL+Wait.swift in Sources */, + 526A4F774F884C5AD7218959ABC26F85 /* DSL.m in Sources */, + 576E5BF23D4A2AF6752939D87C211DDD /* DSL.swift in Sources */, + DFED6A187A8641FD5552C127E3A77AEF /* EndWith.swift in Sources */, + 9383E5B09D57567485DE04EF035356D9 /* Equal.swift in Sources */, + 245C3CE9E2761F83E4D5E258E2BD3622 /* ExceptionCapture.swift in Sources */, + 8901F90279DCCB94E2281EB8F8C19CB4 /* Expectation.swift in Sources */, + 7071128811148914D1738564C0EEAD5E /* Expression.swift in Sources */, + 3785C751B37F631F158EA4CCCB942A9E /* FailureMessage.swift in Sources */, + 805A1E05545888A4E807D5835B5D1D0E /* Functional.swift in Sources */, + BC59A31255D804C8B2FD3144B4138B67 /* HaveCount.swift in Sources */, + 907B0A62D05C5C9EF8DCDCBA7F8868B7 /* Match.swift in Sources */, + DD8F58A14A5415877CAFE43679DB33D7 /* MatcherFunc.swift in Sources */, + F215EE98D2DBCF42218FC69D28500843 /* MatcherProtocols.swift in Sources */, + 34EBD194EA1085AF68F7670FA9F16DAD /* Nimble-dummy.m in Sources */, + 0ED93C20ACB41E7260F5EB39152BDB80 /* NimbleEnvironment.swift in Sources */, + E8BE058CC4FF369E6AE3777374AB3A66 /* NimbleXCTestHandler.swift in Sources */, + 66C66EF805856C9D32E51795F595052B /* NMBExceptionCapture.m in Sources */, + E3DABC8D10B7297AEEC0DD259EB8BDD8 /* ObjCExpectation.swift in Sources */, + 5B4D445D893A387017723FFC687F7DFB /* ObjCMatcher.swift in Sources */, + 9D6237C3E43CDB3EC681C88CBE3229E3 /* PostNotification.swift in Sources */, + F55A763428632B5FD7DC96B3850F3B9F /* RaisesException.swift in Sources */, + C3DF7DC84C3889C096A32E13A862BD32 /* SatisfyAnyOf.swift in Sources */, + DD8764F9B4466802952AA0ED464DB0EC /* SourceLocation.swift in Sources */, + A4EBAF74EB6135EB10930E2FC120B6CE /* Stringers.swift in Sources */, + B0CA346E3898D1F58F2ED08B9A06DF80 /* ThrowError.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5111908BA704400FC15A80EF8AFD7E0F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 7A3FEC3C8303482043DB7C0A6184BF08 /* ASIHTTPRequestStub.m in Sources */, + 3BA67C86ED6B34936485F11775AB6847 /* LSASIHTTPRequestAdapter.m in Sources */, + C375CF1D80C1EDAF7A59CF55A204A1EA /* LSASIHTTPRequestHook.m in Sources */, + 5C50D4DC86334599B9967449D88C8449 /* LSDataMatcher.m in Sources */, + 01FB80B2F451C84E420EF3464F5BA926 /* LSHTTPClientHook.m in Sources */, + 5546B5D9DA48D039B6AA3267D7B6EAE5 /* LSHTTPRequestDiff.m in Sources */, + 4FF8A2C2644173400B8E4CC7BE4D6D77 /* LSHTTPRequestDSLRepresentation.m in Sources */, + 9B078190829C71BDE57F32CA21580BF0 /* LSHTTPStubURLProtocol.m in Sources */, + 1C46D0414C094C95AD85104D38B72539 /* LSMatcher.m in Sources */, + 51F46241DBFA48BE6840E89B60B5C761 /* LSNocilla.m in Sources */, + 351E7765D3B3ADCA308F5A1844DC6761 /* LSNSURLHook.m in Sources */, + 73C671D884BB1EBC50D22264C30ACBF0 /* LSNSURLSessionHook.m in Sources */, + 39E1878913C1AD8669DA18845D2BC218 /* LSRegexMatcher.m in Sources */, + BAB651A8F623A6E827FC716A62B9F74D /* LSStringMatcher.m in Sources */, + 2BC2F1D0EDC01B4314095492D16E1AC4 /* LSStubRequest.m in Sources */, + D1FF865FECBBEC7089ACA994F1C0AA48 /* LSStubRequestDSL.m in Sources */, + B8C5A113F98D10AE527D439BD26EE33F /* LSStubResponse.m in Sources */, + 0A3806CD95128F25EE8B4C806FC19522 /* LSStubResponseDSL.m in Sources */, + 24B569099A40F837596002531AEBBE6C /* Nocilla-dummy.m in Sources */, + EC336944FCF11CEC2C298BFD54B1B863 /* NSData+Matcheable.m in Sources */, + A6A54F64F620A12FB4845FAA238206A7 /* NSData+Nocilla.m in Sources */, + 0BC644233E7FC0A53C9BA5EC6B87A206 /* NSRegularExpression+Matcheable.m in Sources */, + CCDFB6611155BB0F4831F06A1A8E63C2 /* NSString+Matcheable.m in Sources */, + 0072016FECB4F11D51CF666F71713F9E /* NSString+Nocilla.m in Sources */, + B4907351FF7E7AEEAC1F6DADB3ABED1F /* NSURLRequest+DSL.m in Sources */, + 4253F20907FA7DA4F0CF6E404BC9C15B /* NSURLRequest+LSHTTPRequest.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5A2B024904235D1442DC49E1C77C43F5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ABD57ABE0CA2D5E9EDDB246A64C1AD1D /* Callsite.swift in Sources */, + 206541BC9991EE86512D593D96EA83B3 /* Closures.swift in Sources */, + F2096C950FB8A9662DF8BD15AC7E8BBB /* Configuration.swift in Sources */, + 22E176E365EF446AD2ACADC28199A3DE /* DSL.swift in Sources */, + 929FE93E64765FF5AE1BFBA880F12F4C /* ErrorUtility.swift in Sources */, + 7BA96342CEA620B4EDDD7C5D42B8446B /* Example.swift in Sources */, + D017DC2887E3EF5201451BAF25519567 /* ExampleGroup.swift in Sources */, + 826517FF4AF1F646EE0FDC01B6C82722 /* ExampleHooks.swift in Sources */, + 8F83B5ED706BFAA72FC788835E165942 /* ExampleMetadata.swift in Sources */, + 32A4654CFE28CA25FF57109B50458608 /* Filter.swift in Sources */, + AB6DD25D9C52C34F62068EB8635763F6 /* HooksPhase.swift in Sources */, + AC0F9DEB7167B144AD3A2175E0D48B8B /* NSBundle+CurrentTestBundle.swift in Sources */, + 236EB99AF4ED58D8A5B3E9F8B1A0246D /* NSString+QCKSelectorName.m in Sources */, + 82EB4519BD169631C09074DFC535E4B6 /* QCKDSL.m in Sources */, + DBB0527ADF9440FEF442BE39801F8585 /* Quick-dummy.m in Sources */, + E08122859DE3AE6BEA6079C4BA6A758D /* QuickConfiguration.m in Sources */, + 9B27F32E5D611571AF5233DCEF8CB00C /* QuickSelectedTestSuiteBuilder.swift in Sources */, + BE5AF0662CD8B472503A8E996260B213 /* QuickSpec.m in Sources */, + 535D3135B94BEAB04C06E35B082E903E /* QuickTestSuite.swift in Sources */, + 9590790CA8C71CFF36DBF303367C65BE /* String+FileName.swift in Sources */, + F76FAD73B802B3FA5D61EB667A79BC83 /* SuiteHooks.swift in Sources */, + 924BB4EFA04157C8C446B30422705105 /* World+DSL.swift in Sources */, + EDB7BCD432FD07A284C407A4B1F5C0A1 /* World.swift in Sources */, + 9C5DF5EA387519C5C1B8FA73FBE0014E /* XCTestSuite+QuickTestSuiteBuilder.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5CE27B38F2E6E092035857A77A16730F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 113AA408C176B305168CEA5953B5010F /* _Atomic.swift in Sources */, + FF15CD2B5E145B3EBE8B00574F5E790D /* _RecursiveLock.swift in Sources */, + 1D83128B49CF158BA287773A81D4B840 /* _StateMachine.swift in Sources */, + 4741FF4EC5B93F91C3E08226094965F8 /* Cancellable.swift in Sources */, + 11114986CC066598887F794DDAB40F79 /* SwiftTask-dummy.m in Sources */, + 818AFDAE110D05038CAA1229DAA195F8 /* SwiftTask.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5FEED44A5909604CBB444B6BE51B815D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + F51FDBE0B58714B7CCFC263E262B0842 /* Alamofire-dummy.m in Sources */, + 82D1A45C067C46EA182F5271C7CF8398 /* Alamofire.swift in Sources */, + A13F241863C06A82E01A3486274BAA3B /* Download.swift in Sources */, + 863E32885CF961E10C349860B945D58C /* Error.swift in Sources */, + 40B6973E8E5464C0C97726DC08D36735 /* Manager.swift in Sources */, + 734D4E9CBF9F977A8B62365C32ED517B /* MultipartFormData.swift in Sources */, + FB921E2C31223EFB30816D7DB741889B /* NetworkReachabilityManager.swift in Sources */, + 288B407C1861C325D63558155BE51969 /* Notifications.swift in Sources */, + E42A03C03AF789E657C8A1D228A725C2 /* ParameterEncoding.swift in Sources */, + 13202614FB4A2465FD5D212AC6393DE6 /* Request.swift in Sources */, + CFE6E0DA62CC3C0AA51C460558431C28 /* Response.swift in Sources */, + EDBD0FB0C34E68F787748DED462CAE6D /* ResponseSerialization.swift in Sources */, + BAE69CD22A7C90828180D3664DED8E1A /* Result.swift in Sources */, + 514A09BBB819F361E14EA3435507C489 /* ServerTrustPolicy.swift in Sources */, + 250B90954338EEFB0EBC6DAA23894DDA /* Stream.swift in Sources */, + 383F4AF6C46AA6AC9F9217AF905FB7D8 /* Timeline.swift in Sources */, + C86923E3A6648C9DE493F465644EE071 /* Upload.swift in Sources */, + AC0BD0F23C2A8C8F350899F45DB4F91F /* Validation.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7498A3CE01C6B367ABCBE01EF6A5D3C4 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 71E52833B614749DD58941AB12CDFBBB /* Pods-Astro-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 76DE823386D36E684024670DAA367745 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + EBE70D5715F0880918FF30B587E617D1 /* Astro-dummy.m in Sources */, + 47449108E9477D61EB43B0D39602B4C6 /* EnumCountable.swift in Sources */, + BB4CE418BA5B88DA624FA3373A34A236 /* HTTPStatusCode.swift in Sources */, + 2B6556DC8741783CA1F65FA4336F2D3E /* KeychainAccess.swift in Sources */, + 166F14EC7CAB35D2416D035FA9B46489 /* LayoutLabel.swift in Sources */, + 9BC56CBFF66FE0AC478DA745EEAE8871 /* Log.swift in Sources */, + 49E22CBCE875C080D24BC37F234A510D /* NetworkService.swift in Sources */, + F0153EAD01D147292F0DD10A1A61766F /* Queue.swift in Sources */, + FB1EB3B52DD7D60898C88F31CDAC7F67 /* Route.swift in Sources */, + 58CEC650377EB4317EA70FF0120977AE /* UIColor+AstroGadgets.swift in Sources */, + 0718AC0FCBCC64B3C21761D890ED9705 /* UIView+AstroGadgets.swift in Sources */, + CDEDC8DAA0C457292D808100B8B8F60B /* UIViewController+AstroGadgets.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9BDBD44EAD2CFF6A51CC96C708A3EFEA /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 02768FD7624F8269944D5B2F6F6FA849 /* Pods-AstroTests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D7E44F47754710CB8C026109C4FB52EC /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + D531E95431F3763DF1ECE65C1954FB34 /* Freddy-dummy.m in Sources */, + CDE064156886F92A4E4D64FCFED5772C /* JSON.swift in Sources */, + 7EED0AB84822BB4A0C3F059E3AC0901B /* JSONDecodable.swift in Sources */, + 7CD46F6BA12D86D277CF97DF472C6BF3 /* JSONEncodable.swift in Sources */, + 05A6506FFFC7C3D12FD341B6456DA0E1 /* JSONEncodingDetector.swift in Sources */, + D97D6F06A67D170DBF191FDFD82E1410 /* JSONLiteralConvertible.swift in Sources */, + 4A99D0FD16A6B1386D175E720B3CE84F /* JSONParser.swift in Sources */, + 91A0D6340157F6B4741AC14CC07CE36A /* JSONParsing.swift in Sources */, + 6B8050E7370748D1CB6031A31CD45791 /* JSONSerializing.swift in Sources */, + D679FCA415584395E56144D07AF01DD7 /* JSONSubscripting.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 1E46036FCF2A6D78855E341827A463B9 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Astro; + target = FBC498C9743D0DFCE3F099202D9534DC /* Astro */; + targetProxy = 092F98FBAB35E78D80635DC286DE6135 /* PBXContainerItemProxy */; + }; + 4F7FDA146503F1934FD44FF77C947009 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = SwiftTask; + target = 2DED8F1D97AD7B11107A2DF5C2FEBCD7 /* SwiftTask */; + targetProxy = 28E66F9C467517BDD111A676DF6BAFB8 /* PBXContainerItemProxy */; + }; + 5A9FBE1476ECAA5F653CEB42C3741EBB /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Nocilla; + target = 393E0E1A41299C44C63DBB766A243010 /* Nocilla */; + targetProxy = 28C8609FA1466917DCEC3D46AC819CCD /* PBXContainerItemProxy */; + }; + 6152C2CDE3F65E00B48323F2C3B1A26A /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */; + targetProxy = 6C69E40802B58122DBB0A67FBA0169FB /* PBXContainerItemProxy */; + }; + 63A9FA5468BC49D26EB9EF614CCB0BCB /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Quick; + target = A806B96D9DEB1A4DB63C09048B2EF00E /* Quick */; + targetProxy = 9AC142B18F4D42F065666B4445B18163 /* PBXContainerItemProxy */; + }; + 6C2B5AF75E7EFDBB96B95BA26960729B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */; + targetProxy = 1C54C7E54A1BE7D68920E9D73B1357A3 /* PBXContainerItemProxy */; + }; + 8C61511C7F16907EDD83B51428CB689B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Nimble; + target = FF61C7C740C1B196A3B33F37B77DBC68 /* Nimble */; + targetProxy = 683066C568219244AEA91F2E2AB5065E /* PBXContainerItemProxy */; + }; + 96A446CA9840C9BD82FAD02405E2E22C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = SwiftTask; + target = 2DED8F1D97AD7B11107A2DF5C2FEBCD7 /* SwiftTask */; + targetProxy = 4EADF7783FF5A64433DB52605C00B2FD /* PBXContainerItemProxy */; + }; + DCF118E47792B1D75EFAD11D249DC840 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Freddy; + target = 18F2F1BE1B1A39484B66A0C0D41D55C6 /* Freddy */; + targetProxy = 44EE941BAC2FB6F90477DA65C72BFFED /* PBXContainerItemProxy */; + }; + DF0599A3C561D2C98B9C76C00120EB06 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Freddy; + target = 18F2F1BE1B1A39484B66A0C0D41D55C6 /* Freddy */; + targetProxy = A9887DC134EC0A03A91DF0523BD67FF9 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 08E07D38FCD8337813B3828E03AE2D42 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = C58B78530AECACCE9C0F19AA30F62370 /* Quick.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Quick/Quick-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Quick/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Quick/Quick.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = Quick; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 32AD5F8918CA8B349E4671410FA624C9 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 0AB1D855C50B7605DF675B33356E70FF /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 3522160BD543393AB2F619F72121D389 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9F5C636F6C5EA27DBCB9C6C3CA680826 /* Freddy.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Freddy/Freddy-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Freddy/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Freddy/Freddy.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = Freddy; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 47BEF9D903506B003EA5C2B249729489 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + ONLY_ACTIVE_ARCH = YES; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + 5AB9D94A324B8E10031AD6CFEA74566D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 4B41E2C6F9BDDB8E500A76ACD24DC2A6 /* Pods-AstroTests.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-AstroTests/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-AstroTests/Pods-AstroTests.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_AstroTests; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 6740085242C5F4612B71460E80C6F5FF /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 6802180060568B48E5AA39180D643845 /* Pods-Astro.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-Astro/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-Astro/Pods-Astro.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_Astro; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 725B8BBA5FE022465B4FD31670483A3C /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 748EA67BCFF48DE8E76C6F13965EE8E6 /* Astro.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Astro/Astro-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Astro/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Astro/Astro.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = Astro; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 75218111E718FACE36F771E8ABECDB62 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 0AB1D855C50B7605DF675B33356E70FF /* Alamofire.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 9BA46B249725A312A97956A471EC5CC3 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = C58B78530AECACCE9C0F19AA30F62370 /* Quick.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Quick/Quick-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Quick/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Quick/Quick.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = Quick; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + A598D0828FE7B74C6A5014B4A44CF0D7 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1CD70AE2B4CBC113F7A546EC5365B93E /* SwiftTask.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/SwiftTask/SwiftTask-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SwiftTask/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/SwiftTask/SwiftTask.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = SwiftTask; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + AAF678CED40D3499169D10F63CA0719E /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + CB863B3E4E2C477831A313DC75ED9EBD /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1640764CAB261E1814B1BA7709848F58 /* Pods-Astro.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-Astro/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-Astro/Pods-Astro.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_Astro; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + D136996600E31F365F763213EFA35139 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 5F08970D8469F6AC8EFF70AEF946205D /* Nimble.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Nimble/Nimble-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Nimble/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Nimble/Nimble.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = Nimble; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + D5D06A8FA8B5245381932EBEF9EDBFC0 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1CD70AE2B4CBC113F7A546EC5365B93E /* SwiftTask.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/SwiftTask/SwiftTask-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SwiftTask/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/SwiftTask/SwiftTask.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = SwiftTask; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + D7FDD52E5B79A418162D75F787ED258E /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 6FCBC236F707B2863121FD75A2B783A7 /* Nocilla.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Nocilla/Nocilla-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Nocilla/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Nocilla/Nocilla.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = Nocilla; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + DBDF5E281118544458CACC82868DA10B /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9F5C636F6C5EA27DBCB9C6C3CA680826 /* Freddy.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Freddy/Freddy-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Freddy/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Freddy/Freddy.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = Freddy; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + E09F9FDADF04D3E7A36776069400600B /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 6FCBC236F707B2863121FD75A2B783A7 /* Nocilla.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Nocilla/Nocilla-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Nocilla/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Nocilla/Nocilla.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = Nocilla; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + E66D59E1439DFF4327E732E37DF8A67D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 748EA67BCFF48DE8E76C6F13965EE8E6 /* Astro.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Astro/Astro-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Astro/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Astro/Astro.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = Astro; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + F14745E2F2D90E33DB7401B9ED7C5F16 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 5F08970D8469F6AC8EFF70AEF946205D /* Nimble.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/Nimble/Nimble-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Nimble/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/Nimble/Nimble.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = Nimble; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + FACBF971F88F235E565C68B3573ECE0D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F63DCD4CFAFE4F7967822B5A4D971100 /* Pods-AstroTests.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-AstroTests/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-AstroTests/Pods-AstroTests.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_AstroTests; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 12855E5E26887CD66AAB75AF9E177911 /* Build configuration list for PBXNativeTarget "Freddy" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + DBDF5E281118544458CACC82868DA10B /* Debug */, + 3522160BD543393AB2F619F72121D389 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 47BEF9D903506B003EA5C2B249729489 /* Debug */, + AAF678CED40D3499169D10F63CA0719E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 75218111E718FACE36F771E8ABECDB62 /* Debug */, + 32AD5F8918CA8B349E4671410FA624C9 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4655531C845E8D36877301C76982FD46 /* Build configuration list for PBXNativeTarget "Quick" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 08E07D38FCD8337813B3828E03AE2D42 /* Debug */, + 9BA46B249725A312A97956A471EC5CC3 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 5FE57A1C8E467D246D7D1BCB203A09DC /* Build configuration list for PBXNativeTarget "Nimble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F14745E2F2D90E33DB7401B9ED7C5F16 /* Debug */, + D136996600E31F365F763213EFA35139 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 846A64A59C7983583040AD4BF0DD2601 /* Build configuration list for PBXNativeTarget "Pods-Astro" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6740085242C5F4612B71460E80C6F5FF /* Debug */, + CB863B3E4E2C477831A313DC75ED9EBD /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 8F3DD3BC50DF7C47C729F63BC1A9400A /* Build configuration list for PBXNativeTarget "Pods-AstroTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FACBF971F88F235E565C68B3573ECE0D /* Debug */, + 5AB9D94A324B8E10031AD6CFEA74566D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A7D59FB4DC5C8227173E53A060B244C9 /* Build configuration list for PBXNativeTarget "SwiftTask" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + D5D06A8FA8B5245381932EBEF9EDBFC0 /* Debug */, + A598D0828FE7B74C6A5014B4A44CF0D7 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + B7A6539B2C98DBC6CF1353F53ED33581 /* Build configuration list for PBXNativeTarget "Astro" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E66D59E1439DFF4327E732E37DF8A67D /* Debug */, + 725B8BBA5FE022465B4FD31670483A3C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + CFC1B17C6D2D8BA2E80A422D19324095 /* Build configuration list for PBXNativeTarget "Nocilla" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E09F9FDADF04D3E7A36776069400600B /* Debug */, + D7FDD52E5B79A418162D75F787ED258E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; +} diff --git a/Pods/Quick/LICENSE b/Pods/Quick/LICENSE new file mode 100644 index 0000000..e900165 --- /dev/null +++ b/Pods/Quick/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2014, Quick Team + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Pods/Quick/README.md b/Pods/Quick/README.md new file mode 100644 index 0000000..bced23c --- /dev/null +++ b/Pods/Quick/README.md @@ -0,0 +1,61 @@ +![](http://f.cl.ly/items/0r1E192C1R0b2g2Q3h2w/QuickLogo_Color.png) + +Quick is a behavior-driven development framework for Swift and Objective-C. +Inspired by [RSpec](https://github.com/rspec/rspec), [Specta](https://github.com/specta/specta), and [Ginkgo](https://github.com/onsi/ginkgo). + +![](https://raw.githubusercontent.com/Quick/Assets/master/Screenshots/QuickSpec%20screenshot.png) + +```swift +// Swift + +import Quick +import Nimble + +class TableOfContentsSpec: QuickSpec { + override func spec() { + describe("the 'Documentation' directory") { + it("has everything you need to get started") { + let sections = Directory("Documentation").sections + expect(sections).to(contain("Organized Tests with Quick Examples and Example Groups")) + expect(sections).to(contain("Installing Quick")) + } + + context("if it doesn't have what you're looking for") { + it("needs to be updated") { + let you = You(awesome: true) + expect{you.submittedAnIssue}.toEventually(beTruthy()) + } + } + } + } +} +``` +#### Nimble +Quick comes together with [Nimble](https://github.com/Quick/Nimble) — a matcher framework for your tests. You can learn why `XCTAssert()` statements make your expectations unclear and how to fix that using Nimble assertions [here](./Documentation/en-us/NimbleAssertions.md). + +## Documentation + +All documentation can be found in the [Documentation folder](./Documentation), including [detailed installation instructions](./Documentation/en-us/InstallingQuick.md) for CocoaPods, Carthage, Git submodules, and more. For example, you can install Quick and [Nimble](https://github.com/Quick/Nimble) using CocoaPods by adding the following to your Podfile: + +```rb +# Podfile + +use_frameworks! + +def testing_pods + pod 'Quick' + pod 'Nimble' +end + +target 'MyTests' do + testing_pods +end + +target 'MyUITests' do + testing_pods +end +``` + +## License + +Apache 2.0 license. See the `LICENSE` file for details. diff --git a/Pods/Quick/Sources/Quick/Callsite.swift b/Pods/Quick/Sources/Quick/Callsite.swift new file mode 100644 index 0000000..53496cd --- /dev/null +++ b/Pods/Quick/Sources/Quick/Callsite.swift @@ -0,0 +1,30 @@ +import Foundation + +/** + An object encapsulating the file and line number at which + a particular example is defined. +*/ +final public class Callsite: NSObject { + /** + The absolute path of the file in which an example is defined. + */ + public let file: String + + /** + The line number on which an example is defined. + */ + public let line: UInt + + internal init(file: String, line: UInt) { + self.file = file + self.line = line + } +} + +/** + Returns a boolean indicating whether two Callsite objects are equal. + If two callsites are in the same file and on the same line, they must be equal. +*/ +public func ==(lhs: Callsite, rhs: Callsite) -> Bool { + return lhs.file == rhs.file && lhs.line == rhs.line +} diff --git a/Pods/Quick/Sources/Quick/Configuration/Configuration.swift b/Pods/Quick/Sources/Quick/Configuration/Configuration.swift new file mode 100644 index 0000000..7b8c2db --- /dev/null +++ b/Pods/Quick/Sources/Quick/Configuration/Configuration.swift @@ -0,0 +1,161 @@ +import Foundation + +/** + A closure that temporarily exposes a Configuration object within + the scope of the closure. +*/ +public typealias QuickConfigurer = (configuration: Configuration) -> () + +/** + A closure that, given metadata about an example, returns a boolean value + indicating whether that example should be run. +*/ +public typealias ExampleFilter = (example: Example) -> Bool + +/** + A configuration encapsulates various options you can use + to configure Quick's behavior. +*/ +final public class Configuration: NSObject { + internal let exampleHooks = ExampleHooks() + internal let suiteHooks = SuiteHooks() + internal var exclusionFilters: [ExampleFilter] = [{ example in + if let pending = example.filterFlags[Filter.pending] { + return pending + } else { + return false + } + }] + internal var inclusionFilters: [ExampleFilter] = [{ example in + if let focused = example.filterFlags[Filter.focused] { + return focused + } else { + return false + } + }] + + /** + Run all examples if none match the configured filters. True by default. + */ + public var runAllWhenEverythingFiltered = true + + /** + Registers an inclusion filter. + + All examples are filtered using all inclusion filters. + The remaining examples are run. If no examples remain, all examples are run. + + - parameter filter: A filter that, given an example, returns a value indicating + whether that example should be included in the examples + that are run. + */ + public func include(filter: ExampleFilter) { + inclusionFilters.append(filter) + } + + /** + Registers an exclusion filter. + + All examples that remain after being filtered by the inclusion filters are + then filtered via all exclusion filters. + + - parameter filter: A filter that, given an example, returns a value indicating + whether that example should be excluded from the examples + that are run. + */ + public func exclude(filter: ExampleFilter) { + exclusionFilters.append(filter) + } + + /** + Identical to Quick.Configuration.beforeEach, except the closure is + provided with metadata on the example that the closure is being run + prior to. + */ +#if _runtime(_ObjC) + @objc(beforeEachWithMetadata:) + public func beforeEach(closure: BeforeExampleWithMetadataClosure) { + exampleHooks.appendBefore(closure) + } +#else + public func beforeEach(closure: BeforeExampleWithMetadataClosure) { + exampleHooks.appendBefore(closure) + } +#endif + + /** + Like Quick.DSL.beforeEach, this configures Quick to execute the + given closure before each example that is run. The closure + passed to this method is executed before each example Quick runs, + globally across the test suite. You may call this method multiple + times across mulitple +[QuickConfigure configure:] methods in order + to define several closures to run before each example. + + Note that, since Quick makes no guarantee as to the order in which + +[QuickConfiguration configure:] methods are evaluated, there is no + guarantee as to the order in which beforeEach closures are evaluated + either. Mulitple beforeEach defined on a single configuration, however, + will be executed in the order they're defined. + + - parameter closure: The closure to be executed before each example + in the test suite. + */ + public func beforeEach(closure: BeforeExampleClosure) { + exampleHooks.appendBefore(closure) + } + + /** + Identical to Quick.Configuration.afterEach, except the closure + is provided with metadata on the example that the closure is being + run after. + */ +#if _runtime(_ObjC) + @objc(afterEachWithMetadata:) + public func afterEach(closure: AfterExampleWithMetadataClosure) { + exampleHooks.appendAfter(closure) + } +#else + public func afterEach(closure: AfterExampleWithMetadataClosure) { + exampleHooks.appendAfter(closure) + } +#endif + + /** + Like Quick.DSL.afterEach, this configures Quick to execute the + given closure after each example that is run. The closure + passed to this method is executed after each example Quick runs, + globally across the test suite. You may call this method multiple + times across mulitple +[QuickConfigure configure:] methods in order + to define several closures to run after each example. + + Note that, since Quick makes no guarantee as to the order in which + +[QuickConfiguration configure:] methods are evaluated, there is no + guarantee as to the order in which afterEach closures are evaluated + either. Mulitple afterEach defined on a single configuration, however, + will be executed in the order they're defined. + + - parameter closure: The closure to be executed before each example + in the test suite. + */ + public func afterEach(closure: AfterExampleClosure) { + exampleHooks.appendAfter(closure) + } + + /** + Like Quick.DSL.beforeSuite, this configures Quick to execute + the given closure prior to any and all examples that are run. + The two methods are functionally equivalent. + */ + public func beforeSuite(closure: BeforeSuiteClosure) { + suiteHooks.appendBefore(closure) + } + + /** + Like Quick.DSL.afterSuite, this configures Quick to execute + the given closure after all examples have been run. + The two methods are functionally equivalent. + */ + public func afterSuite(closure: AfterSuiteClosure) { + suiteHooks.appendAfter(closure) + } +} diff --git a/Pods/Quick/Sources/Quick/Configuration/QuickConfiguration.h b/Pods/Quick/Sources/Quick/Configuration/QuickConfiguration.h new file mode 100644 index 0000000..5646199 --- /dev/null +++ b/Pods/Quick/Sources/Quick/Configuration/QuickConfiguration.h @@ -0,0 +1,30 @@ +#import + +@class Configuration; + +/** + Subclass QuickConfiguration and override the +[QuickConfiguration configure:] + method in order to configure how Quick behaves when running specs, or to define + shared examples that are used across spec files. + */ +@interface QuickConfiguration : NSObject + +/** + This method is executed on each subclass of this class before Quick runs + any examples. You may override this method on as many subclasses as you like, but + there is no guarantee as to the order in which these methods are executed. + + You can override this method in order to: + + 1. Configure how Quick behaves, by modifying properties on the Configuration object. + Setting the same properties in several methods has undefined behavior. + + 2. Define shared examples using `sharedExamples`. + + @param configuration A mutable object that is used to configure how Quick behaves on + a framework level. For details on all the options, see the + documentation in Configuration.swift. + */ ++ (void)configure:(Configuration *)configuration; + +@end diff --git a/Pods/Quick/Sources/Quick/Configuration/QuickConfiguration.m b/Pods/Quick/Sources/Quick/Configuration/QuickConfiguration.m new file mode 100644 index 0000000..937b818 --- /dev/null +++ b/Pods/Quick/Sources/Quick/Configuration/QuickConfiguration.m @@ -0,0 +1,83 @@ +#import "QuickConfiguration.h" +#import "World.h" +#import + +typedef void (^QCKClassEnumerationBlock)(Class klass); + +/** + Finds all direct subclasses of the given class and passes them to the block provided. + The classes are iterated over in the order that objc_getClassList returns them. + + @param klass The base class to find subclasses of. + @param block A block that takes a Class. This block will be executed once for each subclass of klass. + */ +void qck_enumerateSubclasses(Class klass, QCKClassEnumerationBlock block) { + Class *classes = NULL; + int classesCount = objc_getClassList(NULL, 0); + + if (classesCount > 0) { + classes = (Class *)calloc(sizeof(Class), classesCount); + classesCount = objc_getClassList(classes, classesCount); + + Class subclass, superclass; + for(int i = 0; i < classesCount; i++) { + subclass = classes[i]; + superclass = class_getSuperclass(subclass); + if (superclass == klass && block) { + block(subclass); + } + } + + free(classes); + } +} + +@implementation QuickConfiguration + +#pragma mark - Object Lifecycle + +/** + QuickConfiguration is not meant to be instantiated; it merely provides a hook + for users to configure how Quick behaves. Raise an exception if an instance of + QuickConfiguration is created. + */ +- (instancetype)init { + NSString *className = NSStringFromClass([self class]); + NSString *selectorName = NSStringFromSelector(@selector(configure:)); + [NSException raise:NSInternalInconsistencyException + format:@"%@ is not meant to be instantiated; " + @"subclass %@ and override %@ to configure Quick.", + className, className, selectorName]; + return nil; +} + +#pragma mark - NSObject Overrides + +/** + Hook into when QuickConfiguration is initialized in the runtime in order to + call +[QuickConfiguration configure:] on each of its subclasses. + */ ++ (void)initialize { + // Only enumerate over the subclasses of QuickConfiguration, not any of its subclasses. + if ([self class] == [QuickConfiguration class]) { + + // Only enumerate over subclasses once, even if +[QuickConfiguration initialize] + // were to be called several times. This is necessary because +[QuickSpec initialize] + // manually calls +[QuickConfiguration initialize]. + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + qck_enumerateSubclasses([QuickConfiguration class], ^(__unsafe_unretained Class klass) { + [[World sharedWorld] configure:^(Configuration *configuration) { + [klass configure:configuration]; + }]; + }); + [[World sharedWorld] finalizeConfiguration]; + }); + } +} + +#pragma mark - Public Interface + ++ (void)configure:(Configuration *)configuration { } + +@end diff --git a/Pods/Quick/Sources/Quick/DSL/DSL.swift b/Pods/Quick/Sources/Quick/DSL/DSL.swift new file mode 100644 index 0000000..bc0e0b4 --- /dev/null +++ b/Pods/Quick/Sources/Quick/DSL/DSL.swift @@ -0,0 +1,227 @@ +/** + Defines a closure to be run prior to any examples in the test suite. + You may define an unlimited number of these closures, but there is no + guarantee as to the order in which they're run. + + If the test suite crashes before the first example is run, this closure + will not be executed. + + - parameter closure: The closure to be run prior to any examples in the test suite. +*/ +public func beforeSuite(closure: BeforeSuiteClosure) { + World.sharedWorld.beforeSuite(closure) +} + +/** + Defines a closure to be run after all of the examples in the test suite. + You may define an unlimited number of these closures, but there is no + guarantee as to the order in which they're run. + + If the test suite crashes before all examples are run, this closure + will not be executed. + + - parameter closure: The closure to be run after all of the examples in the test suite. +*/ +public func afterSuite(closure: AfterSuiteClosure) { + World.sharedWorld.afterSuite(closure) +} + +/** + Defines a group of shared examples. These examples can be re-used in several locations + by using the `itBehavesLike` function. + + - parameter name: The name of the shared example group. This must be unique across all shared example + groups defined in a test suite. + - parameter closure: A closure containing the examples. This behaves just like an example group defined + using `describe` or `context`--the closure may contain any number of `beforeEach` + and `afterEach` closures, as well as any number of examples (defined using `it`). +*/ +public func sharedExamples(name: String, closure: () -> ()) { + World.sharedWorld.sharedExamples(name, closure: { (NSDictionary) in closure() }) +} + +/** + Defines a group of shared examples. These examples can be re-used in several locations + by using the `itBehavesLike` function. + + - parameter name: The name of the shared example group. This must be unique across all shared example + groups defined in a test suite. + - parameter closure: A closure containing the examples. This behaves just like an example group defined + using `describe` or `context`--the closure may contain any number of `beforeEach` + and `afterEach` closures, as well as any number of examples (defined using `it`). + + The closure takes a SharedExampleContext as an argument. This context is a function + that can be executed to retrieve parameters passed in via an `itBehavesLike` function. +*/ +public func sharedExamples(name: String, closure: SharedExampleClosure) { + World.sharedWorld.sharedExamples(name, closure: closure) +} + +/** + Defines an example group. Example groups are logical groupings of examples. + Example groups can share setup and teardown code. + + - parameter description: An arbitrary string describing the example group. + - parameter closure: A closure that can contain other examples. + - parameter flags: A mapping of string keys to booleans that can be used to filter examples or example groups. +*/ +public func describe(description: String, flags: FilterFlags = [:], closure: () -> ()) { + World.sharedWorld.describe(description, flags: flags, closure: closure) +} + +/** + Defines an example group. Equivalent to `describe`. +*/ +public func context(description: String, flags: FilterFlags = [:], closure: () -> ()) { + World.sharedWorld.context(description, flags: flags, closure: closure) +} + +/** + Defines a closure to be run prior to each example in the current example + group. This closure is not run for pending or otherwise disabled examples. + An example group may contain an unlimited number of beforeEach. They'll be + run in the order they're defined, but you shouldn't rely on that behavior. + + - parameter closure: The closure to be run prior to each example. +*/ +public func beforeEach(closure: BeforeExampleClosure) { + World.sharedWorld.beforeEach(closure) +} + +/** + Identical to Quick.DSL.beforeEach, except the closure is provided with + metadata on the example that the closure is being run prior to. +*/ +public func beforeEach(closure: BeforeExampleWithMetadataClosure) { + World.sharedWorld.beforeEach(closure: closure) +} + +/** + Defines a closure to be run after each example in the current example + group. This closure is not run for pending or otherwise disabled examples. + An example group may contain an unlimited number of afterEach. They'll be + run in the order they're defined, but you shouldn't rely on that behavior. + + - parameter closure: The closure to be run after each example. +*/ +public func afterEach(closure: AfterExampleClosure) { + World.sharedWorld.afterEach(closure) +} + +/** + Identical to Quick.DSL.afterEach, except the closure is provided with + metadata on the example that the closure is being run after. +*/ +public func afterEach(closure: AfterExampleWithMetadataClosure) { + World.sharedWorld.afterEach(closure: closure) +} + +/** + Defines an example. Examples use assertions to demonstrate how code should + behave. These are like "tests" in XCTest. + + - parameter description: An arbitrary string describing what the example is meant to specify. + - parameter closure: A closure that can contain assertions. + - parameter flags: A mapping of string keys to booleans that can be used to filter examples or example groups. + Empty by default. + - parameter file: The absolute path to the file containing the example. A sensible default is provided. + - parameter line: The line containing the example. A sensible default is provided. +*/ +public func it(description: String, flags: FilterFlags = [:], file: String = #file, line: UInt = #line, closure: () -> ()) { + World.sharedWorld.it(description, flags: flags, file: file, line: line, closure: closure) +} + +/** + Inserts the examples defined using a `sharedExamples` function into the current example group. + The shared examples are executed at this location, as if they were written out manually. + + - parameter name: The name of the shared examples group to be executed. This must be identical to the + name of a shared examples group defined using `sharedExamples`. If there are no shared + examples that match the name given, an exception is thrown and the test suite will crash. + - parameter flags: A mapping of string keys to booleans that can be used to filter examples or example groups. + Empty by default. + - parameter file: The absolute path to the file containing the current example group. A sensible default is provided. + - parameter line: The line containing the current example group. A sensible default is provided. +*/ +public func itBehavesLike(name: String, flags: FilterFlags = [:], file: String = #file, line: UInt = #line) { + itBehavesLike(name, flags: flags, file: file, line: line, sharedExampleContext: { return [:] }) +} + +/** + Inserts the examples defined using a `sharedExamples` function into the current example group. + The shared examples are executed at this location, as if they were written out manually. + This function also passes those shared examples a context that can be evaluated to give the shared + examples extra information on the subject of the example. + + - parameter name: The name of the shared examples group to be executed. This must be identical to the + name of a shared examples group defined using `sharedExamples`. If there are no shared + examples that match the name given, an exception is thrown and the test suite will crash. + - parameter sharedExampleContext: A closure that, when evaluated, returns key-value pairs that provide the + shared examples with extra information on the subject of the example. + - parameter flags: A mapping of string keys to booleans that can be used to filter examples or example groups. + Empty by default. + - parameter file: The absolute path to the file containing the current example group. A sensible default is provided. + - parameter line: The line containing the current example group. A sensible default is provided. +*/ +public func itBehavesLike(name: String, flags: FilterFlags = [:], file: String = #file, line: UInt = #line, sharedExampleContext: SharedExampleContext) { + World.sharedWorld.itBehavesLike(name, sharedExampleContext: sharedExampleContext, flags: flags, file: file, line: line) +} + +/** + Defines an example or example group that should not be executed. Use `pending` to temporarily disable + examples or groups that should not be run yet. + + - parameter description: An arbitrary string describing the example or example group. + - parameter closure: A closure that will not be evaluated. +*/ +public func pending(description: String, closure: () -> ()) { + World.sharedWorld.pending(description, closure: closure) +} + +/** + Use this to quickly mark a `describe` closure as pending. + This disables all examples within the closure. +*/ +public func xdescribe(description: String, flags: FilterFlags, closure: () -> ()) { + World.sharedWorld.xdescribe(description, flags: flags, closure: closure) +} + +/** + Use this to quickly mark a `context` closure as pending. + This disables all examples within the closure. +*/ +public func xcontext(description: String, flags: FilterFlags, closure: () -> ()) { + xdescribe(description, flags: flags, closure: closure) +} + +/** + Use this to quickly mark an `it` closure as pending. + This disables the example and ensures the code within the closure is never run. +*/ +public func xit(description: String, flags: FilterFlags = [:], file: String = #file, line: UInt = #line, closure: () -> ()) { + World.sharedWorld.xit(description, flags: flags, file: file, line: line, closure: closure) +} + +/** + Use this to quickly focus a `describe` closure, focusing the examples in the closure. + If any examples in the test suite are focused, only those examples are executed. + This trumps any explicitly focused or unfocused examples within the closure--they are all treated as focused. +*/ +public func fdescribe(description: String, flags: FilterFlags = [:], closure: () -> ()) { + World.sharedWorld.fdescribe(description, flags: flags, closure: closure) +} + +/** + Use this to quickly focus a `context` closure. Equivalent to `fdescribe`. +*/ +public func fcontext(description: String, flags: FilterFlags = [:], closure: () -> ()) { + fdescribe(description, flags: flags, closure: closure) +} + +/** + Use this to quickly focus an `it` closure, focusing the example. + If any examples in the test suite are focused, only those examples are executed. +*/ +public func fit(description: String, flags: FilterFlags = [:], file: String = #file, line: UInt = #line, closure: () -> ()) { + World.sharedWorld.fit(description, flags: flags, file: file, line: line, closure: closure) +} diff --git a/Pods/Quick/Sources/Quick/DSL/QCKDSL.h b/Pods/Quick/Sources/Quick/DSL/QCKDSL.h new file mode 100644 index 0000000..c5f3152 --- /dev/null +++ b/Pods/Quick/Sources/Quick/DSL/QCKDSL.h @@ -0,0 +1,234 @@ +#import + +@class ExampleMetadata; + +/** + Provides a hook for Quick to be configured before any examples are run. + Within this scope, override the +[QuickConfiguration configure:] method + to set properties on a configuration object to customize Quick behavior. + For details, see the documentation for Configuraiton.swift. + + @param name The name of the configuration class. Like any Objective-C + class name, this must be unique to the current runtime + environment. + */ +#define QuickConfigurationBegin(name) \ + @interface name : QuickConfiguration; @end \ + @implementation name \ + + +/** + Marks the end of a Quick configuration. + Make sure you put this after `QuickConfigurationBegin`. + */ +#define QuickConfigurationEnd \ + @end \ + + +/** + Defines a new QuickSpec. Define examples and example groups within the space + between this and `QuickSpecEnd`. + + @param name The name of the spec class. Like any Objective-C class name, this + must be unique to the current runtime environment. + */ +#define QuickSpecBegin(name) \ + @interface name : QuickSpec; @end \ + @implementation name \ + - (void)spec { \ + + +/** + Marks the end of a QuickSpec. Make sure you put this after `QuickSpecBegin`. + */ +#define QuickSpecEnd \ + } \ + @end \ + +typedef NSDictionary *(^QCKDSLSharedExampleContext)(void); +typedef void (^QCKDSLSharedExampleBlock)(QCKDSLSharedExampleContext); +typedef void (^QCKDSLEmptyBlock)(void); +typedef void (^QCKDSLExampleMetadataBlock)(ExampleMetadata *exampleMetadata); + +#define QUICK_EXPORT FOUNDATION_EXPORT + +QUICK_EXPORT void qck_beforeSuite(QCKDSLEmptyBlock closure); +QUICK_EXPORT void qck_afterSuite(QCKDSLEmptyBlock closure); +QUICK_EXPORT void qck_sharedExamples(NSString *name, QCKDSLSharedExampleBlock closure); +QUICK_EXPORT void qck_describe(NSString *description, QCKDSLEmptyBlock closure); +QUICK_EXPORT void qck_context(NSString *description, QCKDSLEmptyBlock closure); +QUICK_EXPORT void qck_beforeEach(QCKDSLEmptyBlock closure); +QUICK_EXPORT void qck_beforeEachWithMetadata(QCKDSLExampleMetadataBlock closure); +QUICK_EXPORT void qck_afterEach(QCKDSLEmptyBlock closure); +QUICK_EXPORT void qck_afterEachWithMetadata(QCKDSLExampleMetadataBlock closure); +QUICK_EXPORT void qck_pending(NSString *description, QCKDSLEmptyBlock closure); +QUICK_EXPORT void qck_xdescribe(NSString *description, QCKDSLEmptyBlock closure); +QUICK_EXPORT void qck_xcontext(NSString *description, QCKDSLEmptyBlock closure); +QUICK_EXPORT void qck_fdescribe(NSString *description, QCKDSLEmptyBlock closure); +QUICK_EXPORT void qck_fcontext(NSString *description, QCKDSLEmptyBlock closure); + +#ifndef QUICK_DISABLE_SHORT_SYNTAX +/** + Defines a closure to be run prior to any examples in the test suite. + You may define an unlimited number of these closures, but there is no + guarantee as to the order in which they're run. + + If the test suite crashes before the first example is run, this closure + will not be executed. + + @param closure The closure to be run prior to any examples in the test suite. + */ +static inline void beforeSuite(QCKDSLEmptyBlock closure) { + qck_beforeSuite(closure); +} + + +/** + Defines a closure to be run after all of the examples in the test suite. + You may define an unlimited number of these closures, but there is no + guarantee as to the order in which they're run. + + If the test suite crashes before all examples are run, this closure + will not be executed. + + @param closure The closure to be run after all of the examples in the test suite. + */ +static inline void afterSuite(QCKDSLEmptyBlock closure) { + qck_afterSuite(closure); +} + +/** + Defines a group of shared examples. These examples can be re-used in several locations + by using the `itBehavesLike` function. + + @param name The name of the shared example group. This must be unique across all shared example + groups defined in a test suite. + @param closure A closure containing the examples. This behaves just like an example group defined + using `describe` or `context`--the closure may contain any number of `beforeEach` + and `afterEach` closures, as well as any number of examples (defined using `it`). + */ +static inline void sharedExamples(NSString *name, QCKDSLSharedExampleBlock closure) { + qck_sharedExamples(name, closure); +} + +/** + Defines an example group. Example groups are logical groupings of examples. + Example groups can share setup and teardown code. + + @param description An arbitrary string describing the example group. + @param closure A closure that can contain other examples. + */ +static inline void describe(NSString *description, QCKDSLEmptyBlock closure) { + qck_describe(description, closure); +} + +/** + Defines an example group. Equivalent to `describe`. + */ +static inline void context(NSString *description, QCKDSLEmptyBlock closure) { + qck_context(description, closure); +} + +/** + Defines a closure to be run prior to each example in the current example + group. This closure is not run for pending or otherwise disabled examples. + An example group may contain an unlimited number of beforeEach. They'll be + run in the order they're defined, but you shouldn't rely on that behavior. + + @param closure The closure to be run prior to each example. + */ +static inline void beforeEach(QCKDSLEmptyBlock closure) { + qck_beforeEach(closure); +} + +/** + Identical to QCKDSL.beforeEach, except the closure is provided with + metadata on the example that the closure is being run prior to. + */ +static inline void beforeEachWithMetadata(QCKDSLExampleMetadataBlock closure) { + qck_beforeEachWithMetadata(closure); +} + +/** + Defines a closure to be run after each example in the current example + group. This closure is not run for pending or otherwise disabled examples. + An example group may contain an unlimited number of afterEach. They'll be + run in the order they're defined, but you shouldn't rely on that behavior. + + @param closure The closure to be run after each example. + */ +static inline void afterEach(QCKDSLEmptyBlock closure) { + qck_afterEach(closure); +} + +/** + Identical to QCKDSL.afterEach, except the closure is provided with + metadata on the example that the closure is being run after. + */ +static inline void afterEachWithMetadata(QCKDSLExampleMetadataBlock closure) { + qck_afterEachWithMetadata(closure); +} + +/** + Defines an example or example group that should not be executed. Use `pending` to temporarily disable + examples or groups that should not be run yet. + + @param description An arbitrary string describing the example or example group. + @param closure A closure that will not be evaluated. + */ +static inline void pending(NSString *description, QCKDSLEmptyBlock closure) { + qck_pending(description, closure); +} + +/** + Use this to quickly mark a `describe` block as pending. + This disables all examples within the block. + */ +static inline void xdescribe(NSString *description, QCKDSLEmptyBlock closure) { + qck_xdescribe(description, closure); +} + +/** + Use this to quickly mark a `context` block as pending. + This disables all examples within the block. + */ +static inline void xcontext(NSString *description, QCKDSLEmptyBlock closure) { + qck_xcontext(description, closure); +} + +/** + Use this to quickly focus a `describe` block, focusing the examples in the block. + If any examples in the test suite are focused, only those examples are executed. + This trumps any explicitly focused or unfocused examples within the block--they are all treated as focused. + */ +static inline void fdescribe(NSString *description, QCKDSLEmptyBlock closure) { + qck_fdescribe(description, closure); +} + +/** + Use this to quickly focus a `context` block. Equivalent to `fdescribe`. + */ +static inline void fcontext(NSString *description, QCKDSLEmptyBlock closure) { + qck_fcontext(description, closure); +} + +#define it qck_it +#define xit qck_xit +#define fit qck_fit +#define itBehavesLike qck_itBehavesLike +#define xitBehavesLike qck_xitBehavesLike +#define fitBehavesLike qck_fitBehavesLike +#endif + +#define qck_it qck_it_builder(@{}, @(__FILE__), __LINE__) +#define qck_xit qck_it_builder(@{Filter.pending: @YES}, @(__FILE__), __LINE__) +#define qck_fit qck_it_builder(@{Filter.focused: @YES}, @(__FILE__), __LINE__) +#define qck_itBehavesLike qck_itBehavesLike_builder(@{}, @(__FILE__), __LINE__) +#define qck_xitBehavesLike qck_itBehavesLike_builder(@{Filter.pending: @YES}, @(__FILE__), __LINE__) +#define qck_fitBehavesLike qck_itBehavesLike_builder(@{Filter.focused: @YES}, @(__FILE__), __LINE__) + +typedef void (^QCKItBlock)(NSString *description, QCKDSLEmptyBlock closure); +typedef void (^QCKItBehavesLikeBlock)(NSString *description, QCKDSLSharedExampleContext context); + +QUICK_EXPORT QCKItBlock qck_it_builder(NSDictionary *flags, NSString *file, NSUInteger line); +QUICK_EXPORT QCKItBehavesLikeBlock qck_itBehavesLike_builder(NSDictionary *flags, NSString *file, NSUInteger line); diff --git a/Pods/Quick/Sources/Quick/DSL/QCKDSL.m b/Pods/Quick/Sources/Quick/DSL/QCKDSL.m new file mode 100644 index 0000000..10e8a3d --- /dev/null +++ b/Pods/Quick/Sources/Quick/DSL/QCKDSL.m @@ -0,0 +1,79 @@ +#import "QCKDSL.h" +#import "World.h" +#import "World+DSL.h" + +void qck_beforeSuite(QCKDSLEmptyBlock closure) { + [[World sharedWorld] beforeSuite:closure]; +} + +void qck_afterSuite(QCKDSLEmptyBlock closure) { + [[World sharedWorld] afterSuite:closure]; +} + +void qck_sharedExamples(NSString *name, QCKDSLSharedExampleBlock closure) { + [[World sharedWorld] sharedExamples:name closure:closure]; +} + +void qck_describe(NSString *description, QCKDSLEmptyBlock closure) { + [[World sharedWorld] describe:description flags:@{} closure:closure]; +} + +void qck_context(NSString *description, QCKDSLEmptyBlock closure) { + qck_describe(description, closure); +} + +void qck_beforeEach(QCKDSLEmptyBlock closure) { + [[World sharedWorld] beforeEach:closure]; +} + +void qck_beforeEachWithMetadata(QCKDSLExampleMetadataBlock closure) { + [[World sharedWorld] beforeEachWithMetadata:closure]; +} + +void qck_afterEach(QCKDSLEmptyBlock closure) { + [[World sharedWorld] afterEach:closure]; +} + +void qck_afterEachWithMetadata(QCKDSLExampleMetadataBlock closure) { + [[World sharedWorld] afterEachWithMetadata:closure]; +} + +QCKItBlock qck_it_builder(NSDictionary *flags, NSString *file, NSUInteger line) { + return ^(NSString *description, QCKDSLEmptyBlock closure) { + [[World sharedWorld] itWithDescription:description + flags:flags + file:file + line:line + closure:closure]; + }; +} + +QCKItBehavesLikeBlock qck_itBehavesLike_builder(NSDictionary *flags, NSString *file, NSUInteger line) { + return ^(NSString *name, QCKDSLSharedExampleContext context) { + [[World sharedWorld] itBehavesLikeSharedExampleNamed:name + sharedExampleContext:context + flags:flags + file:file + line:line]; + }; +} + +void qck_pending(NSString *description, QCKDSLEmptyBlock closure) { + [[World sharedWorld] pending:description closure:closure]; +} + +void qck_xdescribe(NSString *description, QCKDSLEmptyBlock closure) { + [[World sharedWorld] xdescribe:description flags:@{} closure:closure]; +} + +void qck_xcontext(NSString *description, QCKDSLEmptyBlock closure) { + qck_xdescribe(description, closure); +} + +void qck_fdescribe(NSString *description, QCKDSLEmptyBlock closure) { + [[World sharedWorld] fdescribe:description flags:@{} closure:closure]; +} + +void qck_fcontext(NSString *description, QCKDSLEmptyBlock closure) { + qck_fdescribe(description, closure); +} diff --git a/Pods/Quick/Sources/Quick/DSL/World+DSL.h b/Pods/Quick/Sources/Quick/DSL/World+DSL.h new file mode 100644 index 0000000..a3b8524 --- /dev/null +++ b/Pods/Quick/Sources/Quick/DSL/World+DSL.h @@ -0,0 +1,20 @@ +#import + +@interface World (SWIFT_EXTENSION(Quick)) +- (void)beforeSuite:(void (^ __nonnull)(void))closure; +- (void)afterSuite:(void (^ __nonnull)(void))closure; +- (void)sharedExamples:(NSString * __nonnull)name closure:(void (^ __nonnull)(NSDictionary * __nonnull (^ __nonnull)(void)))closure; +- (void)describe:(NSString * __nonnull)description flags:(NSDictionary * __nonnull)flags closure:(void (^ __nonnull)(void))closure; +- (void)context:(NSString * __nonnull)description flags:(NSDictionary * __nonnull)flags closure:(void (^ __nonnull)(void))closure; +- (void)fdescribe:(NSString * __nonnull)description flags:(NSDictionary * __nonnull)flags closure:(void (^ __nonnull)(void))closure; +- (void)xdescribe:(NSString * __nonnull)description flags:(NSDictionary * __nonnull)flags closure:(void (^ __nonnull)(void))closure; +- (void)beforeEach:(void (^ __nonnull)(void))closure; +- (void)beforeEachWithMetadata:(void (^ __nonnull)(ExampleMetadata * __nonnull))closure; +- (void)afterEach:(void (^ __nonnull)(void))closure; +- (void)afterEachWithMetadata:(void (^ __nonnull)(ExampleMetadata * __nonnull))closure; +- (void)itWithDescription:(NSString * __nonnull)description flags:(NSDictionary * __nonnull)flags file:(NSString * __nonnull)file line:(NSUInteger)line closure:(void (^ __nonnull)(void))closure; +- (void)fitWithDescription:(NSString * __nonnull)description flags:(NSDictionary * __nonnull)flags file:(NSString * __nonnull)file line:(NSUInteger)line closure:(void (^ __nonnull)(void))closure; +- (void)xitWithDescription:(NSString * __nonnull)description flags:(NSDictionary * __nonnull)flags file:(NSString * __nonnull)file line:(NSUInteger)line closure:(void (^ __nonnull)(void))closure; +- (void)itBehavesLikeSharedExampleNamed:(NSString * __nonnull)name sharedExampleContext:(NSDictionary * __nonnull (^ __nonnull)(void))sharedExampleContext flags:(NSDictionary * __nonnull)flags file:(NSString * __nonnull)file line:(NSUInteger)line; +- (void)pending:(NSString * __nonnull)description closure:(void (^ __nonnull)(void))closure; +@end diff --git a/Pods/Quick/Sources/Quick/DSL/World+DSL.swift b/Pods/Quick/Sources/Quick/DSL/World+DSL.swift new file mode 100644 index 0000000..3b9a9be --- /dev/null +++ b/Pods/Quick/Sources/Quick/DSL/World+DSL.swift @@ -0,0 +1,169 @@ +import Foundation + +/** + Adds methods to World to support top-level DSL functions (Swift) and + macros (Objective-C). These functions map directly to the DSL that test + writers use in their specs. +*/ +extension World { + internal func beforeSuite(closure: BeforeSuiteClosure) { + suiteHooks.appendBefore(closure) + } + + internal func afterSuite(closure: AfterSuiteClosure) { + suiteHooks.appendAfter(closure) + } + + internal func sharedExamples(name: String, closure: SharedExampleClosure) { + registerSharedExample(name, closure: closure) + } + + internal func describe(description: String, flags: FilterFlags, closure: () -> ()) { + guard currentExampleMetadata == nil else { + raiseError("'describe' cannot be used inside '\(currentPhase)', 'describe' may only be used inside 'context' or 'describe'. ") + } + guard currentExampleGroup != nil else { + raiseError("Error: example group was not created by its parent QuickSpec spec. Check that describe() or context() was used in QuickSpec.spec() and not a more general context (i.e. an XCTestCase test)") + } + let group = ExampleGroup(description: description, flags: flags) + currentExampleGroup.appendExampleGroup(group) + performWithCurrentExampleGroup(group, closure: closure) + } + + internal func context(description: String, flags: FilterFlags, closure: () -> ()) { + guard currentExampleMetadata == nil else { + raiseError("'context' cannot be used inside '\(currentPhase)', 'context' may only be used inside 'context' or 'describe'. ") + } + self.describe(description, flags: flags, closure: closure) + } + + internal func fdescribe(description: String, flags: FilterFlags, closure: () -> ()) { + var focusedFlags = flags + focusedFlags[Filter.focused] = true + self.describe(description, flags: focusedFlags, closure: closure) + } + + internal func xdescribe(description: String, flags: FilterFlags, closure: () -> ()) { + var pendingFlags = flags + pendingFlags[Filter.pending] = true + self.describe(description, flags: pendingFlags, closure: closure) + } + + internal func beforeEach(closure: BeforeExampleClosure) { + guard currentExampleMetadata == nil else { + raiseError("'beforeEach' cannot be used inside '\(currentPhase)', 'beforeEach' may only be used inside 'context' or 'describe'. ") + } + currentExampleGroup.hooks.appendBefore(closure) + } + +#if _runtime(_ObjC) + @objc(beforeEachWithMetadata:) + internal func beforeEach(closure closure: BeforeExampleWithMetadataClosure) { + currentExampleGroup.hooks.appendBefore(closure) + } +#else + internal func beforeEach(closure closure: BeforeExampleWithMetadataClosure) { + currentExampleGroup.hooks.appendBefore(closure) + } +#endif + + internal func afterEach(closure: AfterExampleClosure) { + guard currentExampleMetadata == nil else { + raiseError("'afterEach' cannot be used inside '\(currentPhase)', 'afterEach' may only be used inside 'context' or 'describe'. ") + } + currentExampleGroup.hooks.appendAfter(closure) + } + +#if _runtime(_ObjC) + @objc(afterEachWithMetadata:) + internal func afterEach(closure closure: AfterExampleWithMetadataClosure) { + currentExampleGroup.hooks.appendAfter(closure) + } +#else + internal func afterEach(closure closure: AfterExampleWithMetadataClosure) { + currentExampleGroup.hooks.appendAfter(closure) + } +#endif + + internal func it(description: String, flags: FilterFlags, file: String, line: UInt, closure: () -> ()) { + if beforesCurrentlyExecuting { + raiseError("'it' cannot be used inside 'beforeEach', 'it' may only be used inside 'context' or 'describe'. ") + } + if aftersCurrentlyExecuting { + raiseError("'it' cannot be used inside 'afterEach', 'it' may only be used inside 'context' or 'describe'. ") + } + guard currentExampleMetadata == nil else { + raiseError("'it' cannot be used inside 'it', 'it' may only be used inside 'context' or 'describe'. ") + } + let callsite = Callsite(file: file, line: line) + let example = Example(description: description, callsite: callsite, flags: flags, closure: closure) + currentExampleGroup.appendExample(example) + } + + internal func fit(description: String, flags: FilterFlags, file: String, line: UInt, closure: () -> ()) { + var focusedFlags = flags + focusedFlags[Filter.focused] = true + self.it(description, flags: focusedFlags, file: file, line: line, closure: closure) + } + + internal func xit(description: String, flags: FilterFlags, file: String, line: UInt, closure: () -> ()) { + var pendingFlags = flags + pendingFlags[Filter.pending] = true + self.it(description, flags: pendingFlags, file: file, line: line, closure: closure) + } + + internal func itBehavesLike(name: String, sharedExampleContext: SharedExampleContext, flags: FilterFlags, file: String, line: UInt) { + guard currentExampleMetadata == nil else { + raiseError("'itBehavesLike' cannot be used inside '\(currentPhase)', 'itBehavesLike' may only be used inside 'context' or 'describe'. ") + } + let callsite = Callsite(file: file, line: line) + let closure = World.sharedWorld.sharedExample(name) + + let group = ExampleGroup(description: name, flags: flags) + currentExampleGroup.appendExampleGroup(group) + performWithCurrentExampleGroup(group) { + closure(sharedExampleContext) + } + + group.walkDownExamples { (example: Example) in + example.isSharedExample = true + example.callsite = callsite + } + } + +#if _runtime(_ObjC) + @objc(itWithDescription:flags:file:line:closure:) + private func objc_it(description: String, flags: FilterFlags, file: String, line: UInt, closure: () -> ()) { + it(description, flags: flags, file: file, line: line, closure: closure) + } + + @objc(fitWithDescription:flags:file:line:closure:) + private func objc_fit(description: String, flags: FilterFlags, file: String, line: UInt, closure: () -> ()) { + fit(description, flags: flags, file: file, line: line, closure: closure) + } + + @objc(xitWithDescription:flags:file:line:closure:) + private func objc_xit(description: String, flags: FilterFlags, file: String, line: UInt, closure: () -> ()) { + xit(description, flags: flags, file: file, line: line, closure: closure) + } + + @objc(itBehavesLikeSharedExampleNamed:sharedExampleContext:flags:file:line:) + private func objc_itBehavesLike(name: String, sharedExampleContext: SharedExampleContext, flags: FilterFlags, file: String, line: UInt) { + itBehavesLike(name, sharedExampleContext: sharedExampleContext, flags: flags, file: file, line: line) + } +#endif + + internal func pending(description: String, closure: () -> ()) { + print("Pending: \(description)") + } + + private var currentPhase: String { + if beforesCurrentlyExecuting { + return "beforeEach" + } else if aftersCurrentlyExecuting { + return "afterEach" + } + + return "it" + } +} diff --git a/Pods/Quick/Sources/Quick/ErrorUtility.swift b/Pods/Quick/Sources/Quick/ErrorUtility.swift new file mode 100644 index 0000000..3c4035a --- /dev/null +++ b/Pods/Quick/Sources/Quick/ErrorUtility.swift @@ -0,0 +1,10 @@ +import Foundation + +@noreturn internal func raiseError(message: String) { +#if _runtime(_ObjC) + NSException(name: NSInternalInconsistencyException, reason: message, userInfo: nil).raise() +#endif + + // This won't be reached when ObjC is available and the exception above is raisd + fatalError(message) +} diff --git a/Pods/Quick/Sources/Quick/Example.swift b/Pods/Quick/Sources/Quick/Example.swift new file mode 100644 index 0000000..8929525 --- /dev/null +++ b/Pods/Quick/Sources/Quick/Example.swift @@ -0,0 +1,113 @@ +import Foundation + +private var numberOfExamplesRun = 0 + +/** + Examples, defined with the `it` function, use assertions to + demonstrate how code should behave. These are like "tests" in XCTest. +*/ +final public class Example: NSObject { + /** + A boolean indicating whether the example is a shared example; + i.e.: whether it is an example defined with `itBehavesLike`. + */ + public var isSharedExample = false + + /** + The site at which the example is defined. + This must be set correctly in order for Xcode to highlight + the correct line in red when reporting a failure. + */ + public var callsite: Callsite + + weak internal var group: ExampleGroup? + + private let internalDescription: String + private let closure: () -> () + private let flags: FilterFlags + + internal init(description: String, callsite: Callsite, flags: FilterFlags, closure: () -> ()) { + self.internalDescription = description + self.closure = closure + self.callsite = callsite + self.flags = flags + } + + public override var description: String { + return internalDescription + } + + /** + The example name. A name is a concatenation of the name of + the example group the example belongs to, followed by the + description of the example itself. + + The example name is used to generate a test method selector + to be displayed in Xcode's test navigator. + */ + public var name: String { + switch group!.name { + case .Some(let groupName): return "\(groupName), \(description)" + case .None: return description + } + } + + /** + Executes the example closure, as well as all before and after + closures defined in the its surrounding example groups. + */ + public func run() { + let world = World.sharedWorld + + if numberOfExamplesRun == 0 { + world.suiteHooks.executeBefores() + } + + let exampleMetadata = ExampleMetadata(example: self, exampleIndex: numberOfExamplesRun) + world.currentExampleMetadata = exampleMetadata + + world.exampleHooks.executeBefores(exampleMetadata) + group!.phase = .BeforesExecuting + for before in group!.befores { + before(exampleMetadata: exampleMetadata) + } + group!.phase = .BeforesFinished + + closure() + + group!.phase = .AftersExecuting + for after in group!.afters { + after(exampleMetadata: exampleMetadata) + } + group!.phase = .AftersFinished + world.exampleHooks.executeAfters(exampleMetadata) + + numberOfExamplesRun += 1 + + if !world.isRunningAdditionalSuites && numberOfExamplesRun >= world.includedExampleCount { + world.suiteHooks.executeAfters() + } + } + + /** + Evaluates the filter flags set on this example and on the example groups + this example belongs to. Flags set on the example are trumped by flags on + the example group it belongs to. Flags on inner example groups are trumped + by flags on outer example groups. + */ + internal var filterFlags: FilterFlags { + var aggregateFlags = flags + for (key, value) in group!.filterFlags { + aggregateFlags[key] = value + } + return aggregateFlags + } +} + +/** + Returns a boolean indicating whether two Example objects are equal. + If two examples are defined at the exact same callsite, they must be equal. +*/ +public func ==(lhs: Example, rhs: Example) -> Bool { + return lhs.callsite == rhs.callsite +} diff --git a/Pods/Quick/Sources/Quick/ExampleGroup.swift b/Pods/Quick/Sources/Quick/ExampleGroup.swift new file mode 100644 index 0000000..cf2b983 --- /dev/null +++ b/Pods/Quick/Sources/Quick/ExampleGroup.swift @@ -0,0 +1,105 @@ +import Foundation + +/** + Example groups are logical groupings of examples, defined with + the `describe` and `context` functions. Example groups can share + setup and teardown code. +*/ +final public class ExampleGroup: NSObject { + weak internal var parent: ExampleGroup? + internal let hooks = ExampleHooks() + + internal var phase: HooksPhase = .NothingExecuted + + private let internalDescription: String + private let flags: FilterFlags + private let isInternalRootExampleGroup: Bool + private var childGroups = [ExampleGroup]() + private var childExamples = [Example]() + + internal init(description: String, flags: FilterFlags, isInternalRootExampleGroup: Bool = false) { + self.internalDescription = description + self.flags = flags + self.isInternalRootExampleGroup = isInternalRootExampleGroup + } + + public override var description: String { + return internalDescription + } + + /** + Returns a list of examples that belong to this example group, + or to any of its descendant example groups. + */ + public var examples: [Example] { + var examples = childExamples + for group in childGroups { + examples.appendContentsOf(group.examples) + } + return examples + } + + internal var name: String? { + if let parent = parent { + switch(parent.name) { + case .Some(let name): return "\(name), \(description)" + case .None: return description + } + } else { + return isInternalRootExampleGroup ? nil : description + } + } + + internal var filterFlags: FilterFlags { + var aggregateFlags = flags + walkUp() { (group: ExampleGroup) -> () in + for (key, value) in group.flags { + aggregateFlags[key] = value + } + } + return aggregateFlags + } + + internal var befores: [BeforeExampleWithMetadataClosure] { + var closures = Array(hooks.befores.reverse()) + walkUp() { (group: ExampleGroup) -> () in + closures.appendContentsOf(Array(group.hooks.befores.reverse())) + } + return Array(closures.reverse()) + } + + internal var afters: [AfterExampleWithMetadataClosure] { + var closures = hooks.afters + walkUp() { (group: ExampleGroup) -> () in + closures.appendContentsOf(group.hooks.afters) + } + return closures + } + + internal func walkDownExamples(callback: (example: Example) -> ()) { + for example in childExamples { + callback(example: example) + } + for group in childGroups { + group.walkDownExamples(callback) + } + } + + internal func appendExampleGroup(group: ExampleGroup) { + group.parent = self + childGroups.append(group) + } + + internal func appendExample(example: Example) { + example.group = self + childExamples.append(example) + } + + private func walkUp(callback: (group: ExampleGroup) -> ()) { + var group = self + while let parent = group.parent { + callback(group: parent) + group = parent + } + } +} diff --git a/Pods/Quick/Sources/Quick/ExampleMetadata.swift b/Pods/Quick/Sources/Quick/ExampleMetadata.swift new file mode 100644 index 0000000..e7510f7 --- /dev/null +++ b/Pods/Quick/Sources/Quick/ExampleMetadata.swift @@ -0,0 +1,24 @@ +import Foundation + +/** + A class that encapsulates information about an example, + including the index at which the example was executed, as + well as the example itself. +*/ +final public class ExampleMetadata: NSObject { + /** + The example for which this metadata was collected. + */ + public let example: Example + + /** + The index at which this example was executed in the + test suite. + */ + public let exampleIndex: Int + + internal init(example: Example, exampleIndex: Int) { + self.example = example + self.exampleIndex = exampleIndex + } +} diff --git a/Pods/Quick/Sources/Quick/Filter.swift b/Pods/Quick/Sources/Quick/Filter.swift new file mode 100644 index 0000000..d452efe --- /dev/null +++ b/Pods/Quick/Sources/Quick/Filter.swift @@ -0,0 +1,31 @@ +import Foundation + +/** + A mapping of string keys to booleans that can be used to + filter examples or example groups. For example, a "focused" + example would have the flags [Focused: true]. +*/ +public typealias FilterFlags = [String: Bool] + +/** + A namespace for filter flag keys, defined primarily to make the + keys available in Objective-C. +*/ +final public class Filter: NSObject { + /** + Example and example groups with [Focused: true] are included in test runs, + excluding all other examples without this flag. Use this to only run one or + two tests that you're currently focusing on. + */ + public class var focused: String { + return "focused" + } + + /** + Example and example groups with [Pending: true] are excluded from test runs. + Use this to temporarily suspend examples that you know do not pass yet. + */ + public class var pending: String { + return "pending" + } +} diff --git a/Pods/Quick/Sources/Quick/Hooks/Closures.swift b/Pods/Quick/Sources/Quick/Hooks/Closures.swift new file mode 100644 index 0000000..3252bbf --- /dev/null +++ b/Pods/Quick/Sources/Quick/Hooks/Closures.swift @@ -0,0 +1,35 @@ +// MARK: Example Hooks + +/** + A closure executed before an example is run. +*/ +public typealias BeforeExampleClosure = () -> () + +/** + A closure executed before an example is run. The closure is given example metadata, + which contains information about the example that is about to be run. +*/ +public typealias BeforeExampleWithMetadataClosure = (exampleMetadata: ExampleMetadata) -> () + +/** + A closure executed after an example is run. +*/ +public typealias AfterExampleClosure = BeforeExampleClosure + +/** + A closure executed after an example is run. The closure is given example metadata, + which contains information about the example that has just finished running. +*/ +public typealias AfterExampleWithMetadataClosure = BeforeExampleWithMetadataClosure + +// MARK: Suite Hooks + +/** + A closure executed before any examples are run. +*/ +public typealias BeforeSuiteClosure = () -> () + +/** + A closure executed after all examples have finished running. +*/ +public typealias AfterSuiteClosure = BeforeSuiteClosure diff --git a/Pods/Quick/Sources/Quick/Hooks/ExampleHooks.swift b/Pods/Quick/Sources/Quick/Hooks/ExampleHooks.swift new file mode 100644 index 0000000..1d5fa91 --- /dev/null +++ b/Pods/Quick/Sources/Quick/Hooks/ExampleHooks.swift @@ -0,0 +1,42 @@ +/** + A container for closures to be executed before and after each example. +*/ +final internal class ExampleHooks { + internal var befores: [BeforeExampleWithMetadataClosure] = [] + internal var afters: [AfterExampleWithMetadataClosure] = [] + internal var phase: HooksPhase = .NothingExecuted + + internal func appendBefore(closure: BeforeExampleWithMetadataClosure) { + befores.append(closure) + } + + internal func appendBefore(closure: BeforeExampleClosure) { + befores.append { (exampleMetadata: ExampleMetadata) in closure() } + } + + internal func appendAfter(closure: AfterExampleWithMetadataClosure) { + afters.append(closure) + } + + internal func appendAfter(closure: AfterExampleClosure) { + afters.append { (exampleMetadata: ExampleMetadata) in closure() } + } + + internal func executeBefores(exampleMetadata: ExampleMetadata) { + phase = .BeforesExecuting + for before in befores { + before(exampleMetadata: exampleMetadata) + } + + phase = .BeforesFinished + } + + internal func executeAfters(exampleMetadata: ExampleMetadata) { + phase = .AftersExecuting + for after in afters { + after(exampleMetadata: exampleMetadata) + } + + phase = .AftersFinished + } +} diff --git a/Pods/Quick/Sources/Quick/Hooks/HooksPhase.swift b/Pods/Quick/Sources/Quick/Hooks/HooksPhase.swift new file mode 100644 index 0000000..8dc3784 --- /dev/null +++ b/Pods/Quick/Sources/Quick/Hooks/HooksPhase.swift @@ -0,0 +1,11 @@ +/** + A description of the execution cycle of the current example with + respect to the hooks of that example. + */ +internal enum HooksPhase: Int { + case NothingExecuted = 0 + case BeforesExecuting + case BeforesFinished + case AftersExecuting + case AftersFinished +} diff --git a/Pods/Quick/Sources/Quick/Hooks/SuiteHooks.swift b/Pods/Quick/Sources/Quick/Hooks/SuiteHooks.swift new file mode 100644 index 0000000..59bdcf2 --- /dev/null +++ b/Pods/Quick/Sources/Quick/Hooks/SuiteHooks.swift @@ -0,0 +1,32 @@ +/** + A container for closures to be executed before and after all examples. +*/ +final internal class SuiteHooks { + internal var befores: [BeforeSuiteClosure] = [] + internal var afters: [AfterSuiteClosure] = [] + internal var phase: HooksPhase = .NothingExecuted + + internal func appendBefore(closure: BeforeSuiteClosure) { + befores.append(closure) + } + + internal func appendAfter(closure: AfterSuiteClosure) { + afters.append(closure) + } + + internal func executeBefores() { + phase = .BeforesExecuting + for before in befores { + before() + } + phase = .BeforesFinished + } + + internal func executeAfters() { + phase = .AftersExecuting + for after in afters { + after() + } + phase = .AftersFinished + } +} diff --git a/Pods/Quick/Sources/Quick/NSBundle+CurrentTestBundle.swift b/Pods/Quick/Sources/Quick/NSBundle+CurrentTestBundle.swift new file mode 100644 index 0000000..e8709e0 --- /dev/null +++ b/Pods/Quick/Sources/Quick/NSBundle+CurrentTestBundle.swift @@ -0,0 +1,20 @@ +#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) + +import Foundation + +extension NSBundle { + + /** + Locates the first bundle with a '.xctest' file extension. + */ + internal static var currentTestBundle: NSBundle? { + return allBundles().lazy + .filter { + $0.bundlePath.hasSuffix(".xctest") + } + .first + } + +} + +#endif diff --git a/Pods/Quick/Sources/Quick/NSString+QCKSelectorName.h b/Pods/Quick/Sources/Quick/NSString+QCKSelectorName.h new file mode 100644 index 0000000..2da524e --- /dev/null +++ b/Pods/Quick/Sources/Quick/NSString+QCKSelectorName.h @@ -0,0 +1,17 @@ +#import + +/** + QuickSpec converts example names into test methods. + Those test methods need valid selector names, which means no whitespace, + control characters, etc. This category gives NSString objects an easy way + to replace those illegal characters with underscores. + */ +@interface NSString (QCKSelectorName) + +/** + Returns a string with underscores in place of all characters that cannot + be included in a selector (SEL) name. + */ +@property (nonatomic, readonly) NSString *qck_selectorName; + +@end diff --git a/Pods/Quick/Sources/Quick/NSString+QCKSelectorName.m b/Pods/Quick/Sources/Quick/NSString+QCKSelectorName.m new file mode 100644 index 0000000..d374be6 --- /dev/null +++ b/Pods/Quick/Sources/Quick/NSString+QCKSelectorName.m @@ -0,0 +1,37 @@ +#import "NSString+QCKSelectorName.h" + +@implementation NSString (QCKSelectorName) + +- (NSString *)qck_selectorName { + static NSMutableCharacterSet *invalidCharacters = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + invalidCharacters = [NSMutableCharacterSet new]; + + NSCharacterSet *whitespaceCharacterSet = [NSCharacterSet whitespaceCharacterSet]; + NSCharacterSet *newlineCharacterSet = [NSCharacterSet newlineCharacterSet]; + NSCharacterSet *illegalCharacterSet = [NSCharacterSet illegalCharacterSet]; + NSCharacterSet *controlCharacterSet = [NSCharacterSet controlCharacterSet]; + NSCharacterSet *punctuationCharacterSet = [NSCharacterSet punctuationCharacterSet]; + NSCharacterSet *nonBaseCharacterSet = [NSCharacterSet nonBaseCharacterSet]; + NSCharacterSet *symbolCharacterSet = [NSCharacterSet symbolCharacterSet]; + + [invalidCharacters formUnionWithCharacterSet:whitespaceCharacterSet]; + [invalidCharacters formUnionWithCharacterSet:newlineCharacterSet]; + [invalidCharacters formUnionWithCharacterSet:illegalCharacterSet]; + [invalidCharacters formUnionWithCharacterSet:controlCharacterSet]; + [invalidCharacters formUnionWithCharacterSet:punctuationCharacterSet]; + [invalidCharacters formUnionWithCharacterSet:nonBaseCharacterSet]; + [invalidCharacters formUnionWithCharacterSet:symbolCharacterSet]; + }); + + NSArray *validComponents = [self componentsSeparatedByCharactersInSet:invalidCharacters]; + + NSString *result = [validComponents componentsJoinedByString:@"_"]; + + return ([result length] == 0 + ? @"_" + : result); +} + +@end diff --git a/Pods/Quick/Sources/Quick/Quick.h b/Pods/Quick/Sources/Quick/Quick.h new file mode 100644 index 0000000..87dad10 --- /dev/null +++ b/Pods/Quick/Sources/Quick/Quick.h @@ -0,0 +1,11 @@ +#import + +//! Project version number for Quick. +FOUNDATION_EXPORT double QuickVersionNumber; + +//! Project version string for Quick. +FOUNDATION_EXPORT const unsigned char QuickVersionString[]; + +#import "QuickSpec.h" +#import "QCKDSL.h" +#import "QuickConfiguration.h" diff --git a/Pods/Quick/Sources/Quick/QuickSelectedTestSuiteBuilder.swift b/Pods/Quick/Sources/Quick/QuickSelectedTestSuiteBuilder.swift new file mode 100644 index 0000000..5163a4e --- /dev/null +++ b/Pods/Quick/Sources/Quick/QuickSelectedTestSuiteBuilder.swift @@ -0,0 +1,73 @@ +#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) + +/** + Responsible for building a "Selected tests" suite. This corresponds to a single + spec, and all its examples. + */ +internal class QuickSelectedTestSuiteBuilder: QuickTestSuiteBuilder { + + /** + The test spec class to run. + */ + let testCaseClass: AnyClass! + + /** + For Objective-C classes, returns the class name. For Swift classes without, + an explicit Objective-C name, returns a module-namespaced class name + (e.g., "FooTests.FooSpec"). + */ + var testSuiteClassName: String { + return NSStringFromClass(testCaseClass) + } + + /** + Given a test case name: + + FooSpec/testFoo + + Optionally constructs a test suite builder for the named test case class + in the running test bundle. + + If no test bundle can be found, or the test case class can't be found, + initialization fails and returns `nil`. + */ + init?(forTestCaseWithName name: String) { + guard let testCaseClass = testCaseClassForTestCaseWithName(name) else { + self.testCaseClass = nil + return nil + } + + self.testCaseClass = testCaseClass + } + + /** + Returns a `QuickTestSuite` that runs the associated test case class. + */ + func buildTestSuite() -> QuickTestSuite { + return QuickTestSuite(forTestCaseClass: testCaseClass) + } + +} + +/** + Searches `NSBundle.allBundles()` for an xctest bundle, then looks up the named + test case class in that bundle. + + Returns `nil` if a bundle or test case class cannot be found. + */ +private func testCaseClassForTestCaseWithName(name: String) -> AnyClass? { + func extractClassName(name: String) -> String? { + return name.characters.split("/").first.map(String.init) + } + + guard let className = extractClassName(name) else { return nil } + guard let bundle = NSBundle.currentTestBundle else { return nil } + + if let testCaseClass = bundle.classNamed(className) { return testCaseClass } + + guard let moduleName = bundle.bundlePath.fileName else { return nil } + + return NSClassFromString("\(moduleName).\(className)") +} + +#endif diff --git a/Pods/Quick/Sources/Quick/QuickSpec.h b/Pods/Quick/Sources/Quick/QuickSpec.h new file mode 100644 index 0000000..105a97e --- /dev/null +++ b/Pods/Quick/Sources/Quick/QuickSpec.h @@ -0,0 +1,50 @@ +#import + +/** + QuickSpec is a base class all specs written in Quick inherit from. + They need to inherit from QuickSpec, a subclass of XCTestCase, in + order to be discovered by the XCTest framework. + + XCTest automatically compiles a list of XCTestCase subclasses included + in the test target. It iterates over each class in that list, and creates + a new instance of that class for each test method. It then creates an + "invocation" to execute that test method. The invocation is an instance of + NSInvocation, which represents a single message send in Objective-C. + The invocation is set on the XCTestCase instance, and the test is run. + + Most of the code in QuickSpec is dedicated to hooking into XCTest events. + First, when the spec is first loaded and before it is sent any messages, + the +[NSObject initialize] method is called. QuickSpec overrides this method + to call +[QuickSpec spec]. This builds the example group stacks and + registers them with Quick.World, a global register of examples. + + Then, XCTest queries QuickSpec for a list of test methods. Normally, XCTest + automatically finds all methods whose selectors begin with the string "test". + However, QuickSpec overrides this default behavior by implementing the + +[XCTestCase testInvocations] method. This method iterates over each example + registered in Quick.World, defines a new method for that example, and + returns an invocation to call that method to XCTest. Those invocations are + the tests that are run by XCTest. Their selector names are displayed in + the Xcode test navigation bar. + */ +@interface QuickSpec : XCTestCase + +/** + Override this method in your spec to define a set of example groups + and examples. + + @code + override func spec() { + describe("winter") { + it("is coming") { + // ... + } + } + } + @endcode + + See DSL.swift for more information on what syntax is available. + */ +- (void)spec; + +@end diff --git a/Pods/Quick/Sources/Quick/QuickSpec.m b/Pods/Quick/Sources/Quick/QuickSpec.m new file mode 100644 index 0000000..ea64934 --- /dev/null +++ b/Pods/Quick/Sources/Quick/QuickSpec.m @@ -0,0 +1,170 @@ +#import "QuickSpec.h" +#import "QuickConfiguration.h" +#import "NSString+QCKSelectorName.h" +#import "World.h" +#import + +static QuickSpec *currentSpec = nil; + +const void * const QCKExampleKey = &QCKExampleKey; + +@interface QuickSpec () +@property (nonatomic, strong) Example *example; +@end + +@implementation QuickSpec + +#pragma mark - XCTestCase Overrides + +/** + The runtime sends initialize to each class in a program just before the class, or any class + that inherits from it, is sent its first message from within the program. QuickSpec hooks into + this event to compile the example groups for this spec subclass. + + If an exception occurs when compiling the examples, report it to the user. Chances are they + included an expectation outside of a "it", "describe", or "context" block. + */ ++ (void)initialize { + [QuickConfiguration initialize]; + + World *world = [World sharedWorld]; + [world performWithCurrentExampleGroup:[world rootExampleGroupForSpecClass:self] closure:^{ + QuickSpec *spec = [self new]; + + @try { + [spec spec]; + } + @catch (NSException *exception) { + [NSException raise:NSInternalInconsistencyException + format:@"An exception occurred when building Quick's example groups.\n" + @"Some possible reasons this might happen include:\n\n" + @"- An 'expect(...).to' expectation was evaluated outside of " + @"an 'it', 'context', or 'describe' block\n" + @"- 'sharedExamples' was called twice with the same name\n" + @"- 'itBehavesLike' was called with a name that is not registered as a shared example\n\n" + @"Here's the original exception: '%@', reason: '%@', userInfo: '%@'", + exception.name, exception.reason, exception.userInfo]; + } + [self testInvocations]; + }]; +} + +/** + Invocations for each test method in the test case. QuickSpec overrides this method to define a + new method for each example defined in +[QuickSpec spec]. + + @return An array of invocations that execute the newly defined example methods. + */ ++ (NSArray *)testInvocations { + NSArray *examples = [[World sharedWorld] examplesForSpecClass:[self class]]; + NSMutableArray *invocations = [NSMutableArray arrayWithCapacity:[examples count]]; + + NSMutableSet *selectorNames = [NSMutableSet set]; + + for (Example *example in examples) { + SEL selector = [self addInstanceMethodForExample:example classSelectorNames:selectorNames]; + NSInvocation *invocation = [self invocationForInstanceMethodWithSelector:selector + example:example]; + [invocations addObject:invocation]; + } + + return invocations; +} + +/** + XCTest sets the invocation for the current test case instance using this setter. + QuickSpec hooks into this event to give the test case a reference to the current example. + It will need this reference to correctly report its name to XCTest. + */ +- (void)setInvocation:(NSInvocation *)invocation { + self.example = objc_getAssociatedObject(invocation, QCKExampleKey); + [super setInvocation:invocation]; +} + +#pragma mark - Public Interface + +- (void)spec { } + +#pragma mark - Internal Methods + +/** + QuickSpec uses this method to dynamically define a new instance method for the + given example. The instance method runs the example, catching any exceptions. + The exceptions are then reported as test failures. + + In order to report the correct file and line number, examples must raise exceptions + containing following keys in their userInfo: + + - "SenTestFilenameKey": A String representing the file name + - "SenTestLineNumberKey": An Int representing the line number + + These keys used to be used by SenTestingKit, and are still used by some testing tools + in the wild. See: https://github.com/Quick/Quick/pull/41 + + @return The selector of the newly defined instance method. + */ ++ (SEL)addInstanceMethodForExample:(Example *)example classSelectorNames:(NSMutableSet *)selectorNames { + IMP implementation = imp_implementationWithBlock(^(QuickSpec *self){ + currentSpec = self; + [example run]; + }); + NSCharacterSet *characterSet = [NSCharacterSet alphanumericCharacterSet]; + NSMutableString *sanitizedFileName = [NSMutableString string]; + for (NSUInteger i = 0; i < example.callsite.file.length; i++) { + unichar ch = [example.callsite.file characterAtIndex:i]; + if ([characterSet characterIsMember:ch]) { + [sanitizedFileName appendFormat:@"%c", ch]; + } + } + + const char *types = [[NSString stringWithFormat:@"%s%s%s", @encode(id), @encode(id), @encode(SEL)] UTF8String]; + + NSString *originalName = example.name.qck_selectorName; + NSString *selectorName = originalName; + NSUInteger i = 2; + + while ([selectorNames containsObject:selectorName]) { + selectorName = [NSString stringWithFormat:@"%@_%tu", originalName, i++]; + } + + [selectorNames addObject:selectorName]; + + SEL selector = NSSelectorFromString(selectorName); + class_addMethod(self, selector, implementation, types); + + return selector; +} + ++ (NSInvocation *)invocationForInstanceMethodWithSelector:(SEL)selector + example:(Example *)example { + NSMethodSignature *signature = [self instanceMethodSignatureForSelector:selector]; + NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; + invocation.selector = selector; + objc_setAssociatedObject(invocation, + QCKExampleKey, + example, + OBJC_ASSOCIATION_RETAIN_NONATOMIC); + return invocation; +} + +/** + This method is used to record failures, whether they represent example + expectations that were not met, or exceptions raised during test setup + and teardown. By default, the failure will be reported as an + XCTest failure, and the example will be highlighted in Xcode. + */ +- (void)recordFailureWithDescription:(NSString *)description + inFile:(NSString *)filePath + atLine:(NSUInteger)lineNumber + expected:(BOOL)expected { + if (self.example.isSharedExample) { + filePath = self.example.callsite.file; + lineNumber = self.example.callsite.line; + } + [currentSpec.testRun recordFailureWithDescription:description + inFile:filePath + atLine:lineNumber + expected:expected]; +} + +@end diff --git a/Pods/Quick/Sources/Quick/QuickTestSuite.swift b/Pods/Quick/Sources/Quick/QuickTestSuite.swift new file mode 100644 index 0000000..0cb5187 --- /dev/null +++ b/Pods/Quick/Sources/Quick/QuickTestSuite.swift @@ -0,0 +1,52 @@ +#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) + +import XCTest + +/** + This protocol defines the role of an object that builds test suites. + */ +internal protocol QuickTestSuiteBuilder { + + /** + Construct a `QuickTestSuite` instance with the appropriate test cases added as tests. + + Subsequent calls to this method should return equivalent test suites. + */ + func buildTestSuite() -> QuickTestSuite + +} + +/** + A base class for a class cluster of Quick test suites, that should correctly + build dynamic test suites for XCTest to execute. + */ +public class QuickTestSuite: XCTestSuite { + + private static var builtTestSuites: Set = Set() + + /** + Construct a test suite for a specific, selected subset of test cases (rather + than the default, which as all test cases). + + If this method is called multiple times for the same test case class, e.g.. + + FooSpec/testFoo + FooSpec/testBar + + It is expected that the first call should return a valid test suite, and + all subsequent calls should return `nil`. + */ + public static func selectedTestSuite(forTestCaseWithName name: String) -> QuickTestSuite? { + guard let builder = QuickSelectedTestSuiteBuilder(forTestCaseWithName: name) else { return nil } + + if builtTestSuites.contains(builder.testSuiteClassName) { + return nil + } else { + builtTestSuites.insert(builder.testSuiteClassName) + return builder.buildTestSuite() + } + } + +} + +#endif diff --git a/Pods/Quick/Sources/Quick/String+FileName.swift b/Pods/Quick/Sources/Quick/String+FileName.swift new file mode 100644 index 0000000..87cea7a --- /dev/null +++ b/Pods/Quick/Sources/Quick/String+FileName.swift @@ -0,0 +1,12 @@ +import Foundation + +extension String { + + /** + If the receiver represents a path, returns its file name with a file extension. + */ + var fileName: String? { + return NSURL(string: self)?.URLByDeletingPathExtension?.lastPathComponent + } + +} diff --git a/Pods/Quick/Sources/Quick/World.h b/Pods/Quick/Sources/Quick/World.h new file mode 100644 index 0000000..e638cf6 --- /dev/null +++ b/Pods/Quick/Sources/Quick/World.h @@ -0,0 +1,18 @@ +#import + +@class ExampleGroup; +@class ExampleMetadata; + +SWIFT_CLASS("_TtC5Quick5World") +@interface World + +@property (nonatomic) ExampleGroup * __nullable currentExampleGroup; +@property (nonatomic) ExampleMetadata * __nullable currentExampleMetadata; +@property (nonatomic) BOOL isRunningAdditionalSuites; ++ (World * __nonnull)sharedWorld; +- (void)configure:(void (^ __nonnull)(Configuration * __nonnull))closure; +- (void)finalizeConfiguration; +- (ExampleGroup * __nonnull)rootExampleGroupForSpecClass:(Class __nonnull)cls; +- (NSArray * __nonnull)examplesForSpecClass:(Class __nonnull)specClass; +- (void)performWithCurrentExampleGroup:(ExampleGroup * __nonnull)group closure:(void (^ __nonnull)(void))closure; +@end diff --git a/Pods/Quick/Sources/Quick/World.swift b/Pods/Quick/Sources/Quick/World.swift new file mode 100644 index 0000000..b2b58c8 --- /dev/null +++ b/Pods/Quick/Sources/Quick/World.swift @@ -0,0 +1,230 @@ +import Foundation + +/** + A closure that, when evaluated, returns a dictionary of key-value + pairs that can be accessed from within a group of shared examples. +*/ +public typealias SharedExampleContext = () -> (NSDictionary) + +/** + A closure that is used to define a group of shared examples. This + closure may contain any number of example and example groups. +*/ +public typealias SharedExampleClosure = (SharedExampleContext) -> () + +/** + A collection of state Quick builds up in order to work its magic. + World is primarily responsible for maintaining a mapping of QuickSpec + classes to root example groups for those classes. + + It also maintains a mapping of shared example names to shared + example closures. + + You may configure how Quick behaves by calling the -[World configure:] + method from within an overridden +[QuickConfiguration configure:] method. +*/ +final internal class World: NSObject { + /** + The example group that is currently being run. + The DSL requires that this group is correctly set in order to build a + correct hierarchy of example groups and their examples. + */ + internal var currentExampleGroup: ExampleGroup! + + /** + The example metadata of the test that is currently being run. + This is useful for using the Quick test metadata (like its name) at + runtime. + */ + + internal var currentExampleMetadata: ExampleMetadata? + + /** + A flag that indicates whether additional test suites are being run + within this test suite. This is only true within the context of Quick + functional tests. + */ + internal var isRunningAdditionalSuites = false + + private var specs: Dictionary = [:] + private var sharedExamples: [String: SharedExampleClosure] = [:] + private let configuration = Configuration() + private var isConfigurationFinalized = false + + internal var exampleHooks: ExampleHooks {return configuration.exampleHooks } + internal var suiteHooks: SuiteHooks { return configuration.suiteHooks } + + // MARK: Singleton Constructor + + private override init() {} + static let sharedWorld = World() + + // MARK: Public Interface + + /** + Exposes the World's Configuration object within the scope of the closure + so that it may be configured. This method must not be called outside of + an overridden +[QuickConfiguration configure:] method. + + - parameter closure: A closure that takes a Configuration object that can + be mutated to change Quick's behavior. + */ + internal func configure(closure: QuickConfigurer) { + assert(!isConfigurationFinalized, + "Quick cannot be configured outside of a +[QuickConfiguration configure:] method. You should not call -[World configure:] directly. Instead, subclass QuickConfiguration and override the +[QuickConfiguration configure:] method.") + closure(configuration: configuration) + } + + /** + Finalizes the World's configuration. + Any subsequent calls to World.configure() will raise. + */ + internal func finalizeConfiguration() { + isConfigurationFinalized = true + } + + /** + Returns an internally constructed root example group for the given + QuickSpec class. + + A root example group with the description "root example group" is lazily + initialized for each QuickSpec class. This root example group wraps the + top level of a -[QuickSpec spec] method--it's thanks to this group that + users can define beforeEach and it closures at the top level, like so: + + override func spec() { + // These belong to the root example group + beforeEach {} + it("is at the top level") {} + } + + - parameter cls: The QuickSpec class for which to retrieve the root example group. + - returns: The root example group for the class. + */ + internal func rootExampleGroupForSpecClass(cls: AnyClass) -> ExampleGroup { + #if _runtime(_ObjC) + let name = NSStringFromClass(cls) + #else + let name = String(cls) + #endif + + if let group = specs[name] { + return group + } else { + let group = ExampleGroup( + description: "root example group", + flags: [:], + isInternalRootExampleGroup: true + ) + specs[name] = group + return group + } + } + + /** + Returns all examples that should be run for a given spec class. + There are two filtering passes that occur when determining which examples should be run. + That is, these examples are the ones that are included by inclusion filters, and are + not excluded by exclusion filters. + + - parameter specClass: The QuickSpec subclass for which examples are to be returned. + - returns: A list of examples to be run as test invocations. + */ + internal func examples(specClass: AnyClass) -> [Example] { + // 1. Grab all included examples. + let included = includedExamples + // 2. Grab the intersection of (a) examples for this spec, and (b) included examples. + let spec = rootExampleGroupForSpecClass(specClass).examples.filter { included.contains($0) } + // 3. Remove all excluded examples. + return spec.filter { example in + !self.configuration.exclusionFilters.reduce(false) { $0 || $1(example: example) } + } + } + +#if _runtime(_ObjC) + @objc(examplesForSpecClass:) + private func objc_examples(specClass: AnyClass) -> [Example] { + return examples(specClass) + } +#endif + + // MARK: Internal + + internal func registerSharedExample(name: String, closure: SharedExampleClosure) { + raiseIfSharedExampleAlreadyRegistered(name) + sharedExamples[name] = closure + } + + internal func sharedExample(name: String) -> SharedExampleClosure { + raiseIfSharedExampleNotRegistered(name) + return sharedExamples[name]! + } + + internal var includedExampleCount: Int { + return includedExamples.count + } + + internal var beforesCurrentlyExecuting: Bool { + let suiteBeforesExecuting = suiteHooks.phase == .BeforesExecuting + let exampleBeforesExecuting = exampleHooks.phase == .BeforesExecuting + var groupBeforesExecuting = false + if let runningExampleGroup = currentExampleMetadata?.example.group { + groupBeforesExecuting = runningExampleGroup.phase == .BeforesExecuting + } + + return suiteBeforesExecuting || exampleBeforesExecuting || groupBeforesExecuting + } + + internal var aftersCurrentlyExecuting: Bool { + let suiteAftersExecuting = suiteHooks.phase == .AftersExecuting + let exampleAftersExecuting = exampleHooks.phase == .AftersExecuting + var groupAftersExecuting = false + if let runningExampleGroup = currentExampleMetadata?.example.group { + groupAftersExecuting = runningExampleGroup.phase == .AftersExecuting + } + + return suiteAftersExecuting || exampleAftersExecuting || groupAftersExecuting + } + + internal func performWithCurrentExampleGroup(group: ExampleGroup, closure: () -> Void) { + let previousExampleGroup = currentExampleGroup + currentExampleGroup = group + + closure() + + currentExampleGroup = previousExampleGroup + } + + private var allExamples: [Example] { + var all: [Example] = [] + for (_, group) in specs { + group.walkDownExamples { all.append($0) } + } + return all + } + + private var includedExamples: [Example] { + let all = allExamples + let included = all.filter { example in + return self.configuration.inclusionFilters.reduce(false) { $0 || $1(example: example) } + } + + if included.isEmpty && configuration.runAllWhenEverythingFiltered { + return all + } else { + return included + } + } + + private func raiseIfSharedExampleAlreadyRegistered(name: String) { + if sharedExamples[name] != nil { + raiseError("A shared example named '\(name)' has already been registered.") + } + } + + private func raiseIfSharedExampleNotRegistered(name: String) { + if sharedExamples[name] == nil { + raiseError("No shared example named '\(name)' has been registered. Registered shared examples: '\(Array(sharedExamples.keys))'") + } + } +} diff --git a/Pods/Quick/Sources/Quick/XCTestSuite+QuickTestSuiteBuilder.m b/Pods/Quick/Sources/Quick/XCTestSuite+QuickTestSuiteBuilder.m new file mode 100644 index 0000000..e49939e --- /dev/null +++ b/Pods/Quick/Sources/Quick/XCTestSuite+QuickTestSuiteBuilder.m @@ -0,0 +1,40 @@ +#import +#import +#import + +@interface XCTestSuite (QuickTestSuiteBuilder) +@end + +@implementation XCTestSuite (QuickTestSuiteBuilder) + +/** + In order to ensure we can correctly build dynamic test suites, we need to + replace some of the default test suite constructors. + */ ++ (void)load { + Method testCaseWithName = class_getClassMethod(self, @selector(testSuiteForTestCaseWithName:)); + Method hooked_testCaseWithName = class_getClassMethod(self, @selector(qck_hooked_testSuiteForTestCaseWithName:)); + method_exchangeImplementations(testCaseWithName, hooked_testCaseWithName); +} + +/** + The `+testSuiteForTestCaseWithName:` method is called when a specific test case + class is run from the Xcode test navigator. If the built test suite is `nil`, + Xcode will not run any tests for that test case. + + Given if the following test case class is run from the Xcode test navigator: + + FooSpec + testFoo + testBar + + XCTest will invoke this once per test case, with test case names following this format: + + FooSpec/testFoo + FooSpec/testBar + */ ++ (nullable instancetype)qck_hooked_testSuiteForTestCaseWithName:(nonnull NSString *)name { + return [QuickTestSuite selectedTestSuiteForTestCaseWithName:name]; +} + +@end diff --git a/Pods/SwiftTask/LICENSE b/Pods/SwiftTask/LICENSE new file mode 100644 index 0000000..8d40515 --- /dev/null +++ b/Pods/SwiftTask/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Yasuhiro Inami + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Pods/SwiftTask/README.md b/Pods/SwiftTask/README.md new file mode 100644 index 0000000..d11d74e --- /dev/null +++ b/Pods/SwiftTask/README.md @@ -0,0 +1,289 @@ +SwiftTask [![Circle CI](https://circleci.com/gh/ReactKit/SwiftTask/tree/swift%2F2.0.svg?style=svg)](https://circleci.com/gh/ReactKit/SwiftTask/tree/swift%2F2.0) +========= + +[Promise](http://www.html5rocks.com/en/tutorials/es6/promises/) + progress + pause + cancel + retry for Swift. + +![SwiftTask](Screenshots/diagram.png) + + +## How to install + +See [ReactKit Wiki page](https://github.com/ReactKit/ReactKit/wiki/How-to-install). + + +## Example + +### Basic + +```swift +// define task +let task = Task { progress, fulfill, reject, configure in + + player.doSomethingWithProgress({ (progressValue: Float) in + progress(progressValue) // optional + }, completion: { (value: NSData?, error: NSError?) in + if error == nil { + fulfill("OK") + } + else { + reject(error) + } + }) + + // pause/resume/cancel configuration (optional) + configure.pause = { [weak player] in + player?.pause() + } + configure.resume = { [weak player] in + player?.resume() + } + configure.cancel = { [weak player] in + player?.cancel() + } + +} + +// set success & failure +task.success { (value: String) -> Void in + // do something with fulfilled value +}.failure { (error: NSError?, isCancelled: Bool) -> Void in + // do something with rejected error +} + +// you can call configured operations outside of Task-definition +task.pause() +task.resume() +task.cancel() +``` + +Notice that `player` has following methods, which will work nicely with `SwiftTask`: + +- `doSomethingWithProgress(_:completion:)` (progress callback as optional) +- `pause()` (optional) +- `resume()` (optional) +- `cancel()` (optional) + +One of the best example would be [Alamofire](https://github.com/Alamofire/Alamofire) (networking library) + as seen below. + +### Using [Alamofire](https://github.com/Alamofire/Alamofire) + +```swift +typealias Progress = (bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) +typealias AlamoFireTask = Task + +// define task +let task = AlamoFireTask { progress, fulfill, reject, configure in + + Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: somewhere) + .progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in + + progress((bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) as Progress) + + }.response { request, response, data, error in + + if let error = error { + reject(error) + return + } + + fulfill("OK") + + } + + return +} + +// set progress & then +task.progress { (oldProgress: Progress?, newProgress: Progress) in + + println("\(newProgress.bytesWritten)") + println("\(newProgress.totalBytesWritten)") + println("\(newProgress.totalBytesExpectedToWrite)") + +}.then { (value: String?, errorInfo: AlamoFireTask.ErrorInfo?) -> Void in + // do something with fulfilled value or rejected errorInfo +} +``` + +### Retry-able + +`Task` can retry for multiple times by using `retry()` method. +For example, `task.retry(n)` will retry at most `n` times (total tries = `n+1`) if `task` keeps rejected, and `task.retry(0)` is obviously same as `task` itself having no retries. + +This feature is extremely useful for unstable tasks e.g. network connection. +By implementing *retryable* from `SwiftTask`'s side, similar code is no longer needed for `player` (inner logic) class. + +```swift +task.retry(2).progress { ... }.success { ... + // this closure will be called even when task is rejected for 1st & 2nd try + // but finally fulfilled in 3rd try. +} +``` + +For more examples, please see XCTest cases. + + +## API Reference + +### Task.init(initClosure:) + +Define your `task` inside `initClosure`. + +```swift +let task = Task { progress, fulfill, reject, configure in + + player.doSomethingWithCompletion { (value: NSString?, error: NSError?) in + if error == nil { + fulfill(value) + } + else { + reject(error) + } + } +} +``` + +In order to pipeline future `task.value` or `task.errorInfo` (tuple of `(error: Error?, isCancelled: Bool)`) via `then()`/`success()`/`failure()`, you have to call `fulfill(value)` and/or `reject(error)` inside `initClosure`. + +Optionally, you can call `progress(progressValue)` multiple times before calling `fulfill`/`reject` to transfer `progressValue` outside of the `initClosure`, notifying it to `task` itself. + +To add `pause`/`resume`/`cancel` functionality to your `task`, use `configure` to wrap up the original one. + +```swift +// NOTE: use weak to let task NOT CAPTURE player via configure +configure.pause = { [weak player] in + player?.pause() +} +configure.resume = { [weak player] in + player?.resume() +} +configure.cancel = { [weak player] in + player?.cancel() +} +``` + +### task.progress(_ progressClosure:) -> task + +```swift +task.progress { (oldProgress: Progress?, newProgress: Progress) in + println(newProgress) + return +}.success { ... } +``` + +`task.progress(progressClosure)` will add `progressClosure` to observe old/new `progressValue` which is notified from inside previous `initClosure`. This method will return **same task**, so it is useful to chain with forthcoming `then`/`success`/`failure`. + +### task.then(_ thenClosure:) -> newTask + +`task.then(thenClosure)` will return a new task where `thenClosure` will be invoked when `task` is either **fulfilled** or **rejected**. + +This case is similar to JavaScript's `promise.then(onFulfilled, onRejected)`. + +`thenClosure` can be two types of closure form: + +1. `thenClosure: (Value?, ErrorInfo?) -> Value2` (flow: *task => newTask*) + + ```swift + // let task will be fulfilled with value "Hello" + + task.then { (value: String?, errorInfo: ErrorInfo?) -> String in + // nil-check to find out whether task is fulfilled or rejected + if errorInfo == nil { + return "\(value!) World" + } + else { + return "\(value!) Error" + } + }.success { (value: String) -> Void in + println("\(value)") // Hello World + return" + } + ``` + +2. `thenClosure: (Value?, ErrorInfo?) -> Task` (flow: *task => task2 => newTask*) + + ```swift + // let task will be fulfilled with value "Hello" + + task.then { (value: String?, errorInfo: ErrorInfo?) -> Task in + if errorInfo == nil { + // let task2 will be fulfilled with value "\(value!) Swift" + let task2 = ... + return task2 + } + else { + return someOtherTask + } + }.success { (value: String) -> Void in + println("\(value)") // Hello Swift + return" + } + ``` + +### task.success(_ successClosure:) -> newTask + +Similar to `then()` method, `task.success(successClosure)` will return a new task, but this time, `successClosure` will be invoked when task is **only fulfilled**. + +This case is similar to JavaScript's `promise.then(onFulfilled)`. + +```swift +// let task will be fulfilled with value "Hello" + +task.success { (value: String) -> String in + return "\(value) World" +}.success { (value: String) -> Void in + println("\(value)") // Hello World + return" +} +``` + +### task.failure(_ failureClosure:) -> newTask + +Just the opposite of `success()`, `task.failure(failureClosure)` will return a new task where `failureClosure` will be invoked when task is **only rejected/cancelled**. + +This case is similar to JavaScript's `promise.then(undefined, onRejected)` or `promise.catch(onRejected)`. + +```swift +// let task will be rejected with error "Oh My God" + +task.success { (value: String) -> Void in + println("\(value)") // never reaches here + return +}.failure { (error: NSError?, isCancelled: Bool) -> Void in + println("\(error!)") // Oh My God + return +} +``` + +### task.try(_ tryCount:) -> newTask + +See [Retry-able section](#retry-able). + +### Task.all(_ tasks:) -> newTask + +`Task.all(tasks)` is a new task that performs all `tasks` simultaneously and will be: + +- fulfilled when **all tasks are fulfilled** +- rejected when **any of the task is rejected** + +### Task.any(_ tasks:) -> newTask + +`Task.any(tasks)` is an opposite of `Task.all(tasks)` which will be: + +- fulfilled when **any of the task is fulfilled** +- rejected when **all tasks are rejected** + +### Task.some(_ tasks:) -> newTask + +`Task.some(tasks)` is a new task that performs all `tasks` without internal rejection, and is fulfilled with given `tasks`'s fulfilled values. Note that this new task **will be fulfilled with empty value-array, even though all `tasks` are rejected.** + + +## Related Articles + +- [SwiftTask(Promise拡張)を使う - Qiita](http://qiita.com/inamiy/items/0756339aee35849384c3) (Japanese, ver 1.0.0) + + +## Licence + +[MIT](LICENSE) diff --git a/Pods/SwiftTask/SwiftTask/Cancellable.swift b/Pods/SwiftTask/SwiftTask/Cancellable.swift new file mode 100644 index 0000000..51c6ea2 --- /dev/null +++ b/Pods/SwiftTask/SwiftTask/Cancellable.swift @@ -0,0 +1,56 @@ +// +// Cancellable.swift +// SwiftTask +// +// Created by Yasuhiro Inami on 2015/05/09. +// Copyright (c) 2015年 Yasuhiro Inami. All rights reserved. +// + +import Foundation + +public protocol Cancellable +{ + associatedtype _Error + + // + // NOTE: + // Single `func cancel(error: Error) -> Bool` is preferred (as first implemented in 8a22ed5), + // but two overloaded methods are required for SwiftTask ver 3.x API compatibility. + // + func cancel() -> Bool + func cancel(error error: _Error) -> Bool +} + +public class Canceller: Cancellable +{ + private var cancelHandler: (Void -> Void)? + + public required init(cancelHandler: Void -> Void) + { + self.cancelHandler = cancelHandler + } + + public func cancel() -> Bool + { + return self.cancel(error: ()) + } + + public func cancel(error error: Void) -> Bool + { + if let cancelHandler = self.cancelHandler { + self.cancelHandler = nil + cancelHandler() + return true + } + + return false + } +} + +public class AutoCanceller: Canceller +{ + deinit + { + self.cancel() + } +} \ No newline at end of file diff --git a/Pods/SwiftTask/SwiftTask/SwiftTask.h b/Pods/SwiftTask/SwiftTask/SwiftTask.h new file mode 100644 index 0000000..73f57ae --- /dev/null +++ b/Pods/SwiftTask/SwiftTask/SwiftTask.h @@ -0,0 +1,19 @@ +// +// SwiftTask.h +// SwiftTask +// +// Created by Yasuhiro Inami on 2014/08/21. +// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. +// + +#import + +//! Project version number for SwiftTask. +FOUNDATION_EXPORT double SwiftTaskVersionNumber; + +//! Project version string for SwiftTask. +FOUNDATION_EXPORT const unsigned char SwiftTaskVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import + + diff --git a/Pods/SwiftTask/SwiftTask/SwiftTask.swift b/Pods/SwiftTask/SwiftTask/SwiftTask.swift new file mode 100644 index 0000000..e69c25e --- /dev/null +++ b/Pods/SwiftTask/SwiftTask/SwiftTask.swift @@ -0,0 +1,854 @@ +// +// SwiftTask.swift +// SwiftTask +// +// Created by Yasuhiro Inami on 2014/08/21. +// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. +// + +// Required for use in the playground Sources folder +import ObjectiveC + +// NOTE: nested type inside generic Task class is not allowed in Swift 1.1 +public enum TaskState: String, CustomStringConvertible +{ + case Paused = "Paused" + case Running = "Running" + case Fulfilled = "Fulfilled" + case Rejected = "Rejected" + case Cancelled = "Cancelled" + + public var description: String + { + return self.rawValue + } +} + +// NOTE: use class instead of struct to pass reference to `_initClosure` to set `pause`/`resume`/`cancel` closures +public class TaskConfiguration +{ + public var pause: (Void -> Void)? + public var resume: (Void -> Void)? + public var cancel: (Void -> Void)? + + /// useful to terminate immediate-infinite-sequence while performing `initClosure` + public var isFinished : Bool + { + return self._isFinished.rawValue + } + + private var _isFinished = _Atomic(false) + + internal func finish() + { + // + // Cancel anyway on task finished (fulfilled/rejected/cancelled). + // + // NOTE: + // ReactKit uses this closure to call `upstreamSignal.cancel()` + // and let it know `configure.isFinished = true` while performing its `initClosure`. + // + self.cancel?() + + self.pause = nil + self.resume = nil + self.cancel = nil + self._isFinished.rawValue = true + } +} + +public class Task: Cancellable, CustomStringConvertible +{ + public typealias ProgressTuple = (oldProgress: Progress?, newProgress: Progress) + public typealias ErrorInfo = (error: Error?, isCancelled: Bool) + + public typealias ProgressHandler = (Progress -> Void) + public typealias FulfillHandler = (Value -> Void) + public typealias RejectHandler = (Error -> Void) + public typealias Configuration = TaskConfiguration + + public typealias PromiseInitClosure = (fulfill: FulfillHandler, reject: RejectHandler) -> Void + public typealias InitClosure = (progress: ProgressHandler, fulfill: FulfillHandler, reject: RejectHandler, configure: TaskConfiguration) -> Void + + internal typealias _Machine = _StateMachine + + internal typealias _InitClosure = (machine: _Machine, progress: ProgressHandler, fulfill: FulfillHandler, _reject: _RejectInfoHandler, configure: TaskConfiguration) -> Void + + internal typealias _ProgressTupleHandler = (ProgressTuple -> Void) + internal typealias _RejectInfoHandler = (ErrorInfo -> Void) + + internal let _machine: _Machine + + // store initial parameters for cloning task when using `try()` + internal let _weakified: Bool + internal let _paused: Bool + internal var _initClosure: _InitClosure! // retained throughout task's lifetime + + public var state: TaskState { return self._machine.state.rawValue } + + /// progress value (NOTE: always nil when `weakified = true`) + public var progress: Progress? { return self._machine.progress.rawValue } + + /// fulfilled value + public var value: Value? { return self._machine.value.rawValue } + + /// rejected/cancelled tuple info + public var errorInfo: ErrorInfo? { return self._machine.errorInfo.rawValue } + + public var name: String = "DefaultTask" + + public var description: String + { + var valueString: String? + + switch (self.state) { + case .Fulfilled: + valueString = "value=\(self.value!)" + case .Rejected, .Cancelled: + valueString = "errorInfo=\(self.errorInfo!)" + default: + valueString = "progress=\(self.progress)" + } + + return "<\(self.name); state=\(self.state.rawValue); \(valueString!))>" + } + + /// + /// Create a new task. + /// + /// - e.g. Task(weakified: false, paused: false) { progress, fulfill, reject, configure in ... } + /// + /// - Parameter weakified: Weakifies progress/fulfill/reject handlers to let player (inner asynchronous implementation inside `initClosure`) NOT CAPTURE this created new task. Normally, `weakified = false` should be set to gain "player -> task" retaining, so that task will be automatically deinited when player is deinited. If `weakified = true`, task must be manually retained somewhere else, or it will be immediately deinited. + /// + /// - Parameter paused: Flag to invoke `initClosure` immediately or not. If `paused = true`, task's initial state will be `.Paused` and needs to `resume()` in order to start `.Running`. If `paused = false`, `initClosure` will be invoked immediately. + /// + /// - Parameter initClosure: e.g. { progress, fulfill, reject, configure in ... }. `fulfill(value)` and `reject(error)` handlers must be called inside this closure, where calling `progress(progressValue)` handler is optional. Also as options, `configure.pause`/`configure.resume`/`configure.cancel` closures can be set to gain control from outside e.g. `task.pause()`/`task.resume()`/`task.cancel()`. When using `configure`, make sure to use weak modifier when appropriate to avoid "task -> player" retaining which often causes retain cycle. + /// + /// - Returns: New task. + /// + public init(weakified: Bool, paused: Bool, initClosure: InitClosure) + { + self._weakified = weakified + self._paused = paused + self._machine = _Machine(weakified: weakified, paused: paused) + + let _initClosure: _InitClosure = { _, progress, fulfill, _reject, configure in + // NOTE: don't expose rejectHandler with ErrorInfo (isCancelled) for public init + initClosure(progress: progress, fulfill: fulfill, reject: { error in _reject(ErrorInfo(error: Optional(error), isCancelled: false)) }, configure: configure) + } + + self.setup(weakified: weakified, paused: paused, _initClosure: _initClosure) + } + + /// + /// Create a new task without weakifying progress/fulfill/reject handlers + /// + /// - e.g. Task(paused: false) { progress, fulfill, reject, configure in ... } + /// + public convenience init(paused: Bool, initClosure: InitClosure) + { + self.init(weakified: false, paused: paused, initClosure: initClosure) + } + + /// + /// Create a new task without weakifying progress/fulfill/reject handlers (non-paused) + /// + /// - e.g. Task { progress, fulfill, reject, configure in ... } + /// + public convenience init(initClosure: InitClosure) + { + self.init(weakified: false, paused: false, initClosure: initClosure) + } + + /// + /// Create fulfilled task (non-paused) + /// + /// - e.g. Task(value: someValue) + /// + public convenience init(value: Value) + { + self.init(initClosure: { progress, fulfill, reject, configure in + fulfill(value) + }) + self.name = "FulfilledTask" + } + + /// + /// Create rejected task (non-paused) + /// + /// - e.g. Task(error: someError) + /// + public convenience init(error: Error) + { + self.init(initClosure: { progress, fulfill, reject, configure in + reject(error) + }) + self.name = "RejectedTask" + } + + /// + /// Create promise-like task which only allows fulfill & reject (no progress & configure) + /// + /// - e.g. Task { fulfill, reject in ... } + /// + public convenience init(promiseInitClosure: PromiseInitClosure) + { + self.init(initClosure: { progress, fulfill, reject, configure in + promiseInitClosure(fulfill: fulfill, reject: { error in reject(error) }) + }) + } + + /// internal-init for accessing `machine` inside `_initClosure` + /// (NOTE: _initClosure has _RejectInfoHandler as argument) + internal init(weakified: Bool = false, paused: Bool = false, _initClosure: _InitClosure) + { + self._weakified = weakified + self._paused = paused + self._machine = _Machine(weakified: weakified, paused: paused) + + self.setup(weakified: weakified, paused: paused, _initClosure: _initClosure) + } + + // NOTE: don't use `internal init` for this setup method, or this will be a designated initializer + internal func setup(weakified weakified: Bool, paused: Bool, _initClosure: _InitClosure) + { +// #if DEBUG +// let addr = String(format: "%p", unsafeAddressOf(self)) +// NSLog("[init] \(self.name) \(addr)") +// #endif + + self._initClosure = _initClosure + + // will be invoked on 1st resume (only once) + self._machine.initResumeClosure.rawValue = { [weak self] in + + // strongify `self` on 1st resume + if let self_ = self { + + var progressHandler: ProgressHandler + var fulfillHandler: FulfillHandler + var rejectInfoHandler: _RejectInfoHandler + + if weakified { + // + // NOTE: + // When `weakified = true`, + // each handler will NOT capture `self_` (strongSelf on 1st resume) + // so it will immediately deinit if not retained in somewhere else. + // + progressHandler = { [weak self_] (progress: Progress) in + if let self_ = self_ { + self_._machine.handleProgress(progress) + } + } + + fulfillHandler = { [weak self_] (value: Value) in + if let self_ = self_ { + self_._machine.handleFulfill(value) + } + } + + rejectInfoHandler = { [weak self_] (errorInfo: ErrorInfo) in + if let self_ = self_ { + self_._machine.handleRejectInfo(errorInfo) + } + } + } + else { + // + // NOTE: + // When `weakified = false`, + // each handler will capture `self_` (strongSelf on 1st resume) + // so that it will live until fulfilled/rejected. + // + progressHandler = { (progress: Progress) in + self_._machine.handleProgress(progress) + } + + fulfillHandler = { (value: Value) in + self_._machine.handleFulfill(value) + } + + rejectInfoHandler = { (errorInfo: ErrorInfo) in + self_._machine.handleRejectInfo(errorInfo) + } + } + + _initClosure(machine: self_._machine, progress: progressHandler, fulfill: fulfillHandler, _reject: rejectInfoHandler, configure: self_._machine.configuration) + + } + + } + + if !paused { + self.resume() + } + } + + deinit + { +// #if DEBUG +// let addr = String(format: "%p", unsafeAddressOf(self)) +// NSLog("[deinit] \(self.name) \(addr)") +// #endif + + // cancel in case machine is still running + self._cancel(nil) + } + + /// Sets task name (method chainable) + public func name(name: String) -> Self + { + self.name = name + return self + } + + /// Creates cloned task. + public func clone() -> Task + { + let clonedTask = Task(weakified: self._weakified, paused: self._paused, _initClosure: self._initClosure) + clonedTask.name = "\(self.name)-clone" + return clonedTask + } + + /// Returns new task that is retryable for `maxRetryCount (= maxTryCount-1)` times. + public func retry(maxRetryCount: Int) -> Task + { + if maxRetryCount < 1 { return self } + + return Task { machine, progress, fulfill, _reject, configure in + + let task = self.progress { _, progressValue in + progress(progressValue) + }.failure { [unowned self] _ -> Task in + return self.clone().retry(maxRetryCount-1) // clone & try recursively + } + + task.progress { _, progressValue in + progress(progressValue) // also receive progresses from clone-try-task + }.success { value -> Void in + fulfill(value) + }.failure { errorInfo -> Void in + _reject(errorInfo) + } + + configure.pause = { + self.pause() + task.pause() + } + configure.resume = { + self.resume() + task.resume() + } + configure.cancel = { + task.cancel() // cancel downstream first + self.cancel() + } + + }.name("\(self.name)-try(\(maxRetryCount))") + } + + /// + /// Add progress handler delivered from `initClosure`'s `progress()` argument. + /// + /// - e.g. task.progress { oldProgress, newProgress in ... } + /// + /// - Note: `oldProgress` is always nil when `weakified = true` + /// - Returns: Self (same `Task`) + /// + public func progress(progressClosure: ProgressTuple -> Void) -> Self + { + var dummyCanceller: Canceller? = nil + return self.progress(&dummyCanceller, progressClosure) + } + + public func progress(inout canceller: C?, _ progressClosure: ProgressTuple -> Void) -> Self + { + var token: _HandlerToken? = nil + self._machine.addProgressTupleHandler(&token, progressClosure) + + canceller = C { [weak self] in + self?._machine.removeProgressTupleHandler(token) + } + + return self + } + + /// + /// `then` (fulfilled & rejected) + closure returning **value**. + /// (similar to `map` in functional programming) + /// + /// - e.g. task.then { value, errorInfo -> NextValueType in ... } + /// + /// - Returns: New `Task` + /// + public func then(thenClosure: (Value?, ErrorInfo?) -> Value2) -> Task + { + var dummyCanceller: Canceller? = nil + return self.then(&dummyCanceller, thenClosure) + } + + public func then(inout canceller: C?, _ thenClosure: (Value?, ErrorInfo?) -> Value2) -> Task + { + return self.then(&canceller) { (value, errorInfo) -> Task in + return Task(value: thenClosure(value, errorInfo)) + } + } + + /// + /// `then` (fulfilled & rejected) + closure returning **task**. + /// (similar to `flatMap` in functional programming) + /// + /// - e.g. task.then { value, errorInfo -> NextTaskType in ... } + /// + /// - Returns: New `Task` + /// + public func then(thenClosure: (Value?, ErrorInfo?) -> Task) -> Task + { + var dummyCanceller: Canceller? = nil + return self.then(&dummyCanceller, thenClosure) + } + + // + // NOTE: then-canceller is a shorthand of `task.cancel(nil)`, i.e. these two are the same: + // + // - `let canceller = Canceller(); task1.then(&canceller) {...}; canceller.cancel();` + // - `let task2 = task1.then {...}; task2.cancel();` + // + /// - Returns: New `Task` + /// + public func then(inout canceller: C?, _ thenClosure: (Value?, ErrorInfo?) -> Task) -> Task + { + return Task { [unowned self, weak canceller] newMachine, progress, fulfill, _reject, configure in + + // + // NOTE: + // We split `self` (Task) and `self.machine` (StateMachine) separately to + // let `completionHandler` retain `selfMachine` instead of `self` + // so that `selfMachine`'s `completionHandlers` can be invoked even though `self` is deinited. + // This is especially important for ReactKit's `deinitSignal` behavior. + // + let selfMachine = self._machine + + self._then(&canceller) { + let innerTask = thenClosure(selfMachine.value.rawValue, selfMachine.errorInfo.rawValue) + _bindInnerTask(innerTask, newMachine, progress, fulfill, _reject, configure) + } + + }.name("\(self.name)-then") + } + + /// invokes `completionHandler` "now" or "in the future" + private func _then(inout canceller: C?, _ completionHandler: Void -> Void) + { + switch self.state { + case .Fulfilled, .Rejected, .Cancelled: + completionHandler() + default: + var token: _HandlerToken? = nil + self._machine.addCompletionHandler(&token, completionHandler) + + canceller = C { [weak self] in + self?._machine.removeCompletionHandler(token) + } + } + } + + /// + /// `success` (fulfilled) + closure returning **value**. + /// (synonym for `map` in functional programming) + /// + /// - e.g. task.success { value -> NextValueType in ... } + /// + /// - Returns: New `Task` + /// + public func success(successClosure: Value -> Value2) -> Task + { + var dummyCanceller: Canceller? = nil + return self.success(&dummyCanceller, successClosure) + } + + public func success(inout canceller: C?, _ successClosure: Value -> Value2) -> Task + { + return self.success(&canceller) { (value: Value) -> Task in + return Task(value: successClosure(value)) + } + } + + /// + /// `success` (fulfilled) + closure returning **task** + /// (synonym for `flatMap` in functional programming) + /// + /// - e.g. task.success { value -> NextTaskType in ... } + /// + /// - Returns: New `Task` + /// + public func success(successClosure: Value -> Task) -> Task + { + var dummyCanceller: Canceller? = nil + return self.success(&dummyCanceller, successClosure) + } + + public func success(inout canceller: C?, _ successClosure: Value -> Task) -> Task + { + return Task { [unowned self] newMachine, progress, fulfill, _reject, configure in + + let selfMachine = self._machine + + // NOTE: using `self._then()` + `selfMachine` instead of `self.then()` will reduce Task allocation + self._then(&canceller) { + if let value = selfMachine.value.rawValue { + let innerTask = successClosure(value) + _bindInnerTask(innerTask, newMachine, progress, fulfill, _reject, configure) + } + else if let errorInfo = selfMachine.errorInfo.rawValue { + _reject(errorInfo) + } + } + + }.name("\(self.name)-success") + } + + /// + /// `failure` (rejected or cancelled) + closure returning **value**. + /// (synonym for `mapError` in functional programming) + /// + /// - e.g. task.failure { errorInfo -> NextValueType in ... } + /// - e.g. task.failure { error, isCancelled -> NextValueType in ... } + /// + /// - Returns: New `Task` + /// + public func failure(failureClosure: ErrorInfo -> Value) -> Task + { + var dummyCanceller: Canceller? = nil + return self.failure(&dummyCanceller, failureClosure) + } + + public func failure(inout canceller: C?, _ failureClosure: ErrorInfo -> Value) -> Task + { + return self.failure(&canceller) { (errorInfo: ErrorInfo) -> Task in + return Task(value: failureClosure(errorInfo)) + } + } + + /// + /// `failure` (rejected or cancelled) + closure returning **task**. + /// (synonym for `flatMapError` in functional programming) + /// + /// - e.g. task.failure { errorInfo -> NextTaskType in ... } + /// - e.g. task.failure { error, isCancelled -> NextTaskType in ... } + /// + /// - Returns: New `Task` + /// + public func failure(failureClosure: ErrorInfo -> Task) -> Task + { + var dummyCanceller: Canceller? = nil + return self.failure(&dummyCanceller, failureClosure) + } + + public func failure(inout canceller: C?, _ failureClosure: ErrorInfo -> Task) -> Task + { + return Task { [unowned self] newMachine, progress, fulfill, _reject, configure in + + let selfMachine = self._machine + + self._then(&canceller) { + if let value = selfMachine.value.rawValue { + fulfill(value) + } + else if let errorInfo = selfMachine.errorInfo.rawValue { + let innerTask = failureClosure(errorInfo) + _bindInnerTask(innerTask, newMachine, progress, fulfill, _reject, configure) + } + } + + }.name("\(self.name)-failure") + } + + /// + /// Add side-effects after completion. + /// + /// - Note: This method doesn't create new task, so it has better performance over `then()`/`success()`/`failure()`. + /// - Returns: Self (same `Task`) + /// + public func on(success success: (Value -> Void)? = nil, failure: (ErrorInfo -> Void)? = nil) -> Self + { + var dummyCanceller: Canceller? = nil + return self.on(&dummyCanceller, success: success, failure: failure) + } + + public func on(inout canceller: C?, success: (Value -> Void)? = nil, failure: (ErrorInfo -> Void)? = nil) -> Self + { + let selfMachine = self._machine + + self._then(&canceller) { + if let value = selfMachine.value.rawValue { + success?(value) + } + else if let errorInfo = selfMachine.errorInfo.rawValue { + failure?(errorInfo) + } + } + + return self + } + + /// Pause task. + public func pause() -> Bool + { + return self._machine.handlePause() + } + + /// Resume task. + public func resume() -> Bool + { + return self._machine.handleResume() + } + + // + // NOTE: + // To conform to `Cancellable`, this method is needed in replace of: + // - `public func cancel(error: Error? = nil) -> Bool` + // - `public func cancel(_ error: Error? = nil) -> Bool` (segfault in Swift 1.2) + // + /// Cancel task. + public func cancel() -> Bool + { + return self.cancel(error: nil) + } + + /// Cancel task. + public func cancel(error error: Error?) -> Bool + { + return self._cancel(error) + } + + internal func _cancel(error: Error? = nil) -> Bool + { + return self._machine.handleCancel(error) + } + +} + +// MARK: - Helper + +internal func _bindInnerTask( + innerTask: Task, + _ newMachine: _StateMachine, + _ progress: Task.ProgressHandler, + _ fulfill: Task.FulfillHandler, + _ _reject: Task._RejectInfoHandler, + _ configure: TaskConfiguration + ) +{ + switch innerTask.state { + case .Fulfilled: + fulfill(innerTask.value!) + return + case .Rejected, .Cancelled: + let (error2, isCancelled) = innerTask.errorInfo! + + // NOTE: innerTask's `error2` will be treated as `nil` if not same type as outerTask's `Error` type + _reject((error2 as? Error, isCancelled)) + return + default: + break + } + + innerTask.progress { _, progressValue in + progress(progressValue) + }.then { (value: Value2?, errorInfo2: Task.ErrorInfo?) -> Void in + if let value = value { + fulfill(value) + } + else if let errorInfo2 = errorInfo2 { + let (error2, isCancelled) = errorInfo2 + + // NOTE: innerTask's `error2` will be treated as `nil` if not same type as outerTask's `Error` type + _reject((error2 as? Error, isCancelled)) + } + } + + configure.pause = { innerTask.pause(); return } + configure.resume = { innerTask.resume(); return } + configure.cancel = { innerTask.cancel(); return } + + // pause/cancel innerTask if descendant task is already paused/cancelled + if newMachine.state.rawValue == .Paused { + innerTask.pause() + } + else if newMachine.state.rawValue == .Cancelled { + innerTask.cancel() + } +} + +// MARK: - Multiple Tasks + +extension Task +{ + public typealias BulkProgress = (completedCount: Int, totalCount: Int) + + public class func all(tasks: [Task]) -> Task + { + guard !tasks.isEmpty else { + return Task(value: []) + } + + return Task { machine, progress, fulfill, _reject, configure in + + var completedCount = 0 + let totalCount = tasks.count + let lock = _RecursiveLock() + + for task in tasks { + task.success { (value: Value) -> Void in + + lock.lock() + completedCount += 1 + + let progressTuple = BulkProgress(completedCount: completedCount, totalCount: totalCount) + progress(progressTuple) + + if completedCount == totalCount { + var values: [Value] = Array() + + for task in tasks { + values.append(task.value!) + } + + fulfill(values) + } + lock.unlock() + + }.failure { (errorInfo: ErrorInfo) -> Void in + + lock.lock() + _reject(errorInfo) + + for task in tasks { + task.cancel() + } + lock.unlock() + } + } + + configure.pause = { self.pauseAll(tasks); return } + configure.resume = { self.resumeAll(tasks); return } + configure.cancel = { self.cancelAll(tasks); return } + + }.name("Task.all") + } + + public class func any(tasks: [Task]) -> Task + { + precondition(!tasks.isEmpty, "`Task.any(tasks)` with empty `tasks` should not be called. It will never be fulfilled or rejected.") + + return Task { machine, progress, fulfill, _reject, configure in + + var completedCount = 0 + var rejectedCount = 0 + let totalCount = tasks.count + let lock = _RecursiveLock() + + for task in tasks { + task.success { (value: Value) -> Void in + + lock.lock() + completedCount += 1 + + if completedCount == 1 { + fulfill(value) + + self.cancelAll(tasks) + } + lock.unlock() + + }.failure { (errorInfo: ErrorInfo) -> Void in + + lock.lock() + rejectedCount += 1 + + if rejectedCount == totalCount { + let isAnyCancelled = (tasks.filter { task in task.state == .Cancelled }.count > 0) + + let errorInfo = ErrorInfo(error: nil, isCancelled: isAnyCancelled) // NOTE: Task.any error returns nil (spec) + _reject(errorInfo) + } + lock.unlock() + } + } + + configure.pause = { self.pauseAll(tasks); return } + configure.resume = { self.resumeAll(tasks); return } + configure.cancel = { self.cancelAll(tasks); return } + + }.name("Task.any") + } + + /// Returns new task which performs all given tasks and stores only fulfilled values. + /// This new task will NEVER be internally rejected. + public class func some(tasks: [Task]) -> Task + { + guard !tasks.isEmpty else { + return Task(value: []) + } + + return Task { machine, progress, fulfill, _reject, configure in + + var completedCount = 0 + let totalCount = tasks.count + let lock = _RecursiveLock() + + for task in tasks { + task.then { (value: Value?, errorInfo: ErrorInfo?) -> Void in + + lock.lock() + completedCount += 1 + + let progressTuple = BulkProgress(completedCount: completedCount, totalCount: totalCount) + progress(progressTuple) + + if completedCount == totalCount { + var values: [Value] = Array() + + for task in tasks { + if task.state == .Fulfilled { + values.append(task.value!) + } + } + + fulfill(values) + } + lock.unlock() + + } + } + + configure.pause = { self.pauseAll(tasks); return } + configure.resume = { self.resumeAll(tasks); return } + configure.cancel = { self.cancelAll(tasks); return } + + }.name("Task.some") + } + + public class func cancelAll(tasks: [Task]) + { + for task in tasks { + task._cancel() + } + } + + public class func pauseAll(tasks: [Task]) + { + for task in tasks { + task.pause() + } + } + + public class func resumeAll(tasks: [Task]) + { + for task in tasks { + task.resume() + } + } +} \ No newline at end of file diff --git a/Pods/SwiftTask/SwiftTask/_Atomic.swift b/Pods/SwiftTask/SwiftTask/_Atomic.swift new file mode 100644 index 0000000..0f14c1a --- /dev/null +++ b/Pods/SwiftTask/SwiftTask/_Atomic.swift @@ -0,0 +1,96 @@ +// +// _Atomic.swift +// SwiftTask +// +// Created by Yasuhiro Inami on 2015/05/18. +// Copyright (c) 2015年 Yasuhiro Inami. All rights reserved. +// + +import Darwin + +internal final class _Atomic +{ + private var _spinlock = OS_SPINLOCK_INIT + private var _rawValue: T + + internal init(_ rawValue: T) + { + self._rawValue = rawValue + } + + internal func withRawValue(@noescape f: T -> U) -> U + { + self._lock() + defer { self._unlock() } + + return f(self._rawValue) + } + + internal func update(@noescape f: T -> T) -> T + { + return self.updateIf { f($0) }! + } + + internal func updateIf(@noescape f: T -> T?) -> T? + { + return self.modify { value in f(value).map { ($0, value) } } + } + + internal func modify(@noescape f: T -> (T, U)?) -> U? + { + self._lock() + defer { self._unlock() } + + let oldValue = self._rawValue + if let (newValue, retValue) = f(oldValue) { + self._rawValue = newValue + return retValue + } + else { + return nil + } + } + + private func _lock() + { + withUnsafeMutablePointer(&self._spinlock, OSSpinLockLock) + } + + private func _unlock() + { + withUnsafeMutablePointer(&self._spinlock, OSSpinLockUnlock) + } +} + +extension _Atomic: RawRepresentable +{ + internal convenience init(rawValue: T) + { + self.init(rawValue) + } + + internal var rawValue: T + { + get { + self._lock() + defer { self._unlock() } + + return self._rawValue + } + + set(newValue) { + self._lock() + defer { self._unlock() } + + self._rawValue = newValue + } + } +} + +extension _Atomic: CustomStringConvertible +{ + internal var description: String + { + return String(self.rawValue) + } +} \ No newline at end of file diff --git a/Pods/SwiftTask/SwiftTask/_RecursiveLock.swift b/Pods/SwiftTask/SwiftTask/_RecursiveLock.swift new file mode 100644 index 0000000..fb0a279 --- /dev/null +++ b/Pods/SwiftTask/SwiftTask/_RecursiveLock.swift @@ -0,0 +1,44 @@ +// +// _RecursiveLock.swift +// SwiftTask +// +// Created by Yasuhiro Inami on 2015/05/18. +// Copyright (c) 2015年 Yasuhiro Inami. All rights reserved. +// + +import Darwin + +internal final class _RecursiveLock +{ + private let mutex: UnsafeMutablePointer + private let attribute: UnsafeMutablePointer + + internal init() + { + self.mutex = UnsafeMutablePointer.alloc(1) + self.attribute = UnsafeMutablePointer.alloc(1) + + pthread_mutexattr_init(self.attribute) + pthread_mutexattr_settype(self.attribute, PTHREAD_MUTEX_RECURSIVE) + pthread_mutex_init(self.mutex, self.attribute) + } + + deinit + { + pthread_mutexattr_destroy(self.attribute) + pthread_mutex_destroy(self.mutex) + + self.attribute.dealloc(1) + self.mutex.dealloc(1) + } + + internal func lock() + { + pthread_mutex_lock(self.mutex) + } + + internal func unlock() + { + pthread_mutex_unlock(self.mutex) + } +} diff --git a/Pods/SwiftTask/SwiftTask/_StateMachine.swift b/Pods/SwiftTask/SwiftTask/_StateMachine.swift new file mode 100644 index 0000000..50f0fa9 --- /dev/null +++ b/Pods/SwiftTask/SwiftTask/_StateMachine.swift @@ -0,0 +1,282 @@ +// +// _StateMachine.swift +// SwiftTask +// +// Created by Yasuhiro Inami on 2015/01/21. +// Copyright (c) 2015年 Yasuhiro Inami. All rights reserved. +// + +import Foundation + +/// +/// fast, naive event-handler-manager in replace of ReactKit/SwiftState (dynamic but slow), +/// introduced from SwiftTask 2.6.0 +/// +/// see also: https://github.com/ReactKit/SwiftTask/pull/22 +/// +internal class _StateMachine +{ + internal typealias ErrorInfo = Task.ErrorInfo + internal typealias ProgressTupleHandler = Task._ProgressTupleHandler + + internal let weakified: Bool + internal let state: _Atomic + + internal let progress: _Atomic = _Atomic(nil) // NOTE: always nil if `weakified = true` + internal let value: _Atomic = _Atomic(nil) + internal let errorInfo: _Atomic = _Atomic(nil) + + internal let configuration = TaskConfiguration() + + /// wrapper closure for `_initClosure` to invoke only once when started `.Running`, + /// and will be set to `nil` afterward + internal var initResumeClosure: _Atomic<(Void -> Void)?> = _Atomic(nil) + + private lazy var _progressTupleHandlers = _Handlers() + private lazy var _completionHandlers = _Handlers Void>() + + private var _lock = _RecursiveLock() + + internal init(weakified: Bool, paused: Bool) + { + self.weakified = weakified + self.state = _Atomic(paused ? .Paused : .Running) + } + + internal func addProgressTupleHandler(inout token: _HandlerToken?, _ progressTupleHandler: ProgressTupleHandler) -> Bool + { + self._lock.lock() + defer { self._lock.unlock() } + + if self.state.rawValue == .Running || self.state.rawValue == .Paused { + token = self._progressTupleHandlers.append(progressTupleHandler) + return token != nil + } + else { + return false + } + } + + internal func removeProgressTupleHandler(handlerToken: _HandlerToken?) -> Bool + { + self._lock.lock() + defer { self._lock.unlock() } + + if let handlerToken = handlerToken { + let removedHandler = self._progressTupleHandlers.remove(handlerToken) + return removedHandler != nil + } + else { + return false + } + } + + internal func addCompletionHandler(inout token: _HandlerToken?, _ completionHandler: Void -> Void) -> Bool + { + self._lock.lock() + defer { self._lock.unlock() } + + if self.state.rawValue == .Running || self.state.rawValue == .Paused { + token = self._completionHandlers.append(completionHandler) + return token != nil + } + else { + return false + } + } + + internal func removeCompletionHandler(handlerToken: _HandlerToken?) -> Bool + { + self._lock.lock() + defer { self._lock.unlock() } + + if let handlerToken = handlerToken { + let removedHandler = self._completionHandlers.remove(handlerToken) + return removedHandler != nil + } + else { + return false + } + } + + internal func handleProgress(progress: Progress) + { + self._lock.lock() + defer { self._lock.unlock() } + + if self.state.rawValue == .Running { + + let oldProgress = self.progress.rawValue + + // NOTE: if `weakified = false`, don't store progressValue for less memory footprint + if !self.weakified { + self.progress.rawValue = progress + } + + for handler in self._progressTupleHandlers { + handler(oldProgress: oldProgress, newProgress: progress) + } + } + } + + internal func handleFulfill(value: Value) + { + self._lock.lock() + defer { self._lock.unlock() } + + let newState = self.state.updateIf { $0 == .Running ? .Fulfilled : nil } + if let _ = newState { + self.value.rawValue = value + self._finish() + } + } + + internal func handleRejectInfo(errorInfo: ErrorInfo) + { + self._lock.lock() + defer { self._lock.unlock() } + + let toState = errorInfo.isCancelled ? TaskState.Cancelled : .Rejected + let newState = self.state.updateIf { $0 == .Running || $0 == .Paused ? toState : nil } + if let _ = newState { + self.errorInfo.rawValue = errorInfo + self._finish() + } + } + + internal func handlePause() -> Bool + { + self._lock.lock() + defer { self._lock.unlock() } + + let newState = self.state.updateIf { $0 == .Running ? .Paused : nil } + if let _ = newState { + self.configuration.pause?() + return true + } + else { + return false + } + } + + internal func handleResume() -> Bool + { + self._lock.lock() + + if let initResumeClosure = self.initResumeClosure.update({ _ in nil }) { + + self.state.rawValue = .Running + self._lock.unlock() + + // + // NOTE: + // Don't use `_lock` here so that dispatch_async'ed `handleProgress` inside `initResumeClosure()` + // will be safely called even when current thread goes into sleep. + // + initResumeClosure() + + // + // Comment-Out: + // Don't call `configuration.resume()` when lazy starting. + // This prevents inapropriate starting of upstream in ReactKit. + // + //self.configuration.resume?() + + return true + } + else { + let resumed = _handleResume() + self._lock.unlock() + return resumed + } + } + + private func _handleResume() -> Bool + { + let newState = self.state.updateIf { $0 == .Paused ? .Running : nil } + if let _ = newState { + self.configuration.resume?() + return true + } + else { + return false + } + } + + internal func handleCancel(error: Error? = nil) -> Bool + { + self._lock.lock() + defer { self._lock.unlock() } + + let newState = self.state.updateIf { $0 == .Running || $0 == .Paused ? .Cancelled : nil } + if let _ = newState { + self.errorInfo.rawValue = ErrorInfo(error: error, isCancelled: true) + self._finish() + return true + } + else { + return false + } + } + + private func _finish() + { + for handler in self._completionHandlers { + handler() + } + + self._progressTupleHandlers.removeAll() + self._completionHandlers.removeAll() + + self.configuration.finish() + + self.initResumeClosure.rawValue = nil + self.progress.rawValue = nil + } +} + +//-------------------------------------------------- +// MARK: - Utility +//-------------------------------------------------- + +internal struct _HandlerToken +{ + internal let key: Int +} + +internal struct _Handlers: SequenceType +{ + internal typealias KeyValue = (key: Int, value: T) + + private var currentKey: Int = 0 + private var elements = [KeyValue]() + + internal mutating func append(value: T) -> _HandlerToken + { + self.currentKey = self.currentKey &+ 1 + + self.elements += [(key: self.currentKey, value: value)] + + return _HandlerToken(key: self.currentKey) + } + + internal mutating func remove(token: _HandlerToken) -> T? + { + for i in 0.. AnyGenerator + { + return AnyGenerator(self.elements.map { $0.value }.generate()) + } +} \ No newline at end of file diff --git a/Pods/Target Support Files/Alamofire/Alamofire-dummy.m b/Pods/Target Support Files/Alamofire/Alamofire-dummy.m new file mode 100644 index 0000000..a6c4594 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Alamofire : NSObject +@end +@implementation PodsDummy_Alamofire +@end diff --git a/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch b/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch new file mode 100644 index 0000000..aa992a4 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch @@ -0,0 +1,4 @@ +#ifdef __OBJC__ +#import +#endif + diff --git a/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h b/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h new file mode 100644 index 0000000..6b71676 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h @@ -0,0 +1,6 @@ +#import + + +FOUNDATION_EXPORT double AlamofireVersionNumber; +FOUNDATION_EXPORT const unsigned char AlamofireVersionString[]; + diff --git a/Pods/Target Support Files/Alamofire/Alamofire.modulemap b/Pods/Target Support Files/Alamofire/Alamofire.modulemap new file mode 100644 index 0000000..d1f125f --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire.modulemap @@ -0,0 +1,6 @@ +framework module Alamofire { + umbrella header "Alamofire-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Alamofire/Alamofire.xcconfig b/Pods/Target Support Files/Alamofire/Alamofire.xcconfig new file mode 100644 index 0000000..772ef0b --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Alamofire +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/Alamofire/Info.plist b/Pods/Target Support Files/Alamofire/Info.plist new file mode 100644 index 0000000..7694605 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 3.4.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Astro/Astro-dummy.m b/Pods/Target Support Files/Astro/Astro-dummy.m new file mode 100644 index 0000000..8f65378 --- /dev/null +++ b/Pods/Target Support Files/Astro/Astro-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Astro : NSObject +@end +@implementation PodsDummy_Astro +@end diff --git a/Pods/Target Support Files/Astro/Astro-prefix.pch b/Pods/Target Support Files/Astro/Astro-prefix.pch new file mode 100644 index 0000000..aa992a4 --- /dev/null +++ b/Pods/Target Support Files/Astro/Astro-prefix.pch @@ -0,0 +1,4 @@ +#ifdef __OBJC__ +#import +#endif + diff --git a/Pods/Target Support Files/Astro/Astro-umbrella.h b/Pods/Target Support Files/Astro/Astro-umbrella.h new file mode 100644 index 0000000..db9dc85 --- /dev/null +++ b/Pods/Target Support Files/Astro/Astro-umbrella.h @@ -0,0 +1,6 @@ +#import + + +FOUNDATION_EXPORT double AstroVersionNumber; +FOUNDATION_EXPORT const unsigned char AstroVersionString[]; + diff --git a/Pods/Target Support Files/Astro/Astro.modulemap b/Pods/Target Support Files/Astro/Astro.modulemap new file mode 100644 index 0000000..811a32e --- /dev/null +++ b/Pods/Target Support Files/Astro/Astro.modulemap @@ -0,0 +1,6 @@ +framework module Astro { + umbrella header "Astro-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Astro/Astro.xcconfig b/Pods/Target Support Files/Astro/Astro.xcconfig new file mode 100644 index 0000000..a71a07b --- /dev/null +++ b/Pods/Target Support Files/Astro/Astro.xcconfig @@ -0,0 +1,11 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Astro +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/Freddy" "$PODS_CONFIGURATION_BUILD_DIR/SwiftTask" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_LDFLAGS = -framework "UIKit" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/Astro/Info.plist b/Pods/Target Support Files/Astro/Info.plist new file mode 100644 index 0000000..fa61356 --- /dev/null +++ b/Pods/Target Support Files/Astro/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.8.7 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Freddy/Freddy-dummy.m b/Pods/Target Support Files/Freddy/Freddy-dummy.m new file mode 100644 index 0000000..49ba8f5 --- /dev/null +++ b/Pods/Target Support Files/Freddy/Freddy-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Freddy : NSObject +@end +@implementation PodsDummy_Freddy +@end diff --git a/Pods/Target Support Files/Freddy/Freddy-prefix.pch b/Pods/Target Support Files/Freddy/Freddy-prefix.pch new file mode 100644 index 0000000..aa992a4 --- /dev/null +++ b/Pods/Target Support Files/Freddy/Freddy-prefix.pch @@ -0,0 +1,4 @@ +#ifdef __OBJC__ +#import +#endif + diff --git a/Pods/Target Support Files/Freddy/Freddy-umbrella.h b/Pods/Target Support Files/Freddy/Freddy-umbrella.h new file mode 100644 index 0000000..7e27ee2 --- /dev/null +++ b/Pods/Target Support Files/Freddy/Freddy-umbrella.h @@ -0,0 +1,7 @@ +#import + +#import "Freddy.h" + +FOUNDATION_EXPORT double FreddyVersionNumber; +FOUNDATION_EXPORT const unsigned char FreddyVersionString[]; + diff --git a/Pods/Target Support Files/Freddy/Freddy.modulemap b/Pods/Target Support Files/Freddy/Freddy.modulemap new file mode 100644 index 0000000..3a4c0c7 --- /dev/null +++ b/Pods/Target Support Files/Freddy/Freddy.modulemap @@ -0,0 +1,6 @@ +framework module Freddy { + umbrella header "Freddy-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Freddy/Freddy.xcconfig b/Pods/Target Support Files/Freddy/Freddy.xcconfig new file mode 100644 index 0000000..ce5d0ea --- /dev/null +++ b/Pods/Target Support Files/Freddy/Freddy.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Freddy +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/Freddy/Info.plist b/Pods/Target Support Files/Freddy/Info.plist new file mode 100644 index 0000000..7f71fff --- /dev/null +++ b/Pods/Target Support Files/Freddy/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 2.1.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Nimble/Info.plist b/Pods/Target Support Files/Nimble/Info.plist new file mode 100644 index 0000000..9ae03a0 --- /dev/null +++ b/Pods/Target Support Files/Nimble/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 3.2.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Nimble/Nimble-dummy.m b/Pods/Target Support Files/Nimble/Nimble-dummy.m new file mode 100644 index 0000000..e8177ab --- /dev/null +++ b/Pods/Target Support Files/Nimble/Nimble-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Nimble : NSObject +@end +@implementation PodsDummy_Nimble +@end diff --git a/Pods/Target Support Files/Nimble/Nimble-prefix.pch b/Pods/Target Support Files/Nimble/Nimble-prefix.pch new file mode 100644 index 0000000..aa992a4 --- /dev/null +++ b/Pods/Target Support Files/Nimble/Nimble-prefix.pch @@ -0,0 +1,4 @@ +#ifdef __OBJC__ +#import +#endif + diff --git a/Pods/Target Support Files/Nimble/Nimble-umbrella.h b/Pods/Target Support Files/Nimble/Nimble-umbrella.h new file mode 100644 index 0000000..5e5b5c8 --- /dev/null +++ b/Pods/Target Support Files/Nimble/Nimble-umbrella.h @@ -0,0 +1,9 @@ +#import + +#import "Nimble.h" +#import "DSL.h" +#import "NMBExceptionCapture.h" + +FOUNDATION_EXPORT double NimbleVersionNumber; +FOUNDATION_EXPORT const unsigned char NimbleVersionString[]; + diff --git a/Pods/Target Support Files/Nimble/Nimble.modulemap b/Pods/Target Support Files/Nimble/Nimble.modulemap new file mode 100644 index 0000000..6f77009 --- /dev/null +++ b/Pods/Target Support Files/Nimble/Nimble.modulemap @@ -0,0 +1,6 @@ +framework module Nimble { + umbrella header "Nimble-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Nimble/Nimble.xcconfig b/Pods/Target Support Files/Nimble/Nimble.xcconfig new file mode 100644 index 0000000..bc9e893 --- /dev/null +++ b/Pods/Target Support Files/Nimble/Nimble.xcconfig @@ -0,0 +1,12 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Nimble +ENABLE_BITCODE = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "$(PLATFORM_DIR)/Developer/Library/Frameworks" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_LDFLAGS = -weak-lswiftXCTest -weak_framework "XCTest" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/Nocilla/Info.plist b/Pods/Target Support Files/Nocilla/Info.plist new file mode 100644 index 0000000..1b8f7d0 --- /dev/null +++ b/Pods/Target Support Files/Nocilla/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.11.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Nocilla/Nocilla-dummy.m b/Pods/Target Support Files/Nocilla/Nocilla-dummy.m new file mode 100644 index 0000000..bf67e7a --- /dev/null +++ b/Pods/Target Support Files/Nocilla/Nocilla-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Nocilla : NSObject +@end +@implementation PodsDummy_Nocilla +@end diff --git a/Pods/Target Support Files/Nocilla/Nocilla-prefix.pch b/Pods/Target Support Files/Nocilla/Nocilla-prefix.pch new file mode 100644 index 0000000..aa992a4 --- /dev/null +++ b/Pods/Target Support Files/Nocilla/Nocilla-prefix.pch @@ -0,0 +1,4 @@ +#ifdef __OBJC__ +#import +#endif + diff --git a/Pods/Target Support Files/Nocilla/Nocilla-umbrella.h b/Pods/Target Support Files/Nocilla/Nocilla-umbrella.h new file mode 100644 index 0000000..e8b33f7 --- /dev/null +++ b/Pods/Target Support Files/Nocilla/Nocilla-umbrella.h @@ -0,0 +1,18 @@ +#import + +#import "NSData+Nocilla.h" +#import "NSString+Nocilla.h" +#import "LSStubRequestDSL.h" +#import "LSStubResponseDSL.h" +#import "LSNocilla.h" +#import "LSMatcheable.h" +#import "LSMatcher.h" +#import "NSData+Matcheable.h" +#import "NSRegularExpression+Matcheable.h" +#import "NSString+Matcheable.h" +#import "LSHTTPBody.h" +#import "Nocilla.h" + +FOUNDATION_EXPORT double NocillaVersionNumber; +FOUNDATION_EXPORT const unsigned char NocillaVersionString[]; + diff --git a/Pods/Target Support Files/Nocilla/Nocilla.modulemap b/Pods/Target Support Files/Nocilla/Nocilla.modulemap new file mode 100644 index 0000000..01df4e2 --- /dev/null +++ b/Pods/Target Support Files/Nocilla/Nocilla.modulemap @@ -0,0 +1,6 @@ +framework module Nocilla { + umbrella header "Nocilla-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Nocilla/Nocilla.xcconfig b/Pods/Target Support Files/Nocilla/Nocilla.xcconfig new file mode 100644 index 0000000..2598e3c --- /dev/null +++ b/Pods/Target Support Files/Nocilla/Nocilla.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Nocilla +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_LDFLAGS = -framework "CFNetwork" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/Pods-Astro/Info.plist b/Pods/Target Support Files/Pods-Astro/Info.plist new file mode 100644 index 0000000..2243fe6 --- /dev/null +++ b/Pods/Target Support Files/Pods-Astro/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Pods-Astro/Pods-Astro-acknowledgements.markdown b/Pods/Target Support Files/Pods-Astro/Pods-Astro-acknowledgements.markdown new file mode 100644 index 0000000..c35eb93 --- /dev/null +++ b/Pods/Target Support Files/Pods-Astro/Pods-Astro-acknowledgements.markdown @@ -0,0 +1,85 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## Alamofire + +Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +## Astro + +Copyright (c) 2015 Robots and Pencils, Inc. All rights reserved. +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: +Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +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. + + +## Freddy + +The MIT License (MIT) + +Copyright (c) 2015 Big Nerd Ranch Inc + +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. + + +## SwiftTask + +The MIT License (MIT) + +Copyright (c) 2014 Yasuhiro Inami + +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 - https://cocoapods.org diff --git a/Pods/Target Support Files/Pods-Astro/Pods-Astro-acknowledgements.plist b/Pods/Target Support Files/Pods-Astro/Pods-Astro-acknowledgements.plist new file mode 100644 index 0000000..ec92f7e --- /dev/null +++ b/Pods/Target Support Files/Pods-Astro/Pods-Astro-acknowledgements.plist @@ -0,0 +1,127 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + Title + Alamofire + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2015 Robots and Pencils, Inc. All rights reserved. +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: +Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +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 + Astro + Type + PSGroupSpecifier + + + FooterText + The MIT License (MIT) + +Copyright (c) 2015 Big Nerd Ranch Inc + +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 + Freddy + Type + PSGroupSpecifier + + + FooterText + The MIT License (MIT) + +Copyright (c) 2014 Yasuhiro Inami + +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 + SwiftTask + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Pods/Target Support Files/Pods-Astro/Pods-Astro-dummy.m b/Pods/Target Support Files/Pods-Astro/Pods-Astro-dummy.m new file mode 100644 index 0000000..566313e --- /dev/null +++ b/Pods/Target Support Files/Pods-Astro/Pods-Astro-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_Astro : NSObject +@end +@implementation PodsDummy_Pods_Astro +@end diff --git a/Pods/Target Support Files/Pods-Astro/Pods-Astro-frameworks.sh b/Pods/Target Support Files/Pods-Astro/Pods-Astro-frameworks.sh new file mode 100755 index 0000000..7c2978c --- /dev/null +++ b/Pods/Target Support Files/Pods-Astro/Pods-Astro-frameworks.sh @@ -0,0 +1,97 @@ +#!/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="${TARGET_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} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\"" + /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --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 +} + + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" + install_framework "$BUILT_PRODUCTS_DIR/Astro/Astro.framework" + install_framework "$BUILT_PRODUCTS_DIR/Freddy/Freddy.framework" + install_framework "$BUILT_PRODUCTS_DIR/SwiftTask/SwiftTask.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" + install_framework "$BUILT_PRODUCTS_DIR/Astro/Astro.framework" + install_framework "$BUILT_PRODUCTS_DIR/Freddy/Freddy.framework" + install_framework "$BUILT_PRODUCTS_DIR/SwiftTask/SwiftTask.framework" +fi diff --git a/Pods/Target Support Files/Pods-Astro/Pods-Astro-resources.sh b/Pods/Target Support Files/Pods-Astro/Pods-Astro-resources.sh new file mode 100755 index 0000000..0a15615 --- /dev/null +++ b/Pods/Target Support Files/Pods-Astro/Pods-Astro-resources.sh @@ -0,0 +1,102 @@ +#!/bin/sh +set -e + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +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 + +realpath() { + DIRECTORY="$(cd "${1%/*}" && pwd)" + FILENAME="${1##*/}" + echo "$DIRECTORY/$FILENAME" +} + +install_resource() +{ + if [[ "$1" = /* ]] ; then + RESOURCE_PATH="$1" + else + RESOURCE_PATH="${PODS_ROOT}/$1" + fi + if [[ ! -e "$RESOURCE_PATH" ]] ; then + cat << EOM +error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. +EOM + exit 1 + fi + case $RESOURCE_PATH in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.framework) + echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" + xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE=$(realpath "$RESOURCE_PATH") + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + *) + echo "$RESOURCE_PATH" + echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_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 + # 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 "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi diff --git a/Pods/Target Support Files/Pods-Astro/Pods-Astro-umbrella.h b/Pods/Target Support Files/Pods-Astro/Pods-Astro-umbrella.h new file mode 100644 index 0000000..80a9e38 --- /dev/null +++ b/Pods/Target Support Files/Pods-Astro/Pods-Astro-umbrella.h @@ -0,0 +1,6 @@ +#import + + +FOUNDATION_EXPORT double Pods_AstroVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_AstroVersionString[]; + diff --git a/Pods/Target Support Files/Pods-Astro/Pods-Astro.debug.xcconfig b/Pods/Target Support Files/Pods-Astro/Pods-Astro.debug.xcconfig new file mode 100644 index 0000000..d8c490f --- /dev/null +++ b/Pods/Target Support Files/Pods-Astro/Pods-Astro.debug.xcconfig @@ -0,0 +1,10 @@ +EMBEDDED_CONTENT_CONTAINS_SWIFT = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/Astro" "$PODS_CONFIGURATION_BUILD_DIR/Freddy" "$PODS_CONFIGURATION_BUILD_DIR/SwiftTask" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/Astro/Astro.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/Freddy/Freddy.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/SwiftTask/SwiftTask.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "Astro" -framework "Freddy" -framework "SwiftTask" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT}/Pods diff --git a/Pods/Target Support Files/Pods-Astro/Pods-Astro.modulemap b/Pods/Target Support Files/Pods-Astro/Pods-Astro.modulemap new file mode 100644 index 0000000..950a0e4 --- /dev/null +++ b/Pods/Target Support Files/Pods-Astro/Pods-Astro.modulemap @@ -0,0 +1,6 @@ +framework module Pods_Astro { + umbrella header "Pods-Astro-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Pods-Astro/Pods-Astro.release.xcconfig b/Pods/Target Support Files/Pods-Astro/Pods-Astro.release.xcconfig new file mode 100644 index 0000000..d8c490f --- /dev/null +++ b/Pods/Target Support Files/Pods-Astro/Pods-Astro.release.xcconfig @@ -0,0 +1,10 @@ +EMBEDDED_CONTENT_CONTAINS_SWIFT = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/Astro" "$PODS_CONFIGURATION_BUILD_DIR/Freddy" "$PODS_CONFIGURATION_BUILD_DIR/SwiftTask" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/Astro/Astro.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/Freddy/Freddy.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/SwiftTask/SwiftTask.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "Astro" -framework "Freddy" -framework "SwiftTask" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT}/Pods diff --git a/Pods/Target Support Files/Pods-AstroTests/Info.plist b/Pods/Target Support Files/Pods-AstroTests/Info.plist new file mode 100644 index 0000000..2243fe6 --- /dev/null +++ b/Pods/Target Support Files/Pods-AstroTests/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-acknowledgements.markdown b/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-acknowledgements.markdown new file mode 100644 index 0000000..6c951aa --- /dev/null +++ b/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-acknowledgements.markdown @@ -0,0 +1,437 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## Nimble + +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2014 Quick Team + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +## Nocilla + +Copyright (c) 2012 Luis Solano Bonet +MIT License + +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. + +## Quick + +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2014, Quick Team + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Generated by CocoaPods - https://cocoapods.org diff --git a/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-acknowledgements.plist b/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-acknowledgements.plist new file mode 100644 index 0000000..32fc511 --- /dev/null +++ b/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-acknowledgements.plist @@ -0,0 +1,475 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2014 Quick Team + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Title + Nimble + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2012 Luis Solano Bonet +MIT License + +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 + Nocilla + Type + PSGroupSpecifier + + + FooterText + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2014, Quick Team + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Title + Quick + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-dummy.m b/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-dummy.m new file mode 100644 index 0000000..d3b668e --- /dev/null +++ b/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_AstroTests : NSObject +@end +@implementation PodsDummy_Pods_AstroTests +@end diff --git a/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-frameworks.sh b/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-frameworks.sh new file mode 100755 index 0000000..9913aab --- /dev/null +++ b/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-frameworks.sh @@ -0,0 +1,95 @@ +#!/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="${TARGET_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} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\"" + /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --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 +} + + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "$BUILT_PRODUCTS_DIR/Nimble/Nimble.framework" + install_framework "$BUILT_PRODUCTS_DIR/Nocilla/Nocilla.framework" + install_framework "$BUILT_PRODUCTS_DIR/Quick/Quick.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "$BUILT_PRODUCTS_DIR/Nimble/Nimble.framework" + install_framework "$BUILT_PRODUCTS_DIR/Nocilla/Nocilla.framework" + install_framework "$BUILT_PRODUCTS_DIR/Quick/Quick.framework" +fi diff --git a/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-resources.sh b/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-resources.sh new file mode 100755 index 0000000..0a15615 --- /dev/null +++ b/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-resources.sh @@ -0,0 +1,102 @@ +#!/bin/sh +set -e + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +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 + +realpath() { + DIRECTORY="$(cd "${1%/*}" && pwd)" + FILENAME="${1##*/}" + echo "$DIRECTORY/$FILENAME" +} + +install_resource() +{ + if [[ "$1" = /* ]] ; then + RESOURCE_PATH="$1" + else + RESOURCE_PATH="${PODS_ROOT}/$1" + fi + if [[ ! -e "$RESOURCE_PATH" ]] ; then + cat << EOM +error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. +EOM + exit 1 + fi + case $RESOURCE_PATH in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.framework) + echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" + xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE=$(realpath "$RESOURCE_PATH") + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + *) + echo "$RESOURCE_PATH" + echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_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 + # 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 "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi diff --git a/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-umbrella.h b/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-umbrella.h new file mode 100644 index 0000000..8d80a8c --- /dev/null +++ b/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests-umbrella.h @@ -0,0 +1,6 @@ +#import + + +FOUNDATION_EXPORT double Pods_AstroTestsVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_AstroTestsVersionString[]; + diff --git a/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests.debug.xcconfig b/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests.debug.xcconfig new file mode 100644 index 0000000..29ae579 --- /dev/null +++ b/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests.debug.xcconfig @@ -0,0 +1,10 @@ +EMBEDDED_CONTENT_CONTAINS_SWIFT = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) $(PLATFORM_DIR)/Developer/Library/Frameworks "$PODS_CONFIGURATION_BUILD_DIR/Nimble" "$PODS_CONFIGURATION_BUILD_DIR/Nocilla" "$PODS_CONFIGURATION_BUILD_DIR/Quick" "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/Astro" "$PODS_CONFIGURATION_BUILD_DIR/Freddy" "$PODS_CONFIGURATION_BUILD_DIR/SwiftTask" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Nimble/Nimble.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/Nocilla/Nocilla.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/Quick/Quick.framework/Headers" $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/Astro/Astro.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/Freddy/Freddy.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/SwiftTask/SwiftTask.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Nimble" -framework "Nocilla" -framework "Quick" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT}/Pods diff --git a/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests.modulemap b/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests.modulemap new file mode 100644 index 0000000..9495844 --- /dev/null +++ b/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests.modulemap @@ -0,0 +1,6 @@ +framework module Pods_AstroTests { + umbrella header "Pods-AstroTests-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests.release.xcconfig b/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests.release.xcconfig new file mode 100644 index 0000000..29ae579 --- /dev/null +++ b/Pods/Target Support Files/Pods-AstroTests/Pods-AstroTests.release.xcconfig @@ -0,0 +1,10 @@ +EMBEDDED_CONTENT_CONTAINS_SWIFT = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) $(PLATFORM_DIR)/Developer/Library/Frameworks "$PODS_CONFIGURATION_BUILD_DIR/Nimble" "$PODS_CONFIGURATION_BUILD_DIR/Nocilla" "$PODS_CONFIGURATION_BUILD_DIR/Quick" "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/Astro" "$PODS_CONFIGURATION_BUILD_DIR/Freddy" "$PODS_CONFIGURATION_BUILD_DIR/SwiftTask" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Nimble/Nimble.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/Nocilla/Nocilla.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/Quick/Quick.framework/Headers" $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/Astro/Astro.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/Freddy/Freddy.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/SwiftTask/SwiftTask.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Nimble" -framework "Nocilla" -framework "Quick" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT}/Pods diff --git a/Pods/Target Support Files/Quick/Info.plist b/Pods/Target Support Files/Quick/Info.plist new file mode 100644 index 0000000..b8a90bb --- /dev/null +++ b/Pods/Target Support Files/Quick/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.9.3 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Quick/Quick-dummy.m b/Pods/Target Support Files/Quick/Quick-dummy.m new file mode 100644 index 0000000..54d7dc0 --- /dev/null +++ b/Pods/Target Support Files/Quick/Quick-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Quick : NSObject +@end +@implementation PodsDummy_Quick +@end diff --git a/Pods/Target Support Files/Quick/Quick-prefix.pch b/Pods/Target Support Files/Quick/Quick-prefix.pch new file mode 100644 index 0000000..aa992a4 --- /dev/null +++ b/Pods/Target Support Files/Quick/Quick-prefix.pch @@ -0,0 +1,4 @@ +#ifdef __OBJC__ +#import +#endif + diff --git a/Pods/Target Support Files/Quick/Quick-umbrella.h b/Pods/Target Support Files/Quick/Quick-umbrella.h new file mode 100644 index 0000000..c1aab14 --- /dev/null +++ b/Pods/Target Support Files/Quick/Quick-umbrella.h @@ -0,0 +1,10 @@ +#import + +#import "QuickConfiguration.h" +#import "QCKDSL.h" +#import "Quick.h" +#import "QuickSpec.h" + +FOUNDATION_EXPORT double QuickVersionNumber; +FOUNDATION_EXPORT const unsigned char QuickVersionString[]; + diff --git a/Pods/Target Support Files/Quick/Quick.modulemap b/Pods/Target Support Files/Quick/Quick.modulemap new file mode 100644 index 0000000..1d12b21 --- /dev/null +++ b/Pods/Target Support Files/Quick/Quick.modulemap @@ -0,0 +1,6 @@ +framework module Quick { + umbrella header "Quick-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Quick/Quick.xcconfig b/Pods/Target Support Files/Quick/Quick.xcconfig new file mode 100644 index 0000000..f25ce83 --- /dev/null +++ b/Pods/Target Support Files/Quick/Quick.xcconfig @@ -0,0 +1,12 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Quick +ENABLE_BITCODE = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "$(PLATFORM_DIR)/Developer/Library/Frameworks" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_LDFLAGS = -framework "XCTest" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/SwiftTask/Info.plist b/Pods/Target Support Files/SwiftTask/Info.plist new file mode 100644 index 0000000..e2771ff --- /dev/null +++ b/Pods/Target Support Files/SwiftTask/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 5.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/SwiftTask/SwiftTask-dummy.m b/Pods/Target Support Files/SwiftTask/SwiftTask-dummy.m new file mode 100644 index 0000000..05ecdf0 --- /dev/null +++ b/Pods/Target Support Files/SwiftTask/SwiftTask-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_SwiftTask : NSObject +@end +@implementation PodsDummy_SwiftTask +@end diff --git a/Pods/Target Support Files/SwiftTask/SwiftTask-prefix.pch b/Pods/Target Support Files/SwiftTask/SwiftTask-prefix.pch new file mode 100644 index 0000000..aa992a4 --- /dev/null +++ b/Pods/Target Support Files/SwiftTask/SwiftTask-prefix.pch @@ -0,0 +1,4 @@ +#ifdef __OBJC__ +#import +#endif + diff --git a/Pods/Target Support Files/SwiftTask/SwiftTask-umbrella.h b/Pods/Target Support Files/SwiftTask/SwiftTask-umbrella.h new file mode 100644 index 0000000..5c4a480 --- /dev/null +++ b/Pods/Target Support Files/SwiftTask/SwiftTask-umbrella.h @@ -0,0 +1,7 @@ +#import + +#import "SwiftTask.h" + +FOUNDATION_EXPORT double SwiftTaskVersionNumber; +FOUNDATION_EXPORT const unsigned char SwiftTaskVersionString[]; + diff --git a/Pods/Target Support Files/SwiftTask/SwiftTask.modulemap b/Pods/Target Support Files/SwiftTask/SwiftTask.modulemap new file mode 100644 index 0000000..d539e70 --- /dev/null +++ b/Pods/Target Support Files/SwiftTask/SwiftTask.modulemap @@ -0,0 +1,6 @@ +framework module SwiftTask { + umbrella header "SwiftTask-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/SwiftTask/SwiftTask.xcconfig b/Pods/Target Support Files/SwiftTask/SwiftTask.xcconfig new file mode 100644 index 0000000..e7e7efe --- /dev/null +++ b/Pods/Target Support Files/SwiftTask/SwiftTask.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/SwiftTask +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/README.md b/README.md new file mode 100644 index 0000000..17b6bd7 --- /dev/null +++ b/README.md @@ -0,0 +1,369 @@ +# Astro + +Astro is a library, built in swift, used to hold common utility methods. + + + +**Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)* + +- [Requirements](#requirements) +- [Installation](#installation) + - [CocoaPods (iOS 8+)](#cocoapods-ios-8) +- [Modules](#modules) + - [Logging](#logging) + - [Networking](#networking) + - [HTTPStatusCode](#httpstatuscode) + - [Route](#route) + - [NetworkService](#networkservice) + - [Security](#security) + - [UI](#ui) + - [UIColor Extension](#uicolor-extension) + - [Reusable Cell Protocols](#reusable-cell-protocols) + - [ReusableView](#reusableview) + - [NibLoadableView](#nibloadableview) + - [ReusableView + NibLoadableView in Tandem](#reusableview--nibloadableview-in-tandem) + - [Utils](#utils) + - [EnumCountable](#enumcountable) + - [Queue](#queue) +- [Module Management](#module-management) +- [Contact](#contact) + - [Maintainers](#maintainers) +- [License](#license) + + + +## Requirements + +- iOS 8.0+ +- Xcode 7 + +## Installation + +#### CocoaPods (iOS 8+) +To integrate `Astro` into your Xcode project using [Cocoapods](http://cocoapods.org/), specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '8.0' +use_frameworks! + +pod 'Astro' +``` + +Or if you don't want the whole enchilada then grab one of the subspecs: + +```ruby +pod 'Astro/Logging' +pod 'Astro/Networking' +pod 'Astro/Security' +pod 'Astro/UI' +``` + +## Modules + +### Logging + +`Log` is a structure that streamlines the printing of log messages. + +Out of the box, you will be able to log error messages. + +```swift +Log.error("I want to log an error message with \(something)") +``` + +However, if you want to see more information you can override the logging level as you wish. For example: + +```swift +#if DEBUG + Log.level = .Debug +#else + Log.level = .Silent +#endif + +Log.info("I want to log an info message with \(something)") +Log.debug("I want to log a debug message with \(somethingElse)") +Log.warning("I want to log a warning message with \(somethingOtherThanElse)") +``` + +You can also write a custom logger as long as it conforms to the `Logger` protocol. +```swift +Log.logger = MyCustomLogger() +``` + +### Networking + +#### HTTPStatusCode +`HTTPStatusCode` is an enum that allows you to clarify status codes returned by your server and includes some more user friendly messaging for `failureReason` and `recoverySuggestion`. + +```swift +guard let code = HTTPStatusCode(rawValue: error.code) else { return } +switch code { +case .Code401Unauthorized: + // Handle unauthorized error, possibly by navigating back to the login screen + break +default: + // Handle other cases by presenting an alert with the failure reason and recovery suggestion + let alertController = UIAlertController(title: code.failureReason, message: code.recoverySuggestion, preferredStyle: .Alert) + let OKAction = UIAlertAction(title: "OK", style: .Default, handler: nil) + alertController.addAction(OKAction) + self.presentViewController(alertController, animated: true, completion: nil) + break +} +``` + +#### Route +`Route` provides a simple abstraction for working with `NSURLRequests`. Recommended approach is to add extensions to `Route` to add a default `baseURL` value and static functions for your specific API. + +```swift +extension Route { + public init(path: String, method: Alamofire.Method = .GET, JSON: Freddy.JSON, additionalHeaders: [String: String] = [:]) { + self.init(baseURL: NSURL(string: "https://myapp.com/api/v1/")!, path: path, method: method, parameters: RequestParameters.JSON(parameters: JSON), additionalHeaders: additionalHeaders) + } + + static func login(username username: String, password: String) -> Route { + return Route(path: "token", method: .POST, JSON: ["username": username, "password": password].toJSON()) + } +} +``` + +#### NetworkService +`NetworkService` brings in AlamoFire, Freddy, and SwiftTask in order to provide a simple networking layer that creates `Task`'s capable of performing network requests, decoding JSON, and mapping the JSON into model objects. Here is an example of a login call where `AuthToken` is a swift struct conforming to `JSONDecodable` (from Freddy): + +```swift +self.networkService.request(Route.login(username: username, password: password)).success { (loginResponse: ResponseValue) in + let networkResponse = loginResponse.response + let authToken = loginResponse.value // on success we directly get our model object(s) + // Do something with authToken and/or networkResponse... +}.failure { errorInfo in + let networkResponse = errorInfo.error?.response + let error = errorInfo.error?.error + // Again, you have access to the error and the network response. +} +``` + +When testing the rest of your app you will want to stub the network layer. The recommended approach is to use the `Nocilla` library and add the following conveniences (I tried to put these into a subspec [but failed](https://github.com/CocoaPods/CocoaPods/issues/5191)): + +```swift +// Improved DSL for Nocilla + +func stubRoute(route: Route) -> LSStubRequestDSL { + return stubRequest(route.method.rawValue, route.URL.absoluteString).withHeaders(route.URLRequest.allHTTPHeaderFields).withBody(route.URLRequest.HTTPBody) +} + +extension LSStubRequestDSL { + func andReturn(status: HTTPStatusCode) -> LSStubResponseDSL { + return andReturn(status.rawValue) + } +} + +extension LSStubResponseDSL { + func withJSON(json: JSON) -> LSStubResponseDSL { + let body = try? json.serialize() ?? NSData() + return withHeader("Content-Type", "application/json").withBody(body) + } +} + +func stubAnyRequest() -> LSStubRequestDSL { + return stubRequest(nil, ".*".regex()) +} +``` + +Now you can easily stub your login `Route` like this: + +```swift +stubRoute(Route.login(username: "user", password: "pass")).andReturn(.Code200OK).withJSON(["token": "[TOKEN]"]) +``` + +### Security + +`KeychainAccess` provides the app access to a device's Keychain store. Usage is fairly straightforward, as part of an account, you can place strings (or data) for a key into the Keychain and then recover those values later. This makes it a good way to securely store a specific user's password or tokens for reuse in the app. For more details on what else you can store, check out the KeychainAccessSpec.swift file. + +```swift +// Instantiate the keychain access using a unique account identifier to house your key/values +let keychain = KeychainAccess(account: "user@example.com") + +// Store a login token +var loginTokenID = "LoginToken" +let loginTokenValue = "SomeSuperSecretValueAboutACat" +keychain.putString(testKey, value: loginTokenID) + +// And pull it back for later use +let loginToken = keychain.getString(loginTokenID) + +``` + +NOTES: +- It is a simple keychain store library and doesn't include any fancy integration with iCloud or TouchID + +### UI +#### UIColor Extension +Includes a UIColor extension for hex code (e.g. `#FF0000`) support. You can now create your project's color palette in another class extension that brings all those pesky colors into one place and with names that are easy to understand: + +```swift +private static let _FF9000 = UIColor(hexString: "#FF9000") +public static func MyApp_BrightOrangeColor() -> UIColor { + return _FF9000 +} +``` + +In your app's implementation you you can then quickly make use of those colors: + +```swift +let color = UIColor.MyApp_BrightOrangeColor() +``` +#### Reusable Cell Protocols +In many iOS apps, it is common to dequeue table or collection view cells. To assist with this and avoid having to define identifiers for each type of cell, a number of protocols are included in Astro/UI. + +##### ReusableView +The [`ReusableView`](Astro/UI/ReusableView.swift) protocol requires that a `defaultReuseIdentifier` string be defined for any objects that wish to adhere to it. To make adoption of this protocol easier, a default implementation is provided for any `UIView` subclasses (namely, `UITableViewCell` and `UICollectionViewCell`). The default implementation will provide the name of the class as the reuse identifier, so as long as you define the reuse identifier for your prototype cells in IB the same as the name of the class, you should be good to go: + +```swift +class AstroTableViewCell: UITableViewCell, ReusableView { + // ... +} + +class AstroTableViewController: UITableViewController { + // ... + func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { + let astroCellIdentifier = AstroTableViewCell.defaultReuseIdentifier // "AstroTableViewCell" + let cell = tableView.dequeueReusableCellWithIdentifier(astroCellIdentifier, forIndexPath: indexPath) + return cell + } + // ... +} +``` + +One other trick you can do to make it so that all your cell subclasses are a `ReusableView` and have a `defaultReuseIdentifier`, you can apply an extension like below for your project: + +```swift +extension UICollectionViewCell: ReusableView {} +``` + +It should also be noted that if you wish to customize the identifier, you can always override the implementation of `defaultReuseIdentifier` in your view subclass. + +##### NibLoadableView +The [`NibLoadableView`](Astro/UI/NibLoadableView.swift) protocol, like `ReusableView`, requires that a string, `nibName`, be defined for objects that wish to adhere to it. Since the use of nibs is similar to how cells are referenced and dequeued for table/collection views, a default implementation is provided for this protocol too, which returns the class' name for the name of the nib (meaning that you should name your nib files the same as the view subclasses you implement them in). + +```swift +class AstroView: NibLoadableView { + // ... +} + +class AstroViewController: UIViewController { + override func viewDidLoad() { + super.viewDidLoad() + let astroNibName = AstroView.nibName // "AstroView" + } +} +``` + +Why bother with this `NibLoadableView` though, you ask? Watch how it combines with `ReusableView`, and some nifty extensions to reduce more boilerplate... + +##### ReusableView + NibLoadableView in Tandem +As alluded to, there are `UITableView` and `UICollectionView` extensions that make use of `ReusableView` and `NibLoadableView` for really easy cell registration and dequeueing. Below is the extension for `UICollectionView`: + +```swift +public extension UICollectionView { + public func register(cellType: T.Type) { + registerClass(cellType.self, forCellWithReuseIdentifier: cellType.defaultReuseIdentifier) + } + + public func register(cellType: T.Type) { + let bundle = NSBundle(forClass: cellType.self) + let nib = UINib(nibName: cellType.nibName, bundle: bundle) + registerNib(nib, forCellWithReuseIdentifier: cellType.defaultReuseIdentifier) + } + + public func dequeueReusableCell(forIndexPath indexPath: NSIndexPath) -> T { + guard let cell = dequeueReusableCellWithReuseIdentifier(T.defaultReuseIdentifier, forIndexPath: indexPath) as? T else { + fatalError("Could not dequeue collection view cell with identifier: \(T.defaultReuseIdentifier)") + } + return cell + } +} +``` + +The register method can take in a cell subclass that adheres to only `ReusableView`, or both `ReusableView` and `NibLoadableView`. After the cell is registered, the provided dequeue method can be used in the necessary delegate method which allows you to stick with just using types to reference our views, and get back the specific view type we just dequeued: + +```swift +class BookCell: UICollectionViewCell, ReusableView, NibLoadableView { + // ... +} + +class BookListViewController: UIViewController, UICollectionViewDataSource { + @IBOutlet private weak var collectionView: UICollectionView! + + override func viewDidLoad() { + super.viewDidLoad() + self.collectionView.register(BookCell.self) + } + + func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { + let cell: BookCell = collectionView.dequeueReusableCell(forIndexPath: indexPath) + return cell + } +} +``` + +### Utils +#### EnumCountable +`EnumCountable` provides an easy way to add a static `count` constant to Swift enums of type Int. + +It requires that the first case start at 0 and all cases must be continuous. + +Example: + +```swift +class SettingsViewController : UICollectionViewController { +enum Section: Int, EnumCountable { + case Customizations = 0 + case Faqs + case Support + case Logout + + static let count = Section.countCases() +} +... +override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { + return Section.count + } +} +``` + +#### Queue +`Queue` provides a prettier interface for the most common needs of dispatching onto different GCD Queues. If you require something more powerfull consider [Async](https://github.com/duemunk/Async). + +```swift +Queue.Background.execute { + // Do some work... + Queue.Main.executeAfter(delay: 1) { + // Back on main thread + } +} +``` + +## Module Management + +As the library matures, more classes will be introduced to the project and it would be nice to keep it from +becoming a mish-mash of things. One of the ways we intend to do this is to cluster the code in directories +by functionality using pod subspecs for these modules. That way if a project just needs one or two things they can grab that +subset easily. + +So if you want to add some classes in, think about the existing modules and decide if it belongs with one +or if it should have a new home. If you don't know then please ask. + +## Contact + +[![Robots & Pencils Logo](http://f.cl.ly/items/2W3n1r2R0j2p2b3n3j3c/rnplogo.png)](http://www.robotsandpencils.com) + +Made with ❤ by Robots & Pencils ([@robotsNpencils](https://twitter.com/robotsNpencils)) + +### Maintainers + +- [Chad Sykes](http://github.com/csykes) +- [Dominic Pepin](http://github.com/dompepin) +- [Michael Beauregard](http://github.com/mjbeauregard) + +## License + +Astro is available under the MIT license. See the LICENSE file for more info. diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..b8ffc2d --- /dev/null +++ b/Rakefile @@ -0,0 +1,87 @@ +def workspace + return 'Astro.xcworkspace' +end + +def configuration + return 'Debug' +end + +def targets + return [ + :ios, + # :tvos # Note: we're omiting this until Circle supports testing on tvOS simulators. + ] +end + +def schemes + return { + ios: 'Astro', + tvos: 'Astro' + } +end + +def sdks + return { + ios: 'iphonesimulator', + tvos: 'appletvsimulator9.2' + } +end + +def devices + return { + ios: "platform='iOS Simulator',OS='9.3',name='iPhone 6s'", + tvos: "name='Apple TV 1080p'" + } +end + +def xcodebuild_astro(tasks, platform, xcpretty_args: '') + sdk = sdks[platform] + scheme = schemes[platform] + destination = devices[platform] + + sh "set -o pipefail && xcodebuild CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= PROVISIONING_PROFILE= -workspace '#{workspace}' -scheme '#{scheme}' -sdk #{sdk} -destination #{destination} #{tasks} | xcpretty -c #{xcpretty_args}" +end + +desc 'Build the Astro framework.' +task :build do + xcodebuild_astro 'build', :ios +end + +desc 'Clean build directory.' +task :clean do + xcodebuild_astro 'clean', :ios +end + +desc 'Build, then run tests.' +task :test do + targets.map { |platform| xcodebuild_astro 'build test', platform, xcpretty_args: '--test' } + sh "killall Simulator" +end + +desc 'Release a version, specified as an argument.' +task :release, :version do |task, args| + version = args[:version] + abort "You must specify a version in semver format." if version.nil? || version.scan(/\d+\.\d+\.\d+/).length == 0 + + puts "Updating podspec." + filename = "Astro.podspec" + contents = File.read(filename) + contents.gsub!(/s\.version\s*=\s"\d+\.\d+\.\d+"/, "s.version = \"#{version}\"") + File.open(filename, 'w') { |file| file.puts contents } + + puts "Comitting, tagging, and pushing." + message = "Releasing version #{version}." + sh "git commit -am '#{message}'" + sh "git tag #{version} -m '#{message}'" + sh "git push --follow-tags" + + puts "Pushing to Astro.podspec" + sh "pod trunk push Astro.podspec --allow-warnings" + + puts "Pushing as a GitHub Release." + require 'octokit' + Octokit::Client.new(netrc: true). + create_release('RobotsAndPencils/Astro', + version, + name: version) +end diff --git a/circle.yml b/circle.yml new file mode 100644 index 0000000..4117679 --- /dev/null +++ b/circle.yml @@ -0,0 +1,18 @@ +general: +machine: + xcode: + version: 7.3 +test: + override: + - set -o pipefail && + xcodebuild + CODE_SIGNING_REQUIRED=NO + CODE_SIGN_IDENTITY= + PROVISIONING_PROFILE= + -sdk iphonesimulator + -destination 'platform=iOS Simulator,OS=9.3,name=iPhone 6' + -workspace Astro.xcworkspace + -scheme "Astro" + clean build test | + tee $CIRCLE_ARTIFACTS/xcode_raw.log | + xcpretty --color --report junit --output $CIRCLE_TEST_REPORTS/xcode/results.xml \ No newline at end of file