diff --git a/NoughtsAndCrosses.xcworkspace/contents.xcworkspacedata b/NoughtsAndCrosses.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..e0943c4 --- /dev/null +++ b/NoughtsAndCrosses.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/NoughtsAndCrosses/ClosureExperiment.swift b/NoughtsAndCrosses/ClosureExperiment.swift new file mode 100644 index 0000000..55daf87 --- /dev/null +++ b/NoughtsAndCrosses/ClosureExperiment.swift @@ -0,0 +1,30 @@ +// +// ClosureExperiment.swift +// NoughtsAndCrosses +// +// Created by Rachel on 6/6/16. +// Copyright © 2016 Julian Hulme. All rights reserved. +// + +import Foundation + +class ClosureExperiment { + + + + init () { + self.anotherFunction() + } + + func thisIsAFunction(withAnInputVariable:String, withAClosure: () -> ()){ + //print("thisIsAFunction is executing") + withAClosure() + } + + func anotherFunction(){ + //print("Another Function is executing") + } + + + +} \ No newline at end of file diff --git a/NoughtsAndCrosses/EmailValidatedTextField.swift b/NoughtsAndCrosses/EmailValidatedTextField.swift new file mode 100644 index 0000000..2ed2aa3 --- /dev/null +++ b/NoughtsAndCrosses/EmailValidatedTextField.swift @@ -0,0 +1,60 @@ +// +// EmailValidatedTextField.swift +// NoughtsAndCrosses +// +// Created by Rachel on 6/1/16. +// Copyright © 2016 Julian Hulme. All rights reserved. +// + +import UIKit + +class EmailValidatedTextField: UITextField, UITextFieldDelegate { + var imageView: UIImageView = UIImageView() + var message = "" + + + override func drawRect(rect: CGRect) { + self.delegate = self + imageView = UIImageView(frame: CGRectMake(self.frame.width-30, 5, 22, 22)) + self.addSubview(imageView) + } + +// Create a function called valid that takes no params, and returns a boolean. For now, always return true. + private func valid() -> Bool { + let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" + let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) + return emailTest.evaluateWithObject(message) + } +// Create a function called updateUI that takes no params and returns no value. Leave the body blank for now. + func updateUI() { + if ( self.valid() ){ + imageView.image = UIImage( named: "input_valid" ) + } + else { + imageView.image = UIImage( named: "input_invalid") + } + + } + + + func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { + if ( string == "" ){ + message.removeAtIndex(message.endIndex.predecessor()) + } + message = message + string + updateUI() + return true + } + + + + //Add a third function called validate that calls updateUI and returns the value of the valid function. + func validate() -> Bool { + self.updateUI() + return self.valid() + } + + + + +} diff --git a/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/project.pbxproj b/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/project.pbxproj index 36b4b0a..68fcb8b 100644 --- a/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/project.pbxproj +++ b/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/project.pbxproj @@ -12,6 +12,25 @@ 42D447D81CD765670070326E /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 42D447D61CD765670070326E /* LaunchScreen.storyboard */; }; 42D447E31CD765680070326E /* NoughtsAndCrossesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42D447E21CD765680070326E /* NoughtsAndCrossesTests.swift */; }; 42D447EE1CD765680070326E /* NoughtsAndCrossesUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42D447ED1CD765680070326E /* NoughtsAndCrossesUITests.swift */; }; + B649DFC4A1CACAAF36F004FC /* Pods_NoughtsAndCrosses.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C646BCA96E577A86A9AC2373 /* Pods_NoughtsAndCrosses.framework */; }; + CA07DB211CFF6633002895CF /* EasterEggViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA07DB1F1CFF6633002895CF /* EasterEggViewController.swift */; }; + CA07DB221CFF6633002895CF /* EasterEggViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = CA07DB201CFF6633002895CF /* EasterEggViewController.xib */; }; + CA07DB251CFF66F6002895CF /* EasterEggController.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA07DB241CFF66F6002895CF /* EasterEggController.swift */; }; + CA1A82CD1CFEDED700BCBF24 /* EmailValidatedTextField.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA1A82CC1CFEDED700BCBF24 /* EmailValidatedTextField.swift */; }; + CA35D7221CFE2C420030E246 /* LandingViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA35D7201CFE2C420030E246 /* LandingViewController.swift */; }; + CA35D7231CFE2C420030E246 /* LandingViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = CA35D7211CFE2C420030E246 /* LandingViewController.xib */; }; + CA35D7261CFE2CEF0030E246 /* LoginViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA35D7241CFE2CEF0030E246 /* LoginViewController.swift */; }; + CA35D7271CFE2CEF0030E246 /* LoginViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = CA35D7251CFE2CEF0030E246 /* LoginViewController.xib */; }; + CA35D72A1CFE32930030E246 /* RegistrationViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA35D7281CFE32930030E246 /* RegistrationViewController.swift */; }; + CA35D72B1CFE32930030E246 /* RegistrationViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = CA35D7291CFE32930030E246 /* RegistrationViewController.xib */; }; + CA3ED6D31D0565DC00765DA8 /* Podfile in Resources */ = {isa = PBXBuildFile; fileRef = CA3ED6D21D0565DC00765DA8 /* Podfile */; }; + CA3ED6D71D05700B00765DA8 /* ClosureExperiment.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA3ED6D61D05700B00765DA8 /* ClosureExperiment.swift */; }; + CA3ED6D91D057E9C00765DA8 /* WebService.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA3ED6D81D057E9C00765DA8 /* WebService.swift */; }; + CA3ED6DB1D05862800765DA8 /* UIViewControllerExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA3ED6DA1D05862800765DA8 /* UIViewControllerExtensions.swift */; }; + CA47A89B1D016EA0005F66F3 /* NetworkPlayViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA47A8991D016EA0005F66F3 /* NetworkPlayViewController.swift */; }; + CA47A89C1D016EA0005F66F3 /* NetworkPlayViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = CA47A89A1D016EA0005F66F3 /* NetworkPlayViewController.xib */; }; + CA5FE1C61D01BF04005DB249 /* OXGameController.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA5FE1C51D01BF04005DB249 /* OXGameController.swift */; }; + CAE1B4661CFE3A0700887A64 /* UserController.swift in Sources */ = {isa = PBXBuildFile; fileRef = CAE1B4651CFE3A0700887A64 /* UserController.swift */; }; FBDE70841CF87AD00025275C /* BoardViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FBDE70821CF87AD00025275C /* BoardViewController.swift */; }; FBDE70851CF87AD00025275C /* BoardViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = FBDE70831CF87AD00025275C /* BoardViewController.xib */; }; /* End PBXBuildFile section */ @@ -45,6 +64,27 @@ 42D447E91CD765680070326E /* NoughtsAndCrossesUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = NoughtsAndCrossesUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 42D447ED1CD765680070326E /* NoughtsAndCrossesUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NoughtsAndCrossesUITests.swift; sourceTree = ""; }; 42D447EF1CD765680070326E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 782AE7B5918F932283C1C1E9 /* Pods-NoughtsAndCrosses.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-NoughtsAndCrosses.debug.xcconfig"; path = "Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses.debug.xcconfig"; sourceTree = ""; }; + 7BAA4FBB12CBD602A3A39B7F /* Pods-NoughtsAndCrosses.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-NoughtsAndCrosses.release.xcconfig"; path = "Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses.release.xcconfig"; sourceTree = ""; }; + C646BCA96E577A86A9AC2373 /* Pods_NoughtsAndCrosses.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_NoughtsAndCrosses.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + CA07DB1F1CFF6633002895CF /* EasterEggViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EasterEggViewController.swift; sourceTree = ""; }; + CA07DB201CFF6633002895CF /* EasterEggViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = EasterEggViewController.xib; sourceTree = ""; }; + CA07DB241CFF66F6002895CF /* EasterEggController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EasterEggController.swift; sourceTree = ""; }; + CA1A82CC1CFEDED700BCBF24 /* EmailValidatedTextField.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EmailValidatedTextField.swift; sourceTree = ""; }; + CA35D7201CFE2C420030E246 /* LandingViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LandingViewController.swift; sourceTree = ""; }; + CA35D7211CFE2C420030E246 /* LandingViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = LandingViewController.xib; sourceTree = ""; }; + CA35D7241CFE2CEF0030E246 /* LoginViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LoginViewController.swift; sourceTree = ""; }; + CA35D7251CFE2CEF0030E246 /* LoginViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = LoginViewController.xib; sourceTree = ""; }; + CA35D7281CFE32930030E246 /* RegistrationViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RegistrationViewController.swift; sourceTree = ""; }; + CA35D7291CFE32930030E246 /* RegistrationViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = RegistrationViewController.xib; sourceTree = ""; }; + CA3ED6D21D0565DC00765DA8 /* Podfile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + CA3ED6D61D05700B00765DA8 /* ClosureExperiment.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ClosureExperiment.swift; sourceTree = ""; }; + CA3ED6D81D057E9C00765DA8 /* WebService.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WebService.swift; sourceTree = ""; }; + CA3ED6DA1D05862800765DA8 /* UIViewControllerExtensions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UIViewControllerExtensions.swift; sourceTree = ""; }; + CA47A8991D016EA0005F66F3 /* NetworkPlayViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NetworkPlayViewController.swift; sourceTree = ""; }; + CA47A89A1D016EA0005F66F3 /* NetworkPlayViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = NetworkPlayViewController.xib; sourceTree = ""; }; + CA5FE1C51D01BF04005DB249 /* OXGameController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OXGameController.swift; sourceTree = ""; }; + CAE1B4651CFE3A0700887A64 /* UserController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserController.swift; sourceTree = ""; }; FBDE70821CF87AD00025275C /* BoardViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BoardViewController.swift; sourceTree = ""; }; FBDE70831CF87AD00025275C /* BoardViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = BoardViewController.xib; sourceTree = ""; }; /* End PBXFileReference section */ @@ -54,6 +94,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + B649DFC4A1CACAAF36F004FC /* Pods_NoughtsAndCrosses.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -84,10 +125,16 @@ 42D447C11CD765670070326E = { isa = PBXGroup; children = ( + CA3ED6DA1D05862800765DA8 /* UIViewControllerExtensions.swift */, + CA3ED6D81D057E9C00765DA8 /* WebService.swift */, + CA3ED6D61D05700B00765DA8 /* ClosureExperiment.swift */, + CA1A82CC1CFEDED700BCBF24 /* EmailValidatedTextField.swift */, 42D447CC1CD765670070326E /* NoughtsAndCrosses */, 42D447E11CD765680070326E /* NoughtsAndCrossesTests */, 42D447EC1CD765680070326E /* NoughtsAndCrossesUITests */, 42D447CB1CD765670070326E /* Products */, + 8BF78FC294A25E0909463277 /* Pods */, + D867E4FDC9E9F9D0267B25E4 /* Frameworks */, ); sourceTree = ""; }; @@ -104,9 +151,12 @@ 42D447CC1CD765670070326E /* NoughtsAndCrosses */ = { isa = PBXGroup; children = ( + CA3ED6D21D0565DC00765DA8 /* Podfile */, + CA5FE1C41D01BD06005DB249 /* Screens */, + CA5FE1C31D01BC3C005DB249 /* ModelControllers */, + CA07DB231CFF667B002895CF /* EasterEgg */, + CA35D71F1CFE2A430030E246 /* Authentication */, 42D447CD1CD765670070326E /* AppDelegate.swift */, - FBDE70821CF87AD00025275C /* BoardViewController.swift */, - FBDE70831CF87AD00025275C /* BoardViewController.xib */, 42D447D41CD765670070326E /* Assets.xcassets */, 42D447D61CD765670070326E /* LaunchScreen.storyboard */, 42D447D91CD765670070326E /* Info.plist */, @@ -133,6 +183,74 @@ path = NoughtsAndCrossesUITests; sourceTree = ""; }; + 8BF78FC294A25E0909463277 /* Pods */ = { + isa = PBXGroup; + children = ( + 782AE7B5918F932283C1C1E9 /* Pods-NoughtsAndCrosses.debug.xcconfig */, + 7BAA4FBB12CBD602A3A39B7F /* Pods-NoughtsAndCrosses.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; + CA07DB231CFF667B002895CF /* EasterEgg */ = { + isa = PBXGroup; + children = ( + CA07DB1F1CFF6633002895CF /* EasterEggViewController.swift */, + CA07DB201CFF6633002895CF /* EasterEggViewController.xib */, + CA07DB241CFF66F6002895CF /* EasterEggController.swift */, + ); + name = EasterEgg; + sourceTree = ""; + }; + CA35D71D1CFE29DB0030E246 /* Game */ = { + isa = PBXGroup; + children = ( + FBDE70821CF87AD00025275C /* BoardViewController.swift */, + FBDE70831CF87AD00025275C /* BoardViewController.xib */, + ); + name = Game; + sourceTree = ""; + }; + CA35D71F1CFE2A430030E246 /* Authentication */ = { + isa = PBXGroup; + children = ( + CA35D7201CFE2C420030E246 /* LandingViewController.swift */, + CA35D7211CFE2C420030E246 /* LandingViewController.xib */, + CA35D7241CFE2CEF0030E246 /* LoginViewController.swift */, + CA35D7251CFE2CEF0030E246 /* LoginViewController.xib */, + CA35D7281CFE32930030E246 /* RegistrationViewController.swift */, + CA35D7291CFE32930030E246 /* RegistrationViewController.xib */, + ); + name = Authentication; + sourceTree = ""; + }; + CA5FE1C31D01BC3C005DB249 /* ModelControllers */ = { + isa = PBXGroup; + children = ( + CAE1B4651CFE3A0700887A64 /* UserController.swift */, + CA5FE1C51D01BF04005DB249 /* OXGameController.swift */, + ); + name = ModelControllers; + sourceTree = ""; + }; + CA5FE1C41D01BD06005DB249 /* Screens */ = { + isa = PBXGroup; + children = ( + CA47A8991D016EA0005F66F3 /* NetworkPlayViewController.swift */, + CA47A89A1D016EA0005F66F3 /* NetworkPlayViewController.xib */, + CA35D71D1CFE29DB0030E246 /* Game */, + ); + name = Screens; + sourceTree = ""; + }; + D867E4FDC9E9F9D0267B25E4 /* Frameworks */ = { + isa = PBXGroup; + children = ( + C646BCA96E577A86A9AC2373 /* Pods_NoughtsAndCrosses.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -140,9 +258,12 @@ isa = PBXNativeTarget; buildConfigurationList = 42D447F21CD765680070326E /* Build configuration list for PBXNativeTarget "NoughtsAndCrosses" */; buildPhases = ( + 1A7973273201DDE10A8BB034 /* [CP] Check Pods Manifest.lock */, 42D447C61CD765670070326E /* Sources */, 42D447C71CD765670070326E /* Frameworks */, 42D447C81CD765670070326E /* Resources */, + EE312ADEF732D7931AD50BF9 /* [CP] Embed Pods Frameworks */, + B36B5534F758F32A5A148DC1 /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -237,8 +358,14 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + CA35D7271CFE2CEF0030E246 /* LoginViewController.xib in Resources */, 42D447D81CD765670070326E /* LaunchScreen.storyboard in Resources */, 42D447D51CD765670070326E /* Assets.xcassets in Resources */, + CA07DB221CFF6633002895CF /* EasterEggViewController.xib in Resources */, + CA35D72B1CFE32930030E246 /* RegistrationViewController.xib in Resources */, + CA47A89C1D016EA0005F66F3 /* NetworkPlayViewController.xib in Resources */, + CA3ED6D31D0565DC00765DA8 /* Podfile in Resources */, + CA35D7231CFE2C420030E246 /* LandingViewController.xib in Resources */, FBDE70851CF87AD00025275C /* BoardViewController.xib in Resources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -259,13 +386,73 @@ }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + 1A7973273201DDE10A8BB034 /* [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; + }; + B36B5534F758F32A5A148DC1 /* [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-NoughtsAndCrosses/Pods-NoughtsAndCrosses-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + EE312ADEF732D7931AD50BF9 /* [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-NoughtsAndCrosses/Pods-NoughtsAndCrosses-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ 42D447C61CD765670070326E /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + CA35D72A1CFE32930030E246 /* RegistrationViewController.swift in Sources */, + CA07DB251CFF66F6002895CF /* EasterEggController.swift in Sources */, + CA3ED6D91D057E9C00765DA8 /* WebService.swift in Sources */, + CA07DB211CFF6633002895CF /* EasterEggViewController.swift in Sources */, 42D447CE1CD765670070326E /* AppDelegate.swift in Sources */, + CA35D7221CFE2C420030E246 /* LandingViewController.swift in Sources */, + CA3ED6DB1D05862800765DA8 /* UIViewControllerExtensions.swift in Sources */, + CAE1B4661CFE3A0700887A64 /* UserController.swift in Sources */, + CA47A89B1D016EA0005F66F3 /* NetworkPlayViewController.swift in Sources */, + CA35D7261CFE2CEF0030E246 /* LoginViewController.swift in Sources */, + CA3ED6D71D05700B00765DA8 /* ClosureExperiment.swift in Sources */, FBDE70841CF87AD00025275C /* BoardViewController.swift in Sources */, + CA5FE1C61D01BF04005DB249 /* OXGameController.swift in Sources */, + CA1A82CD1CFEDED700BCBF24 /* EmailValidatedTextField.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -399,22 +586,26 @@ }; 42D447F31CD765680070326E /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 782AE7B5918F932283C1C1E9 /* Pods-NoughtsAndCrosses.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = NoughtsAndCrosses/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - PRODUCT_BUNDLE_IDENTIFIER = AS.NoughtsAndCrosses; + PRODUCT_BUNDLE_IDENTIFIER = katz.NoughtsAndCrosses; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Debug; }; 42D447F41CD765680070326E /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 7BAA4FBB12CBD602A3A39B7F /* Pods-NoughtsAndCrosses.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = NoughtsAndCrosses/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; - PRODUCT_BUNDLE_IDENTIFIER = AS.NoughtsAndCrosses; + PRODUCT_BUNDLE_IDENTIFIER = katz.NoughtsAndCrosses; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Release; diff --git a/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/project.xcworkspace/xcuserdata/Jordan.xcuserdatad/UserInterfaceState.xcuserstate b/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/project.xcworkspace/xcuserdata/Jordan.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000..d7b0112 Binary files /dev/null and b/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/project.xcworkspace/xcuserdata/Jordan.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/project.xcworkspace/xcuserdata/Katz.xcuserdatad/UserInterfaceState.xcuserstate b/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/project.xcworkspace/xcuserdata/Katz.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000..2633d45 Binary files /dev/null and b/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/project.xcworkspace/xcuserdata/Katz.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/xcuserdata/Jordan.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/xcuserdata/Jordan.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist new file mode 100644 index 0000000..fe2b454 --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/xcuserdata/Jordan.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist @@ -0,0 +1,5 @@ + + + diff --git a/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/xcuserdata/Jordan.xcuserdatad/xcschemes/NoughtsAndCrosses.xcscheme b/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/xcuserdata/Jordan.xcuserdatad/xcschemes/NoughtsAndCrosses.xcscheme new file mode 100644 index 0000000..f64f008 --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/xcuserdata/Jordan.xcuserdatad/xcschemes/NoughtsAndCrosses.xcscheme @@ -0,0 +1,111 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/xcuserdata/Jordan.xcuserdatad/xcschemes/xcschememanagement.plist b/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/xcuserdata/Jordan.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..a468be2 --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/xcuserdata/Jordan.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,32 @@ + + + + + SchemeUserState + + NoughtsAndCrosses.xcscheme + + orderHint + 0 + + + SuppressBuildableAutocreation + + 42D447C91CD765670070326E + + primary + + + 42D447DD1CD765680070326E + + primary + + + 42D447E81CD765680070326E + + primary + + + + + diff --git a/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/xcuserdata/Katz.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/xcuserdata/Katz.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist new file mode 100644 index 0000000..fe2b454 --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/xcuserdata/Katz.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist @@ -0,0 +1,5 @@ + + + diff --git a/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/xcuserdata/Katz.xcuserdatad/xcschemes/NoughtsAndCrosses.xcscheme b/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/xcuserdata/Katz.xcuserdatad/xcschemes/NoughtsAndCrosses.xcscheme new file mode 100644 index 0000000..13be6ca --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/xcuserdata/Katz.xcuserdatad/xcschemes/NoughtsAndCrosses.xcscheme @@ -0,0 +1,111 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/xcuserdata/Katz.xcuserdatad/xcschemes/xcschememanagement.plist b/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/xcuserdata/Katz.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..a468be2 --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses.xcodeproj/xcuserdata/Katz.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,32 @@ + + + + + SchemeUserState + + NoughtsAndCrosses.xcscheme + + orderHint + 0 + + + SuppressBuildableAutocreation + + 42D447C91CD765670070326E + + primary + + + 42D447DD1CD765680070326E + + primary + + + 42D447E81CD765680070326E + + primary + + + + + diff --git a/NoughtsAndCrosses/NoughtsAndCrosses.xcworkspace/contents.xcworkspacedata b/NoughtsAndCrosses/NoughtsAndCrosses.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..dde8317 --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/NoughtsAndCrosses/NoughtsAndCrosses.xcworkspace/xcuserdata/Katz.xcuserdatad/UserInterfaceState.xcuserstate b/NoughtsAndCrosses/NoughtsAndCrosses.xcworkspace/xcuserdata/Katz.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000..0dc9d59 Binary files /dev/null and b/NoughtsAndCrosses/NoughtsAndCrosses.xcworkspace/xcuserdata/Katz.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/NoughtsAndCrosses/NoughtsAndCrosses.xcworkspace/xcuserdata/Katz.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/NoughtsAndCrosses/NoughtsAndCrosses.xcworkspace/xcuserdata/Katz.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist new file mode 100644 index 0000000..ed9a9b4 --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses.xcworkspace/xcuserdata/Katz.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist @@ -0,0 +1,5 @@ + + + diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/AppDelegate.swift b/NoughtsAndCrosses/NoughtsAndCrosses/AppDelegate.swift index 232c5f7..dc8fa27 100644 --- a/NoughtsAndCrosses/NoughtsAndCrosses/AppDelegate.swift +++ b/NoughtsAndCrosses/NoughtsAndCrosses/AppDelegate.swift @@ -12,20 +12,43 @@ import UIKit class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? - var navigationController: UINavigationController? + var authorisationNavigationController: UINavigationController? + var GameNavigationController: UINavigationController? + var EasterEggNavigationController: UINavigationController? + func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. - let boardViewController = BoardViewController(nibName:"BoardViewController",bundle:nil) - self.navigationController = UINavigationController(rootViewController: boardViewController) - self.navigationController?.navigationBarHidden = true - self.window = UIWindow(frame: UIScreen.mainScreen().bounds) - self.window?.rootViewController = self.navigationController self.window?.makeKeyAndVisible() + EasterEggController.sharedInstance.initiate(self.window!) + + let userIsLoggedIn = UserController.sharedInstance.getLoggedInUser() + + let boardViewController = BoardViewController(nibName:"BoardViewController",bundle:nil) + self.GameNavigationController = UINavigationController(rootViewController: boardViewController) + self.GameNavigationController?.navigationBarHidden = true + + let landingViewController = LandingViewController(nibName: "LandingViewController", bundle:nil) + authorisationNavigationController = UINavigationController(rootViewController: landingViewController) + + let easterEggViewController = EasterEggViewController(nibName: "EasterEggViewController", bundle:nil) + EasterEggNavigationController = UINavigationController(rootViewController: easterEggViewController) + + + if userIsLoggedIn != nil { + + self.window?.rootViewController = self.GameNavigationController + } else { + //LandingViewController + self.window?.rootViewController = self.authorisationNavigationController + //self.window?.rootViewController = self.GameNavigationController + } + + return true } @@ -51,7 +74,26 @@ class AppDelegate: UIResponder, UIApplicationDelegate { func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } + func navigateToBoardNavigationController(){ + + self.window?.rootViewController = self.GameNavigationController + + } + + func navigateBackToLandingNavigationController(){ + // This function should take no params and return nothing. Inside this function, set the windows rootViewController to be the loggedInNavController. You have already seen a line of code that allows for this. Read up :) + self.window?.rootViewController = self.authorisationNavigationController + + } + + func navigateToEasterEggScreen(){ + + self.window?.rootViewController = self.EasterEggNavigationController + + + } + } diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/Contents.json b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/Contents.json new file mode 100644 index 0000000..da4a164 --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/Easter_Egg_Background.imageset/Contents.json b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/Easter_Egg_Background.imageset/Contents.json new file mode 100644 index 0000000..c73d574 --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/Easter_Egg_Background.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "IMG_2698 copy 1x.jpg", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "IMG_2698 copy 2x.jpg", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "IMG_2698.jpg", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/Easter_Egg_Background.imageset/IMG_2698 copy 1x.jpg b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/Easter_Egg_Background.imageset/IMG_2698 copy 1x.jpg new file mode 100644 index 0000000..d2bfd4a Binary files /dev/null and b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/Easter_Egg_Background.imageset/IMG_2698 copy 1x.jpg differ diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/Easter_Egg_Background.imageset/IMG_2698 copy 2x.jpg b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/Easter_Egg_Background.imageset/IMG_2698 copy 2x.jpg new file mode 100644 index 0000000..4d980b5 Binary files /dev/null and b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/Easter_Egg_Background.imageset/IMG_2698 copy 2x.jpg differ diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/Easter_Egg_Background.imageset/IMG_2698.jpg b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/Easter_Egg_Background.imageset/IMG_2698.jpg new file mode 100644 index 0000000..9ba23cf Binary files /dev/null and b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/Easter_Egg_Background.imageset/IMG_2698.jpg differ diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/iX_Logo.imageset/1x.png b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/iX_Logo.imageset/1x.png new file mode 100644 index 0000000..dbfeca7 Binary files /dev/null and b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/iX_Logo.imageset/1x.png differ diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/iX_Logo.imageset/2x.png b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/iX_Logo.imageset/2x.png new file mode 100644 index 0000000..1b99f2e Binary files /dev/null and b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/iX_Logo.imageset/2x.png differ diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/iX_Logo.imageset/Contents.json b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/iX_Logo.imageset/Contents.json new file mode 100644 index 0000000..7b8106c --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/iX_Logo.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "1x.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "Screen Shot 2016-06-07 at 11.28.09 PM.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/iX_Logo.imageset/Screen Shot 2016-06-07 at 11.28.09 PM.png b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/iX_Logo.imageset/Screen Shot 2016-06-07 at 11.28.09 PM.png new file mode 100644 index 0000000..496d572 Binary files /dev/null and b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/iX_Logo.imageset/Screen Shot 2016-06-07 at 11.28.09 PM.png differ diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_invalid.imageset/Contents.json b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_invalid.imageset/Contents.json new file mode 100644 index 0000000..ad5242d --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_invalid.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "cross-S.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "cross-M.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "cross-L.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_invalid.imageset/cross-L.png b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_invalid.imageset/cross-L.png new file mode 100644 index 0000000..c8821f1 Binary files /dev/null and b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_invalid.imageset/cross-L.png differ diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_invalid.imageset/cross-M.png b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_invalid.imageset/cross-M.png new file mode 100644 index 0000000..2d0af35 Binary files /dev/null and b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_invalid.imageset/cross-M.png differ diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_invalid.imageset/cross-S.png b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_invalid.imageset/cross-S.png new file mode 100644 index 0000000..17e76ab Binary files /dev/null and b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_invalid.imageset/cross-S.png differ diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_valid.imageset/Contents.json b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_valid.imageset/Contents.json new file mode 100644 index 0000000..6579c85 --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_valid.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "tick-S.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "tick-M.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "tick-L.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_valid.imageset/tick-L.png b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_valid.imageset/tick-L.png new file mode 100644 index 0000000..1c2ff38 Binary files /dev/null and b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_valid.imageset/tick-L.png differ diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_valid.imageset/tick-M.png b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_valid.imageset/tick-M.png new file mode 100644 index 0000000..6bdd620 Binary files /dev/null and b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_valid.imageset/tick-M.png differ diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_valid.imageset/tick-S.png b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_valid.imageset/tick-S.png new file mode 100644 index 0000000..70f0eba Binary files /dev/null and b/NoughtsAndCrosses/NoughtsAndCrosses/Assets.xcassets/input_valid.imageset/tick-S.png differ diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Base.lproj/LaunchScreen.storyboard b/NoughtsAndCrosses/NoughtsAndCrosses/Base.lproj/LaunchScreen.storyboard index 14d9a6a..f40fb03 100644 --- a/NoughtsAndCrosses/NoughtsAndCrosses/Base.lproj/LaunchScreen.storyboard +++ b/NoughtsAndCrosses/NoughtsAndCrosses/Base.lproj/LaunchScreen.storyboard @@ -1,11 +1,7 @@ - + - - - - @@ -19,125 +15,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/BoardViewController.swift b/NoughtsAndCrosses/NoughtsAndCrosses/BoardViewController.swift index 038913c..d6df9bd 100644 --- a/NoughtsAndCrosses/NoughtsAndCrosses/BoardViewController.swift +++ b/NoughtsAndCrosses/NoughtsAndCrosses/BoardViewController.swift @@ -8,14 +8,271 @@ import UIKit -class BoardViewController: UIViewController { +class BoardViewController: UIViewController, UIGestureRecognizerDelegate { + + @IBOutlet weak var newGameButton: UIButton! + @IBOutlet weak var logoutButton: UIButton! + @IBOutlet weak var networkPlay: UIButton! + @IBOutlet weak var BoardView: UIView! + @IBOutlet var allButtons: [UIButton]! + @IBOutlet weak var refreshButton: UIButton! + //var game = OXGameController.sharedInstance.getCurrentGame()! + var networkMode = false + + var currentGame = OXGame() + + override func viewDidLoad() { super.viewDidLoad() + + + view.userInteractionEnabled = true + + let rotation: UIRotationGestureRecognizer = UIRotationGestureRecognizer(target: self, action:#selector(BoardViewController.handleRotation(_:))) + + self.BoardView.addGestureRecognizer(rotation) + + let pinch = UIPinchGestureRecognizer(target: self, action:#selector(BoardViewController.handleRotation(_:))) + + updateUI() + } + + func gameUpdateReceived(game:OXGame?, message: String?){ + if let gameReceived = game { + self.currentGame = gameReceived + } + self.updateUI() + + OXGameController.sharedInstance.getGame(self.currentGame.gameID!, presentingViewController: nil, viewControllerCompletionFunction: {(game, message) in self.gameUpdateReceived(game,message:message)}) + } + + func updateUI(){ + + + if ( networkMode ) { + networkPlay.hidden = true + refreshButton.hidden = false + logoutButton.setTitle("Cancel Game", forState: UIControlState.Normal) + + if ( !currentGame.localUsersTurn() || (currentGame.guestUser!.email == "")){ + + for view in BoardView.subviews { + if let button = view as? UIButton { + + button.enabled = false + + + } + } + + } + + + if currentGame.guestUser!.email != "" { + + for view in BoardView.subviews { + if let button = view as? UIButton { + + button.enabled = true + + + } + } + + + newGameButton.setTitle("It's \(currentGame.whosTurn().rawValue)'s turn", forState: UIControlState.Normal) + + + + if ( currentGame.winDetection() ) { + if ( currentGame.state() == OXGameState.complete_someone_won ){ + newGameButton.setTitle(" \(currentGame.whoJustPlayed()) Won the Game!", forState: UIControlState.Normal) + + let alert = UIAlertController(title: "\(currentGame.whoJustPlayed()) Won the Game!", message: "Click OK to return to the list of Network Games", preferredStyle: UIAlertControllerStyle.Alert) + let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: {(action) in + self.navigationController?.popViewControllerAnimated(true) + + }) + alert.addAction(action) + self.presentViewController(alert, animated: true, completion: nil) + + } + else if (currentGame.state() == OXGameState.complete_no_one_won) { + newGameButton.setTitle("There was a Tie!", forState: UIControlState.Normal) + let alert = UIAlertController(title: "There was a Tie!", message: "Click OK to return to the list of Network Games", preferredStyle: UIAlertControllerStyle.Alert) + let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: {(action) in + self.navigationController?.popViewControllerAnimated(true) + + }) + alert.addAction(action) + self.presentViewController(alert, animated: true, completion: nil) + + } + + } + + + } + else { + newGameButton.setTitle("Awaiting Opponent To Join...", forState: UIControlState.Normal) + } + + } + else { + refreshButton.hidden = true + } + + for view in BoardView.subviews { + if let button = view as? UIButton { + + let toPrint = self.currentGame.typeAtIndex(button.tag).rawValue + button.setTitle(toPrint, forState: UIControlState.Normal) + + + } + } + + } + @IBAction func refreshButtonTapped(sender: UIButton) { + OXGameController.sharedInstance.getGame(self.currentGame.gameID!, presentingViewController: self, viewControllerCompletionFunction: {(game, message) in self.gameUpdateReceived(game,message:message)}) + } + + override func viewWillAppear(animated: Bool) { + self.navigationController?.navigationBarHidden = true + } + func handlePinch( sender: UIPinchGestureRecognizer? = nil ){ + print("pinch detected") + } + + func handleRotation(sender: UIRotationGestureRecognizer? = nil ){ + self.BoardView.transform = CGAffineTransformMakeRotation(sender!.rotation) + print("rotation detected") + + + if (sender!.state == UIGestureRecognizerState.Ended){ + print("rotation \(sender!.rotation)") + //self.BoardView.transform = CGAffineTransformMakeRotation(CGFloat(0)) + + + if( sender!.rotation < CGFloat(M_1_PI)/2) { + UIView.animateWithDuration(NSTimeInterval(3), animations: {} ) + self.BoardView.transform = CGAffineTransformMakeRotation(0) + } + else if ( sender!.rotation < CGFloat(M_1_PI)) { + UIView.animateWithDuration(NSTimeInterval(3), animations: {} ) + self.BoardView.transform = CGAffineTransformMakeRotation(CGFloat(M_1_PI)/2) + } + } + + + } + + override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } + @IBAction func boardTapped(sender: UIButton) { + + + //if i'm in network mode: + if ( networkMode ) { + + currentGame.playMove(sender.tag) + OXGameController.sharedInstance.playMove( self.currentGame.serialiseBoard() , gameId: self.currentGame.gameID!, presentingViewController: self, viewControllerCompletionFunction: {(game, message) in self.playGameReceived(game,message:message)}) + +// else if ( currentGame.backendState == OXGameState.inProgress ) { +// +// //OXGameController.sharedInstance.playMove( self.currentGame.serialiseBoard() , gameId: self.currentGame.gameID!, presentingViewController: self, viewControllerCompletionFunction: {(game, message) in self.playGameReceived(game,message:message)}) +// +// +// let celltype = currentGame.whoJustPlayed() +// let delay = Double(NSEC_PER_SEC)/2 +// let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) +// dispatch_after(time, dispatch_get_main_queue()) { +// } +// +// } + + } + else { + + let tag = sender.tag + + let cell = String(currentGame.playMove(tag)) + + print(String(cell)) + sender.setTitle( String(cell), forState: UIControlState.Normal) + + let gameState = currentGame.state() + + if ( gameState == OXGameState.complete_someone_won){ + + print("\(String(currentGame.whoJustPlayed())) is the Winner!") + restartGame() + + } + else if ( gameState == OXGameState.complete_no_one_won ) { + print("There is a Tie!") + restartGame() + + } + + } + } + + + func playGameReceived(game: OXGame!, message: String!){ + if ( message == nil ) { + currentGame = game + updateUI() + } else { + print("invalid move") + } + + + } + + func restartGame() { + //OXGameController.sharedInstance.getCurrentGame()!.reset() + //OXGameController.sharedInstance.getCurrentGame()!.currTurn = CellType.X + currentGame = OXGame() + for cell in allButtons { + cell.setTitle("", forState: UIControlState.Normal) + + } + } + + @IBAction func resetGame(sender: UIButton) { + restartGame() + } + + @IBAction func logoutButtonPressed(sender: UIButton) { + + if ( networkMode ){ + //OXGameController.sharedInstance.finishCurrentGame() + self.navigationController?.popViewControllerAnimated( true) + } + else { + let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate + + appDelegate.navigateBackToLandingNavigationController() + NSUserDefaults.standardUserDefaults().setValue( nil , forKey: "userIdLoggedIn") + } + + } + + func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { + return true + } + + @IBAction func networkPlayTapped(sender: UIButton) { + let npc = NetworkPlayViewController(nibName: "NetworkPlayViewController", bundle: nil) + self.navigationController?.pushViewController(npc, animated: true) + } + + } diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/BoardViewController.xib b/NoughtsAndCrosses/NoughtsAndCrosses/BoardViewController.xib index 769e0ef..3b24a78 100644 --- a/NoughtsAndCrosses/NoughtsAndCrosses/BoardViewController.xib +++ b/NoughtsAndCrosses/NoughtsAndCrosses/BoardViewController.xib @@ -1,7 +1,6 @@ - + - @@ -9,7 +8,21 @@ + + + + + + + + + + + + + + @@ -27,7 +40,7 @@ - + - - - @@ -135,6 +145,36 @@ + + + @@ -375,9 +415,41 @@ + + + + + + + - + diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/EasterEggController.swift b/NoughtsAndCrosses/NoughtsAndCrosses/EasterEggController.swift new file mode 100644 index 0000000..41118ca --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/EasterEggController.swift @@ -0,0 +1,146 @@ +// +// EasterEggController.swift +// NoughtsAndCrosses +// +// Created by Rachel on 6/1/16. +// Copyright © 2016 Julian Hulme. All rights reserved. +// + +import Foundation +import UIKit + +class EasterEggController: NSObject, UIGestureRecognizerDelegate { + + + enum gesture{ + case ClockwiseRotation + case CounterClockwiseRotation + case RightSwipe + case LongPress + case DownSwipe + case none + } + + var lastGesture = gesture.none + + let gesturesCombo = ["RightSwipe", "DownSwipe", "LongPress"] + var index = 0 + + //MARK: Class Singleton + class var sharedInstance: EasterEggController { + struct Static { + static var instance:EasterEggController? + static var token: dispatch_once_t = 0 + } + + dispatch_once(&Static.token) { + Static.instance = EasterEggController() + } + return Static.instance! + } + + + func initiate(view:UIView) { + + + //rotations + let rotation: UIRotationGestureRecognizer = UIRotationGestureRecognizer(target: self, action:#selector(EasterEggController.handleRotation(_:))) + view.addGestureRecognizer(rotation) + + rotation.delegate = self + + //rightSwipe + let rightSwipe: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action:#selector(EasterEggController.handleRightSwipe(_:))) + rightSwipe.direction = UISwipeGestureRecognizerDirection.Right + view.addGestureRecognizer(rightSwipe) + + //longPress + let longPress: UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action:#selector(EasterEggController.handlelongPress(_:))) + view.addGestureRecognizer(longPress) + + //downSwipe + let downSwipe: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action:#selector(EasterEggController.handledownSwipe(_:))) + downSwipe.direction = UISwipeGestureRecognizerDirection.Down + view.addGestureRecognizer(downSwipe) + + + } + + func checkKey(){ + if (index == gesturesCombo.endIndex) { + let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate + appDelegate.navigateToEasterEggScreen() + index = 0 + + } + else { + return + } + } + + //rotation handler + func handleRotation( sender: UIRotationGestureRecognizer? = nil ){ + + if (sender!.state == UIGestureRecognizerState.Ended) + { + + if ( sender!.rotation < 0 ){ + print("CCR Detected") + } + else { + print("CR Detected") + } + } + } + + //right swipe handler + func handleRightSwipe( sender: UISwipeGestureRecognizer? = nil ){ + + print("Right Swipe Detected") + if ( gesturesCombo[index] == "RightSwipe"){ + index += 1 + checkKey() + } + else { + index = 0 + } + + } + + //long press handler + func handlelongPress( sender: UILongPressGestureRecognizer? = nil ){ + + print("Long Press Detected") + if ( gesturesCombo[index] == "LongPress" ){ + index += 1 + checkKey() + } + else { + index = 0 + } + + + } + + //down swipe handler + func handledownSwipe( sender: UISwipeGestureRecognizer? = nil ){ + + print("Down Swipe Detected") + if ( gesturesCombo[index] == "DownSwipe"){ + index += 1 + checkKey() + } + else { + index = 0 + } + + + } + + //Allow to recognize multiple gestures of the same type + func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { + return true + } + + +} \ No newline at end of file diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/EasterEggViewController.swift b/NoughtsAndCrosses/NoughtsAndCrosses/EasterEggViewController.swift new file mode 100644 index 0000000..080434a --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/EasterEggViewController.swift @@ -0,0 +1,32 @@ +// +// EasterEggViewController.swift +// NoughtsAndCrosses +// +// Created by Rachel on 6/1/16. +// Copyright © 2016 Julian Hulme. All rights reserved. +// + +import UIKit + +class EasterEggViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + self.navigationController?.navigationBarHidden = true + + // Do any additional setup after loading the view. + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + + @IBAction func ReturnButtonWasTapped(sender: UIButton) { + let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate + + appDelegate.navigateToBoardNavigationController() + } + +} diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/EasterEggViewController.xib b/NoughtsAndCrosses/NoughtsAndCrosses/EasterEggViewController.xib new file mode 100644 index 0000000..617328a --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/EasterEggViewController.xib @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/EmailValidatedTextField.swift b/NoughtsAndCrosses/NoughtsAndCrosses/EmailValidatedTextField.swift new file mode 100644 index 0000000..d187773 --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/EmailValidatedTextField.swift @@ -0,0 +1,35 @@ +// +// EmailValidatedTextField.swift +// NoughtsAndCrosses +// +// Created by Rachel on 6/1/16. +// Copyright © 2016 Julian Hulme. All rights reserved. +// + +import UIKit + +class EmailValidatedTextField: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + + // Do any additional setup after loading the view. + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + +// Create a function called valid that takes no params, and returns a boolean. For now, always return true. + + private func valid() -> Bool { + return true + } + +// Create a function called updateUI that takes no params and returns no value. Leave the body blank for now. + func updateUI() { + + } + +} diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/EmailValidatedTextField.xib b/NoughtsAndCrosses/NoughtsAndCrosses/EmailValidatedTextField.xib new file mode 100644 index 0000000..ca2ccdd --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/EmailValidatedTextField.xib @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/Info.plist b/NoughtsAndCrosses/NoughtsAndCrosses/Info.plist index e372d58..c764056 100644 --- a/NoughtsAndCrosses/NoughtsAndCrosses/Info.plist +++ b/NoughtsAndCrosses/NoughtsAndCrosses/Info.plist @@ -33,6 +33,8 @@ UISupportedInterfaceOrientations UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight UISupportedInterfaceOrientations~ipad diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/LandingViewController.swift b/NoughtsAndCrosses/NoughtsAndCrosses/LandingViewController.swift new file mode 100644 index 0000000..c5e2922 --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/LandingViewController.swift @@ -0,0 +1,64 @@ +// +// LandingViewController.swift +// Assigment 2A +// +// Created by Rachel on 5/31/16. +// Copyright © 2016 Rachel Katz. All rights reserved. +// + +import UIKit + +class LandingViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + + + let _ = ClosureExperiment() + // Do any additional setup after loading the view. + } + + + override func viewWillAppear(animated: Bool) { + self.navigationController?.navigationBarHidden = true + + + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + + /* + // MARK: - Navigation + + // In a storyboard-based application, you will often want to do a little preparation before navigation + override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { + // Get the new view controller using segue.destinationViewController. + // Pass the selected object to the new view controller. + } + */ + + + + + @IBAction func loginButtonTapped(sender: UIButton) { + //print("login Button was tapped") + let lvc = LoginViewController(nibName: "LoginViewController", bundle: nil) + self.navigationController?.pushViewController(lvc, animated: true) + } + + + + @IBAction func registerButtonTapped(sender: UIButton) { + let rvc = RegistrationViewController(nibName: "RegistrationViewController", bundle: nil) + self.navigationController?.pushViewController(rvc, animated: true) + } + + + + + +} diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/LandingViewController.xib b/NoughtsAndCrosses/NoughtsAndCrosses/LandingViewController.xib new file mode 100644 index 0000000..00f0541 --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/LandingViewController.xib @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/LoginViewController.swift b/NoughtsAndCrosses/NoughtsAndCrosses/LoginViewController.swift new file mode 100644 index 0000000..b6e6e8e --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/LoginViewController.swift @@ -0,0 +1,81 @@ +// +// LoginViewController.swift +// Assigment 2A +// +// Created by Rachel on 5/31/16. +// Copyright © 2016 Rachel Katz. All rights reserved. +// + +import UIKit + +class LoginViewController: UIViewController, UITextFieldDelegate { + + @IBOutlet weak var emailField: EmailValidatedTextField! + @IBOutlet weak var passwordField: UITextField! + + + + + override func viewDidLoad() { + super.viewDidLoad() + self.title = "Login" + + emailField.delegate = self + passwordField.delegate = self + + // Do any additional setup after loading the view. + } + + override func viewWillAppear(animated: Bool) { + self.navigationController?.navigationBarHidden = false + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { + //print(string) + if( textField == emailField ){ + //print("email field was updated: " + emailField.text! + string) + } + return true + } + + @IBAction func loginButtonTapped(sender: UIButton) { + let email = emailField.text! + let password = passwordField.text! + + if !emailField.validate() { + return + } + + UserController.sharedInstance.loginUser(email, password: password, presentingViewController: nil, viewControllerCompletionFunction: {(user,message) in self.loginCallComplete(user,message:message)}) + + + + + } + func loginCallComplete(user: User?, message: String?){ + + if let _ = user { + let alert = UIAlertController(title: "Login Sucessful", message: "You will now be logged in", preferredStyle: UIAlertControllerStyle.Alert) + let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: {(action) in + let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate + appDelegate.navigateToBoardNavigationController() + + }) + alert.addAction(action) + self.presentViewController(alert, animated: true, completion: nil) + } else { + let alert = UIAlertController(title: "Login Failed", message: message!, preferredStyle: UIAlertControllerStyle.Alert) + alert.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.Default, handler: nil )) + self.presentViewController(alert, animated: true, completion: { + + }) + + } + + } +} diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/LoginViewController.xib b/NoughtsAndCrosses/NoughtsAndCrosses/LoginViewController.xib new file mode 100644 index 0000000..f7a053c --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/LoginViewController.xib @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/NetworkPlayViewController.swift b/NoughtsAndCrosses/NoughtsAndCrosses/NetworkPlayViewController.swift new file mode 100644 index 0000000..3b37530 --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/NetworkPlayViewController.swift @@ -0,0 +1,145 @@ +// +// NetworkPlayViewController.swift +// NoughtsAndCrosses +// +// Created by Rachel on 6/3/16. +// Copyright © 2016 Julian Hulme. All rights reserved. +// + + +//In the delegate method that returns the cell for an index, get the game in the gamesList at the given index, and display the email of the hostUser of the game in the cell. + +import UIKit + +class NetworkPlayViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { + + @IBOutlet weak var networkGameButton: UIButton! + @IBOutlet weak var tableView: UITableView! + var gameList = [OXGame]() + var refreshControl: UIRefreshControl! + +// override func viewDidAppear(animated: Bool) { +// self.title = "Network Play" +// self.navigationController?.navigationBarHidden = false +// OXGameController.sharedInstance.gameList(self, viewControllerCompletionFunction: {(gameList, message) in self.gameListReceived(gameList, message: message )}) +// } + + func gameListReceived( games: [OXGame]?, message: String?){ + + print("games received \(games!)") + if let newGames = games { + self.gameList = newGames + } + self.tableView.reloadData() + } + + override func viewDidLoad() { + super.viewDidLoad() + self.title = "Network Play" + tableView.dataSource = self + tableView.delegate = self + + refreshControl = UIRefreshControl() + refreshControl.attributedTitle = NSAttributedString(string: "Release to refresh") + refreshControl.addTarget(self, action: #selector(NetworkPlayViewController.refreshTable), forControlEvents: UIControlEvents.ValueChanged) + tableView.addSubview(refreshControl) + + + } + func refreshTable(){ + + OXGameController.sharedInstance.gameList( self, viewControllerCompletionFunction: {(gameList , message) in self.getListOfGamesCompletion(gameList, message: message )}) + + self.tableView.reloadData() + refreshControl.endRefreshing() + + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + override func viewWillAppear(animated: Bool) { + + self.title = "Network Play" + + self.navigationController?.navigationBarHidden = false + OXGameController.sharedInstance.gameList( self, viewControllerCompletionFunction: {(gameList , message) in self.getListOfGamesCompletion(gameList, message: message )}) + + self.tableView.reloadData() + refreshControl.endRefreshing() + + } + + func getListOfGamesCompletion(gameList: [OXGame]?, message: String?){ + if let newGames = gameList { + self.gameList = newGames + } + self.tableView.reloadData() + } + + func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + //return the number of games in the gamesList if it is set, if it is not set, return 0. + if ( gameList.count > 0 ){ + return gameList.count + } + + return 0 + } + func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { + //return a cell with it’s textLabel’s text property set to “test cell label” + + let cell = UITableViewCell() + + //cell.backgroundColor = UIColor.redColor() + //get the game in the gamesList at the given index, and display the email of the hostUser of the game in the cell. + cell.textLabel?.text = "gameID: " + self.gameList[indexPath.row].gameID! + ", " + self.gameList[indexPath.row].hostUser!.email + return cell + } + + func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { + return "Available Network Games" + } + + + //push a new board view onto the existing navigation. This involves, instantiating and then pushing the view. + + func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { + + let gameRowSelected = indexPath.row + let gameSelected = gameList[gameRowSelected] + + OXGameController.sharedInstance.acceptGame(gameSelected.gameID!, presentingViewController: self, viewControllerCompletionFunction: {(game, message) in self.acceptGameComplete(game,message:message)}) + } + + func acceptGameComplete( game: OXGame!, message: String! ){ + if let gameAcceptedSuccess = game { + let networkBoardView = BoardViewController(nibName: "BoardViewController", bundle: nil ) + networkBoardView.networkMode = true + networkBoardView.currentGame = gameAcceptedSuccess + self.navigationController?.pushViewController(networkBoardView, animated: true) + } + } + + + @IBAction func networkGameButtonTapped(sender: UIButton) { + + OXGameController.sharedInstance.createNewGame(UserController.sharedInstance.getLoggedInUser()!, presentingViewController: self, viewControllerCompletionFunction: {(game, message) in self.newStartGameCompleted(game,message:message)}) + } + + func newStartGameCompleted(game: OXGame!, message: String!){ + if let newGame = game { + let networkBoardView = BoardViewController(nibName: "BoardViewController", bundle: nil ) + networkBoardView.networkMode = true + networkBoardView.currentGame = newGame + self.navigationController?.pushViewController(networkBoardView, animated: true) + } + + } + + + + + +} diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/NetworkPlayViewController.xib b/NoughtsAndCrosses/NoughtsAndCrosses/NetworkPlayViewController.xib new file mode 100644 index 0000000..2a39ac4 --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/NetworkPlayViewController.xib @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/OXGameController.swift b/NoughtsAndCrosses/NoughtsAndCrosses/OXGameController.swift new file mode 100644 index 0000000..e1a949d --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/OXGameController.swift @@ -0,0 +1,523 @@ +// +// OXGameController.swift +// NoughtsAndCrosses +// +// Created by Alejandro Castillejo on 6/2/16. +// Copyright © 2016 Julian Hulme. All rights reserved. +// + +import Foundation +import UIKit +import SwiftyJSON + + +enum CellType : String { + + case O = "O" + case X = "X" + case EMPTY = "" + +} + +enum OXGameState : String { + + case inProgress + case complete_no_one_won + case complete_someone_won + case open + case abandoned + +} + +class OXGame { + + //the board data, stored in a 1D array + + var board = [CellType](count: 9, repeatedValue: CellType.EMPTY) + //the type of O or X that plays first + private var startType:CellType = CellType.X + + var gameID: String? + var hostUser: User? + var guestUser: User? + var backendState: OXGameState? + + //default constructor + init() { + + } + + //constructor from JSON + init(json:JSON) { + + self.gameID = json["id"].stringValue + self.backendState = OXGameState(rawValue: json["state"].stringValue) + self.board = deserialiseBoard(json["board"].stringValue) + self.hostUser = User(json:json["host_user"]) + self.guestUser = User(json:json["guest_user"]) + + } + + private func deserialiseBoard(boardString:String) -> [CellType] { + + var newBoard:[CellType] = [] + for (index, char) in boardString.characters.enumerate() { + print (char) + + if (char == "_") { + //EMPTY + newBoard.append(CellType.EMPTY) + } else if (char == "x") { + newBoard.append(CellType.X) + } else if (char == "o") { + newBoard.append(CellType.O) + } + } + return newBoard + } + + func serialiseBoard() -> String { + + var resultBoard = "" + for cell in self.board { + if (cell == CellType.EMPTY) { + resultBoard = resultBoard + "_" + } else if (cell == CellType.O) { + resultBoard = resultBoard + "o" + } else { + resultBoard = resultBoard + "x" + } + } + + return resultBoard + } + + + //returns the number of turns the players have had on the board + private func turn() -> Int { + return board.filter{(pos) in (pos != CellType.EMPTY)}.count + } + + //returns if its X or O's turn to play + func whosTurn() -> CellType { + let count = turn() + if (count % 2 == 0) { + return startType + } else { + + if (startType == CellType.X) { + return CellType.O + } else { + return CellType.X + } + } + + } + + func whoJustPlayed() -> CellType { + let next = whosTurn() + if (next == CellType.X) { + return CellType.O + } else { + return CellType.X + } + } + + func localUsersTurn() -> Bool { + + let XorO = whosTurn() + if (self.hostUser?.email == UserController.sharedInstance.getLoggedInUser()?.email) { + + + return (XorO == CellType.X) + } else { + return (XorO == CellType.O) + + } + } + + //returns user type at a specific board index + func typeAtIndex(pos:Int) -> CellType! { + return board[pos] + } + + //one of the later functions created in the demo + //execute the move in the game + func playMove(position:Int) -> CellType! { + board[position] = whosTurn() + return board[position] + } + + func winDetection() -> Bool { + + //Check rows + for i in 0...2 { + if((board[3*i] == board[3*i + 1]) && (board[3*i] == board[3*i + 2]) && !(String(board[3*i]) == "EMPTY")){ + print("Someone won at row i") + print(i) + print( board[i]) + return true + } + } + + //Check columns + for j in 0...2 { + if((board[j] == board[j + 3]) && (board[j] == board[j + 6]) && !(String(board[j]) == "EMPTY")){ + print("Someone won at column j") + print(j) + print( board[j]) + return true + } + } + + //Check diagonals + if((board[0] == board[4]) && (board[0] == board[8]) && !(String(board[0]) == "EMPTY")){ + print("Someone won at diagonal 1") + return true + } + if((board[2] == board[4]) && (board[2] == board[6]) && !(String(board[2]) == "EMPTY")){ + print("Someone won at diagonal 2") + return true + } + + return false + + } + + //the current state of the game + func state() -> OXGameState { + + //check if someone won on this turn + let win = winDetection() + + //if noone won, game is still in progress + if (win) { + return OXGameState.complete_someone_won + } else if (turn() == 9) { + return OXGameState.complete_no_one_won + } else { + return OXGameState.inProgress + } + + } + + //restart the game + func reset() { + board = [CellType](count: 9, repeatedValue: CellType.EMPTY) + print("Reseting") + } + + +} + + +class OXGameController: WebService { + + private var currentGame: OXGame? + + + class var sharedInstance: OXGameController { + struct Static { + static var instance:OXGameController? + static var token: dispatch_once_t = 0 + } + + dispatch_once(&Static.token) { + Static.instance = OXGameController() + } + return Static.instance! + + } + + + //Called when an user in an active game want to end the game before its finished + func cancelGame(gameID:String, presentingViewController:UIViewController? = nil, viewControllerCompletionFunction:(Bool,String?) -> ()) { + + //remember a request has 4 things: + //1: A endpoint + //2: A method + //3: input data (optional) + //4: A response + let request = self.createMutableRequest(NSURL(string: "https://ox-backend.herokuapp.com/games/\(gameID)"), method: "DELETE", parameters: nil) + + //execute request is a function we are able to call in OXGameController, because OXGameController extends WebService (See top of file, where OXGameController is defined) + self.executeRequest(request, presentingViewController:presentingViewController, requestCompletionFunction: {(responseCode, json) in + + //Here is our completion closure for the web request. when the web service is done, this is what is executed. + //Not only is the code in this block executed, but we are given 2 input parameters, responseCode and json. + //responseCode is the response code from the server. + //json is the response data received + + print(json) + + if (responseCode / 100 == 2) { //if the responseCode is 2xx (any responseCode in the 200's range is a success case. For example, some servers return 201 for successful object creation) + + //successfully deleted the game, no data to return needed + + //lets execute that closure now - Lets me be clear. This is 1 step more advanced than normal. We are executing a closure inside a closure (we are executing the viewControllerCompletionFunction from within the requestCompletionFunction. + viewControllerCompletionFunction(true,nil) + } else { + //the web service to create a user failed. Lets extract the error message to be displayed + + let errorMessage = json["errors"]["full_messages"][0].stringValue + + //execute the closure in the ViewController + viewControllerCompletionFunction(false, errorMessage) + } + + }) + + //we are now done with the registerUser function. Note that this function doesnt return anything. But because of the viewControllerCompletionFunction closure we are given as an input parameter, we can set in motion a function in the calling class when it is needed. + + } + + + + // this function returns a array of OXGAmes available from the web. if the webs service fails for some reason it returns nil for the OXGame array, and a message instead to show the user for reason o ffailure + func gameList(presentingViewController:UIViewController? = nil, viewControllerCompletionFunction:([OXGame]?,String?) -> ()) { + + //remember a request has 4 things: + //1: A endpoint + //2: A method + //3: input data (optional) + //4: A response + let request = self.createMutableRequest(NSURL(string: "https://ox-backend.herokuapp.com/games"), method: "GET", parameters: nil) + + //execute request is a function we are able to call in OXGameController, because OXGameController extends WebService (See top of file, where OXGameController is defined) + self.executeRequest(request, presentingViewController:presentingViewController, requestCompletionFunction: {(responseCode, json) in + + //Here is our completion closure for the web request. when the web service is done, this is what is executed. + //Not only is the code in this block executed, but we are given 2 input parameters, responseCode and json. + //responseCode is the response code from the server. + //json is the response data received + + print(json) + + if (responseCode / 100 == 2) { //if the responseCode is 2xx (any responseCode in the 200's range is a success case. For example, some servers return 201 for successful object creation) + + //successfully received the game list + var list:[OXGame]? = [] + + //lets populate the list var with the game data received + for (str, game) in json { + var game = OXGame(json: game) + if (game.backendState == OXGameState.open) { + list?.append(game) + } + + } + + //lets execute that closure now - Lets me be clear. This is 1 step more advanced than normal. We are executing a closure inside a closure (we are executing the viewControllerCompletionFunction from within the requestCompletionFunction. + viewControllerCompletionFunction(list,nil) + } else { + //the web service to create a user failed. Lets extract the error message to be displayed + + let errorMessage = json["errors"]["full_messages"][0].stringValue + + //execute the closure in the ViewController + viewControllerCompletionFunction(nil, errorMessage) + } + + }) + + //we are now done with the registerUser function. Note that this function doesnt return anything. But because of the viewControllerCompletionFunction closure we are given as an input parameter, we can set in motion a function in the calling class when it is needed. + + } + + + //Can only be called when there is an active game + func playMove(board: String, gameId:String, presentingViewController:UIViewController? = nil, viewControllerCompletionFunction:(OXGame?,String?) -> ()) { + + + //remember a request has 4 things: + //1: A endpoint + //2: A method + //3: input data (optional) + //4: A response + + var params = ["board":board] + let request = self.createMutableRequest(NSURL(string: "https://ox-backend.herokuapp.com/games/\(gameId)"), method: "PUT", parameters: params) + + //execute request is a function we are able to call in OXGameController, because OXGameController extends WebService (See top of file, where OXGameController is defined) + self.executeRequest(request, presentingViewController:presentingViewController, requestCompletionFunction: {(responseCode, json) in + + //Here is our completion closure for the web request. when the web service is done, this is what is executed. + //Not only is the code in this block executed, but we are given 2 input parameters, responseCode and json. + //responseCode is the response code from the server. + //json is the response data received + + print(json) + + if (responseCode / 100 == 2) { //if the responseCode is 2xx (any responseCode in the 200's range is a success case. For example, some servers return 201 for successful object creation) + + let game = OXGame(json: json) + + //lets execute that closure now - Lets me be clear. This is 1 step more advanced than normal. We are executing a closure inside a closure (we are executing the viewControllerCompletionFunction from within the requestCompletionFunction. + viewControllerCompletionFunction(game,nil) + } else { + //the web service to create a user failed. Lets extract the error message to be displayed + + let errorMessage = json["errors"]["full_messages"][0].stringValue + + //execute the closure in the ViewController + viewControllerCompletionFunction(nil, errorMessage) + } + + }) + + //we are now done with the registerUser function. Note that this function doesnt return anything. But because of the viewControllerCompletionFunction closure we are given as an input parameter, we can set in motion a function in the calling class when it is needed. + + + } + + //Can only be called when there is an active game + func getGame(gameId:String, presentingViewController:UIViewController? = nil, viewControllerCompletionFunction:(OXGame?,String?) -> ()) { + + + //remember a request has 4 things: + //1: A endpoint + //2: A method + //3: input data (optional) + //4: A response + + let request = self.createMutableRequest(NSURL(string: "https://ox-backend.herokuapp.com/games/\(gameId)"), method: "GET", parameters: nil) + + //execute request is a function we are able to call in OXGameController, because OXGameController extends WebService (See top of file, where OXGameController is defined) + self.executeRequest(request, presentingViewController:presentingViewController, requestCompletionFunction: {(responseCode, json) in + + //Here is our completion closure for the web request. when the web service is done, this is what is executed. + //Not only is the code in this block executed, but we are given 2 input parameters, responseCode and json. + //responseCode is the response code from the server. + //json is the response data received + + print(json) + + if (responseCode / 100 == 2) { //if the responseCode is 2xx (any responseCode in the 200's range is a success case. For example, some servers return 201 for successful object creation) + + let game = OXGame(json: json) + + //lets execute that closure now - Lets me be clear. This is 1 step more advanced than normal. We are executing a closure inside a closure (we are executing the viewControllerCompletionFunction from within the requestCompletionFunction. + viewControllerCompletionFunction(game,nil) + } else { + //the web service to create a user failed. Lets extract the error message to be displayed + + let errorMessage = json["errors"]["full_messages"][0].stringValue + + //execute the closure in the ViewController + viewControllerCompletionFunction(nil, errorMessage) + } + + }) + + //we are now done with the registerUser function. Note that this function doesnt return anything. But because of the viewControllerCompletionFunction closure we are given as an input parameter, we can set in motion a function in the calling class when it is needed. + + + } + + + //Simple random move, it will always try to play the first indexes + func playRandomMove() -> (CellType, Int)? { + print("Playing random move") + if let count = currentGame?.board.count { + for i in 0...count - 1 { + if (currentGame?.board[i] == CellType.EMPTY){ + let cellType: CellType = (currentGame?.playMove(i))! + print(cellType) + print("Succesfully at: " + String(i)) + return (cellType, i) + } + } + } + print("Unsuccesfully") + return nil + + } + + func createNewGame(host:User, presentingViewController:UIViewController? = nil, viewControllerCompletionFunction:(OXGame?,String?) -> ()) { + print("Creating new network game") + + //remember a request has 4 things: + //1: A endpoint + //2: A method + //3: input data (optional) + //4: A response + let request = self.createMutableRequest(NSURL(string: "https://ox-backend.herokuapp.com/games/"), method: "POST", parameters: nil) + + //execute request is a function we are able to call in OXGameController, because OXGameController extends WebService (See top of file, where OXGameController is defined) + self.executeRequest(request, presentingViewController:presentingViewController, requestCompletionFunction: {(responseCode, json) in + + //Here is our completion closure for the web request. when the web service is done, this is what is executed. + //Not only is the code in this block executed, but we are given 2 input parameters, responseCode and json. + //responseCode is the response code from the server. + //json is the response data received + + print(json) + + if (responseCode / 100 == 2) { //if the responseCode is 2xx (any responseCode in the 200's range is a success case. For example, some servers return 201 for successful object creation) + + //lets populate the list var with the game data received + let game = OXGame(json: json) + + //lets execute that closure now - Lets me be clear. This is 1 step more advanced than normal. We are executing a closure inside a closure (we are executing the viewControllerCompletionFunction from within the requestCompletionFunction. + viewControllerCompletionFunction(game,nil) + } else { + //the web service to create a user failed. Lets extract the error message to be displayed + + let errorMessage = json["errors"]["full_messages"][0].stringValue + + //execute the closure in the ViewController + viewControllerCompletionFunction(nil, errorMessage) + } + + }) + + //we are now done with the acceptGame function. Note that this function doesnt return anything. But because of the viewControllerCompletionFunction closure we are given as an input parameter, we can set in motion a function in the calling class when it is needed. + + + } + + + func acceptGame(id:String, presentingViewController:UIViewController? = nil, viewControllerCompletionFunction:(OXGame?,String?) -> ()) { + + + //remember a request has 4 things: + //1: A endpoint + //2: A method + //3: input data (optional) + //4: A response + let request = self.createMutableRequest(NSURL(string: "https://ox-backend.herokuapp.com/games/\(id)/join"), method: "GET", parameters: nil) + + //execute request is a function we are able to call in OXGameController, because OXGameController extends WebService (See top of file, where OXGameController is defined) + self.executeRequest(request, presentingViewController:presentingViewController, requestCompletionFunction: {(responseCode, json) in + + //Here is our completion closure for the web request. when the web service is done, this is what is executed. + //Not only is the code in this block executed, but we are given 2 input parameters, responseCode and json. + //responseCode is the response code from the server. + //json is the response data received + + print(json) + + if (responseCode / 100 == 2) { //if the responseCode is 2xx (any responseCode in the 200's range is a success case. For example, some servers return 201 for successful object creation) + + //lets obtain the returned game data received + let game = OXGame(json: json) + + //lets execute that closure now - Lets me be clear. This is 1 step more advanced than normal. We are executing a closure inside a closure (we are executing the viewControllerCompletionFunction from within the requestCompletionFunction. + viewControllerCompletionFunction(game,nil) + } else { + //the web service to create a user failed. Lets extract the error message to be displayed + + let errorMessage = json["errors"]["full_messages"][0].stringValue + + //execute the closure in the ViewController + viewControllerCompletionFunction(nil, errorMessage) + } + + }) + + //we are now done with the acceptGame function. Note that this function doesnt return anything. But because of the viewControllerCompletionFunction closure we are given as an input parameter, we can set in motion a function in the calling class when it is needed. + + + } + +} \ No newline at end of file diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/RegistrationViewController.swift b/NoughtsAndCrosses/NoughtsAndCrosses/RegistrationViewController.swift new file mode 100644 index 0000000..32e7edd --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/RegistrationViewController.swift @@ -0,0 +1,99 @@ +// +// RegistrationViewController.swift +// Assigment 2A +// +// Created by Rachel on 5/31/16. +// Copyright © 2016 Rachel Katz. All rights reserved. +// + +import UIKit + +class RegistrationViewController: UIViewController { + + + @IBOutlet weak var emailField: EmailValidatedTextField! + @IBOutlet weak var passwordField: UITextField! + + + override func viewDidLoad() { + super.viewDidLoad() + self.title = "Register" + + + // Do any additional setup after loading the view. + } + override func viewWillAppear(animated: Bool) { + self.navigationController?.navigationBarHidden = false + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + @IBAction func registerButtonTapped(sender: UIButton) { + let email = emailField.text! + let password = passwordField.text! + + if ( !emailField.validate() ){ + return + } + + //let( failMsg , newUser ) = UserController.sharedInstance.registerUser(email, newPassword: password ) + //new registration code + UserController.sharedInstance.registerUser(email,password: password, presentingViewController: self, viewControllerCompletionFunction: {(user,message) in self.registrationComplete(user,message:message)}) + + + /** + if ( newUser != nil ){ + print("User registered view registration view") + + let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate + + appDelegate.navigateToBoardNavigationController() + + NSUserDefaults.standardUserDefaults().setValue("TRUE", forKey: "userIdLoggedIn") + + } + else { + if( failMsg != nil ){ + let alertController = UIAlertController(title: "WARNING", message: failMsg, preferredStyle: .Alert) + + let OKAction = UIAlertAction(title: "OK", style: .Default, handler: nil) + + alertController.addAction(OKAction) + + self.presentViewController(alertController, animated: true, completion: nil) + } + } + + */ + } + + + func registrationComplete(user: User?, message: String?){ + + if let _ = user { + let alert = UIAlertController(title: "Registration Sucessful", message: "You will now be registered", preferredStyle: UIAlertControllerStyle.Alert) + let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: {(action) in + let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate + appDelegate.navigateToBoardNavigationController() + + }) + alert.addAction(action) + self.presentViewController(alert, animated: true, completion: nil) + } else { + let alert = UIAlertController(title: "Registration Failed", message: message!, preferredStyle: UIAlertControllerStyle.Alert) + alert.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.Default, handler: nil )) + self.presentViewController(alert, animated: true, completion: { + + }) + + } + + + + + } + +} diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/RegistrationViewController.xib b/NoughtsAndCrosses/NoughtsAndCrosses/RegistrationViewController.xib new file mode 100644 index 0000000..1bb123b --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/RegistrationViewController.xib @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/NoughtsAndCrosses/NoughtsAndCrosses/UserController.swift b/NoughtsAndCrosses/NoughtsAndCrosses/UserController.swift new file mode 100644 index 0000000..1e8ac42 --- /dev/null +++ b/NoughtsAndCrosses/NoughtsAndCrosses/UserController.swift @@ -0,0 +1,205 @@ +// +// UserManager.swift +// Onboarding +// +// Created by Josh Broomberg on 2016/05/28. +// Copyright © 2016 iXperience. All rights reserved. +// + +import Foundation +import Alamofire +import SwiftyJSON + +struct User { + var email: String + var password: String + var token:String + var client:String + + //default contructor + init(email:String, password:String, token:String, client:String) { + self.email = email + self.password = password + self.token = token + self.client = client + } + + //constructor from JSON + init(json:JSON) { + + self.email = json["email"].stringValue + self.client = json["client"].stringValue + self.token = json["token"].stringValue + self.password = json["password"].stringValue + + + } +} + + +class UserController: WebService { + + class var sharedInstance: UserController { + struct Static { + static var instance:UserController? + static var token: dispatch_once_t = 0 + } + + dispatch_once(&Static.token) { + Static.instance = UserController() + } + return Static.instance! + } + + //private var users: [User] = [] + + var logged_in_user: User? + + + func registerUser(email:String, password:String, presentingViewController:UIViewController? = nil, viewControllerCompletionFunction:(User?,String?) -> ()) { + + let user = ["email":email,"password":password] + + //remember a request has 4 things: + //1: A endpoint + //2: A method + //3: input data (optional) + //4: A response + let request = self.createMutableAnonRequest(NSURL(string: "https://ox-backend.herokuapp.com/auth"), method: "POST", parameters: user) + + //execute request is a function we are able to call in UserController, because UserController extends WebService (See top of file, where UserController is defined) + self.executeRequest(request, presentingViewController:presentingViewController, requestCompletionFunction: {(responseCode, json) in + + //Here is our completion closure for the web request. when the web service is done, this is what is executed. + //Not only is the code in this block executed, but we are given 2 input parameters, responseCode and json. + //responseCode is the response code from the server. + //json is the response data received + + print(json) + var user:User = User(email: "", password: "", token: "", client:"") + + if (responseCode / 100 == 2) { //if the responseCode is 2xx (any responseCode in the 200's range is a success case. For example, some servers return 201 for successful object creation) + + //successfully registered user. get the obtained data from the json response data and create the user object to give back to the calling ViewController + user = User(email: json["data"]["email"].stringValue,password:"not_given_and_not_stored",token:json["data"]["token"].stringValue, client:json["data"]["client"].stringValue) + //while we at it, lets persist our user + self.storeUser(user) + + //and while we still at it, lets set the user as logged in. This is good programming as we are keeping all the user management inside the UserController and handling it at the right time + self.setLoggedInUser(user) + + //Note that our registerUser function has 4 parameters: email, password, presentingViewController and requestCompletionFunction + //requestCompletionFunction is a closure for what is to happen in the ViewController when we are done with the webservice. + + //lets execute that closure now - Lets me be clear. This is 1 step more advanced than normal. We are executing a closure inside a closure (we are executing the viewControllerCompletionFunction from within the requestCompletionFunction. + viewControllerCompletionFunction(user,nil) + } else { + //the web service to create a user failed. Lets extract the error message to be displayed + + let errorMessage = json["errors"]["full_messages"][0].stringValue + + //execute the closure in the ViewController + viewControllerCompletionFunction(nil,errorMessage) + } + + }) + + //we are now done with the registerUser function. Note that this function doesnt return anything. But because of the viewControllerCompletionFunction closure we are given as an input parameter, we can set in motion a function in the calling class when it is needed. + + } + + func loginUser(email:String, password:String, presentingViewController:UIViewController? = nil, viewControllerCompletionFunction:(User?,String?) -> ()) { + + let user = ["email":email,"password":password] + + //remember a request has 4 things: + //1: A endpoint + //2: A method + //3: input data (optional) + //4: A response + let request = self.createMutableAnonRequest(NSURL(string: "https://ox-backend.herokuapp.com/auth/sign_in"), method: "POST", parameters: user) + + //execute request is a function we are able to call in UserController, because UserController extends WebService (See top of file, where UserController is defined) + self.executeRequest(request, presentingViewController:presentingViewController, requestCompletionFunction: {(responseCode, json) in + + //Here is our completion closure for the web request. when the web service is done, this is what is executed. + //Not only is the code in this block executed, but we are given 2 input parameters, responseCode and json. + //responseCode is the response code from the server. + //json is the response data received + + print(json) + var user:User = User(email: "", password: "",token:"", client: "") + + if (responseCode / 100 == 2) { //if the responseCode is 2xx (any responseCode in the 200's range is a success case. For example, some servers return 201 for successful object creation) + + //successfully registered user. get the obtained data from the json response data and create the user object to give back to the calling ViewController + user = User(email: json["data"]["email"].stringValue,password:"not_given_and_not_stored",token:json["data"]["token"].stringValue, client:json["data"]["client"].stringValue) + + //we need to get our user security token out of the request's header (remember from Postman, we need those values when making in app calls) + + + //while we at it, lets persist our user + self.storeUser(user) + + //and while we still at it, lets set the user as logged in. This is good programming as we are keeping all the user management inside the UserController and handling it at the right time + self.setLoggedInUser(user) + + //Note that our registerUser function has 4 parameters: email, password, presentingViewController and requestCompletionFunction + //requestCompletionFunction is a closure for what is to happen in the ViewController when we are done with the webservice. + + //lets execute that closure now - Lets me be clear. This is 1 step more advanced than normal. We are executing a closure inside a closure (we are executing the viewControllerCompletionFunction from within the requestCompletionFunction. + viewControllerCompletionFunction(user,nil) + } else { + //the web service to create a user failed. Lets extract the error message to be displayed + + let errorMessage = json["errors"][0].stringValue + + //execute the closure in the ViewController + viewControllerCompletionFunction(nil,errorMessage) + } + + }) + + //we are now done with the registerUser function. Note that this function doesnt return anything. But because of the viewControllerCompletionFunction closure we are given as an input parameter, we can set in motion a function in the calling class when it is needed. + + } + + //MARK:- User Persistence Functions + func storeUser(user:User) { + + let userDict = ["email":user.email, "token":user.token, "password":user.password,"client":user.client] + NSUserDefaults.standardUserDefaults().setObject(userDict, forKey:user.email) + + + } + + func setLoggedInUser(user:User?) { + + NSUserDefaults.standardUserDefaults().setObject(user?.email, forKey: "loggedInUser") + + } + + func getLoggedInUser() -> User? { + + if let userId = NSUserDefaults.standardUserDefaults().stringForKey("loggedInUser") { + //a user is logged in, return the User object for this user id + return self.getStoredUser(userId) + } else { + //else user not found + return nil + } + } + + func getStoredUser(id:String) -> User? { + + if let userDict:Dictionary = NSUserDefaults.standardUserDefaults().objectForKey(id) as? Dictionary { + //user found + let user = User(email: id, password: userDict["password"]!, token: userDict["token"]!, client:userDict["client"]!) + return user + } else { + //else user not found + return nil + } + + } +} diff --git a/NoughtsAndCrosses/Podfile b/NoughtsAndCrosses/Podfile new file mode 100644 index 0000000..f630c27 --- /dev/null +++ b/NoughtsAndCrosses/Podfile @@ -0,0 +1,18 @@ +#source ‘https://github.com/CocoaPods/Specs.git’ +#global platform for your project +platform :ios, ‘8.0’ + + +# Comment this line if you're not using Swift and don't want to use dynamic frameworks + +use_frameworks! + + + +target 'NoughtsAndCrosses' do + workspace '/Users/Katz/oX/NoughtsAndCrosses' + pod 'Alamofire', '~> 3.4' + pod 'SwiftyJSON', :git => 'https://github.com/SwiftyJSON/SwiftyJSON.git' + +end + diff --git a/NoughtsAndCrosses/Podfile.lock b/NoughtsAndCrosses/Podfile.lock new file mode 100644 index 0000000..6aa96a4 --- /dev/null +++ b/NoughtsAndCrosses/Podfile.lock @@ -0,0 +1,24 @@ +PODS: + - Alamofire (3.4.0) + - SwiftyJSON (2.3.2) + +DEPENDENCIES: + - Alamofire (~> 3.4) + - SwiftyJSON (from `https://github.com/SwiftyJSON/SwiftyJSON.git`) + +EXTERNAL SOURCES: + SwiftyJSON: + :git: https://github.com/SwiftyJSON/SwiftyJSON.git + +CHECKOUT OPTIONS: + SwiftyJSON: + :commit: 2a5b70f06001316d4fb54501edc70b4084705da0 + :git: https://github.com/SwiftyJSON/SwiftyJSON.git + +SPEC CHECKSUMS: + Alamofire: c19a627cefd6a95f840401c49ab1f124e07f54ee + SwiftyJSON: 04ccea08915aa0109039157c7974cf0298da292a + +PODFILE CHECKSUM: 17b09ec58cd341184bdf616ad0ade19eed1aa4ed + +COCOAPODS: 1.0.1 diff --git a/NoughtsAndCrosses/Pods/Alamofire/LICENSE b/NoughtsAndCrosses/Pods/Alamofire/LICENSE new file mode 100644 index 0000000..4cfbf72 --- /dev/null +++ b/NoughtsAndCrosses/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/NoughtsAndCrosses/Pods/Alamofire/README.md b/NoughtsAndCrosses/Pods/Alamofire/README.md new file mode 100644 index 0000000..68e54e9 --- /dev/null +++ b/NoughtsAndCrosses/Pods/Alamofire/README.md @@ -0,0 +1,1270 @@ +![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! + +pod 'Alamofire', '~> 3.4' +``` + +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 + +#### 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(error!) } + + guard let validData = data else { + let failureReason = "Data could not be serialized. Input data was nil." + let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + + do { + let XML = try ONOXMLDocument(data: validData) + return .Success(XML) + } catch { + return .Failure(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(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 { + let failureReason = "JSON could not be serialized into response object: \(value)" + let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + case .Failure(let error): + return .Failure(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 Alamofire.Request { + public func responseCollection(completionHandler: Response<[T], NSError> -> Void) -> Self { + let responseSerializer = ResponseSerializer<[T], NSError> { request, response, data, error in + guard error == nil else { return .Failure(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 { + let failureReason = "Response collection could not be serialized due to nil response" + let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) + return .Failure(error) + } + case .Failure(let error): + return .Failure(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 + } + + static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [User] { + var users: [User] = [] + + if let representation = representation as? [[String: AnyObject]] { + for userRepresentation in representation { + if let user = User(response: response, representation: userRepresentation) { + users.append(user) + } + } + } + + return users + } +} +``` + +```swift +Alamofire.request(.GET, "http://example.com/users") + .responseCollection { (response: Response<[User], NSError>) 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 > 1: + 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 + +## 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. + +## License + +Alamofire is released under the MIT license. See LICENSE for details. diff --git a/NoughtsAndCrosses/Pods/Alamofire/Source/Alamofire.swift b/NoughtsAndCrosses/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 0000000..cb4b36a --- /dev/null +++ b/NoughtsAndCrosses/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/NoughtsAndCrosses/Pods/Alamofire/Source/Download.swift b/NoughtsAndCrosses/Pods/Alamofire/Source/Download.swift new file mode 100644 index 0000000..97b146f --- /dev/null +++ b/NoughtsAndCrosses/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/NoughtsAndCrosses/Pods/Alamofire/Source/Error.swift b/NoughtsAndCrosses/Pods/Alamofire/Source/Error.swift new file mode 100644 index 0000000..467d99c --- /dev/null +++ b/NoughtsAndCrosses/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/NoughtsAndCrosses/Pods/Alamofire/Source/Manager.swift b/NoughtsAndCrosses/Pods/Alamofire/Source/Manager.swift new file mode 100644 index 0000000..7b5f888 --- /dev/null +++ b/NoughtsAndCrosses/Pods/Alamofire/Source/Manager.swift @@ -0,0 +1,755 @@ +// +// 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 os = NSProcessInfo.processInfo().operatingSystemVersionString + + var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString + let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString + + if CFStringTransform(mutableUserAgent, UnsafeMutablePointer(nil), transform, false) { + return mutableUserAgent as String + } + } + + 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/NoughtsAndCrosses/Pods/Alamofire/Source/MultipartFormData.swift b/NoughtsAndCrosses/Pods/Alamofire/Source/MultipartFormData.swift new file mode 100644 index 0000000..b4087ec --- /dev/null +++ b/NoughtsAndCrosses/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/NoughtsAndCrosses/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/NoughtsAndCrosses/Pods/Alamofire/Source/NetworkReachabilityManager.swift new file mode 100644 index 0000000..949ed28 --- /dev/null +++ b/NoughtsAndCrosses/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -0,0 +1,253 @@ +// +// 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 with the default socket IPv4 or IPv6 address. + + - returns: The new `NetworkReachabilityManager` instance. + */ + public convenience init?() { + if #available(iOS 9.0, OSX 10.10, *) { + var address = sockaddr_in6() + address.sin6_len = UInt8(sizeofValue(address)) + address.sin6_family = sa_family_t(AF_INET6) + + guard let reachability = withUnsafePointer(&address, { + SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) + }) else { return nil } + + self.init(reachability: reachability) + } else { + 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/NoughtsAndCrosses/Pods/Alamofire/Source/Notifications.swift b/NoughtsAndCrosses/Pods/Alamofire/Source/Notifications.swift new file mode 100644 index 0000000..cece87a --- /dev/null +++ b/NoughtsAndCrosses/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/NoughtsAndCrosses/Pods/Alamofire/Source/ParameterEncoding.swift b/NoughtsAndCrosses/Pods/Alamofire/Source/ParameterEncoding.swift new file mode 100644 index 0000000..bfa4d12 --- /dev/null +++ b/NoughtsAndCrosses/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 Chinense 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/NoughtsAndCrosses/Pods/Alamofire/Source/Response.swift b/NoughtsAndCrosses/Pods/Alamofire/Source/Response.swift new file mode 100644 index 0000000..dd700bb --- /dev/null +++ b/NoughtsAndCrosses/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/NoughtsAndCrosses/Pods/Alamofire/Source/ResponseSerialization.swift b/NoughtsAndCrosses/Pods/Alamofire/Source/ResponseSerialization.swift new file mode 100644 index 0000000..5b7b61f --- /dev/null +++ b/NoughtsAndCrosses/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/NoughtsAndCrosses/Pods/Alamofire/Source/Result.swift b/NoughtsAndCrosses/Pods/Alamofire/Source/Result.swift new file mode 100644 index 0000000..ed1df0f --- /dev/null +++ b/NoughtsAndCrosses/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/NoughtsAndCrosses/Pods/Alamofire/Source/ServerTrustPolicy.swift b/NoughtsAndCrosses/Pods/Alamofire/Source/ServerTrustPolicy.swift new file mode 100644 index 0000000..44ba100 --- /dev/null +++ b/NoughtsAndCrosses/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/NoughtsAndCrosses/Pods/Alamofire/Source/Stream.swift b/NoughtsAndCrosses/Pods/Alamofire/Source/Stream.swift new file mode 100644 index 0000000..07ebe33 --- /dev/null +++ b/NoughtsAndCrosses/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/NoughtsAndCrosses/Pods/Alamofire/Source/Timeline.swift b/NoughtsAndCrosses/Pods/Alamofire/Source/Timeline.swift new file mode 100644 index 0000000..3610f15 --- /dev/null +++ b/NoughtsAndCrosses/Pods/Alamofire/Source/Timeline.swift @@ -0,0 +1,125 @@ +// +// 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) + + 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 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/NoughtsAndCrosses/Pods/Alamofire/Source/Upload.swift b/NoughtsAndCrosses/Pods/Alamofire/Source/Upload.swift new file mode 100644 index 0000000..7b31ba5 --- /dev/null +++ b/NoughtsAndCrosses/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/NoughtsAndCrosses/Pods/Alamofire/Source/Validation.swift b/NoughtsAndCrosses/Pods/Alamofire/Source/Validation.swift new file mode 100644 index 0000000..e90db2d --- /dev/null +++ b/NoughtsAndCrosses/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/NoughtsAndCrosses/Pods/Local Podspecs/SwiftyJSON.podspec.json b/NoughtsAndCrosses/Pods/Local Podspecs/SwiftyJSON.podspec.json new file mode 100644 index 0000000..e5818d1 --- /dev/null +++ b/NoughtsAndCrosses/Pods/Local Podspecs/SwiftyJSON.podspec.json @@ -0,0 +1,25 @@ +{ + "name": "SwiftyJSON", + "version": "2.3.2", + "summary": "SwiftyJSON makes it easy to deal with JSON data in Swift", + "homepage": "https://github.com/SwiftyJSON/SwiftyJSON", + "license": { + "type": "MIT" + }, + "authors": { + "lingoer": "lingoerer@gmail.com", + "tangplin": "tangplin@gmail.com" + }, + "requires_arc": true, + "platforms": { + "osx": "10.9", + "ios": "8.0", + "watchos": "2.0", + "tvos": "9.0" + }, + "source": { + "git": "https://github.com/SwiftyJSON/SwiftyJSON.git", + "tag": "2.3.2" + }, + "source_files": "Source/*.swift" +} diff --git a/NoughtsAndCrosses/Pods/Manifest.lock b/NoughtsAndCrosses/Pods/Manifest.lock new file mode 100644 index 0000000..6aa96a4 --- /dev/null +++ b/NoughtsAndCrosses/Pods/Manifest.lock @@ -0,0 +1,24 @@ +PODS: + - Alamofire (3.4.0) + - SwiftyJSON (2.3.2) + +DEPENDENCIES: + - Alamofire (~> 3.4) + - SwiftyJSON (from `https://github.com/SwiftyJSON/SwiftyJSON.git`) + +EXTERNAL SOURCES: + SwiftyJSON: + :git: https://github.com/SwiftyJSON/SwiftyJSON.git + +CHECKOUT OPTIONS: + SwiftyJSON: + :commit: 2a5b70f06001316d4fb54501edc70b4084705da0 + :git: https://github.com/SwiftyJSON/SwiftyJSON.git + +SPEC CHECKSUMS: + Alamofire: c19a627cefd6a95f840401c49ab1f124e07f54ee + SwiftyJSON: 04ccea08915aa0109039157c7974cf0298da292a + +PODFILE CHECKSUM: 17b09ec58cd341184bdf616ad0ade19eed1aa4ed + +COCOAPODS: 1.0.1 diff --git a/NoughtsAndCrosses/Pods/Pods.xcodeproj/project.pbxproj b/NoughtsAndCrosses/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 0000000..ab8cb2d --- /dev/null +++ b/NoughtsAndCrosses/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,745 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 095406039B4D371E48D08B38A2975AC8 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C2D373B20FED4A7FAA1E5EC993B74FA /* Error.swift */; }; + 0958E439A0E82F238189BEC6FC84242A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CEC22C73C1608DFA5D5D78BDCB218219 /* Foundation.framework */; }; + 16102E4E35FAA0FC4161282FECE56469 /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 22E8F73147901B7F30D5AF9C3924364F /* Timeline.swift */; }; + 2D3405986FC586FA6C0A5E0B6BA7E64E /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC71BA52BA5094114A735CF801251599 /* Validation.swift */; }; + 34CCDCA848A701466256BC2927DA8856 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51D3931E976C0FF2B3CBFD590528F74E /* NetworkReachabilityManager.swift */; }; + 3EA8F215C9C1432D74E5CCA4834AA8C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = D509E73B46BBAF5DFF3E6517F2940EDB /* ResponseSerialization.swift */; }; + 4081EA628AF0B73AC51FFB9D7AB3B89E /* Manager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 29CF31B29D3B759DCFB762B564F77BF2 /* Manager.swift */; }; + 4FBE18CD56428D3DD6979ABB59F9D87E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CEC22C73C1608DFA5D5D78BDCB218219 /* Foundation.framework */; }; + 5BC19E6E0F199276003F0AF96838BCE5 /* Upload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4BA00B7770CE5C0311E922DD7CA72265 /* Upload.swift */; }; + 5CB05FBCB32D21E194B5ECF680CB6AE0 /* Download.swift in Sources */ = {isa = PBXBuildFile; fileRef = 813B1E8F489400673C23422C9FECCAB8 /* Download.swift */; }; + 62E8346F03C03E7F4D631361F325689E /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26C873080C03FCB4833BC2B3063E0862 /* Response.swift */; }; + 7B48852C4D848FA2DA416A98F6425869 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70A64FD6EA90FBA31DFA9101B0FF7901 /* ServerTrustPolicy.swift */; }; + 801FBB0AAB759009AB8E2875FCB39DBE /* SwiftyJSON-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = BA5B8F6AE942BA3D7E8C0B8732349B67 /* SwiftyJSON-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8EB11202167FCDDF1257AAAB1D1FB244 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21E5EF6BB7D195D5FA6C641B07B50D4D /* Alamofire.swift */; }; + 91C09AC2A52ED69A27C8D923139A006F /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CEC22C73C1608DFA5D5D78BDCB218219 /* Foundation.framework */; }; + 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 6AB7F7C2BBCF479B732091AEE1D3050B /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9F113FEFF1016C766C59FF0C5D06FB0D /* SwiftyJSON-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 17C7C311169F3CAF970644274FB0787A /* SwiftyJSON-dummy.m */; }; + A31CB1F4783A8042B97B1D6ED775DAA8 /* SwiftyJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = CFBFF681209D4E5030FF4116EFD41362 /* SwiftyJSON.swift */; }; + AA314156AC500125F4078EE968DB14C6 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAE4A28E1CBA2C4B6D06B5029FAFD7D1 /* Result.swift */; }; + ADF19C953CE2A7D0B72EC93A81FCCC26 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 9FF202EA510C267D614F17C0950E6395 /* Alamofire-dummy.m */; }; + AE4CF87C02C042DF13ED5B21C4FDC1E0 /* Stream.swift in Sources */ = {isa = PBXBuildFile; fileRef = 582C0D56CD61146874DF0CEF602D1F08 /* Stream.swift */; }; + B6DD6E4F2AC743E86AE312FFA8CC1604 /* Pods-NoughtsAndCrosses-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 80479C151B14A2E9D5DC6BEAF443061D /* Pods-NoughtsAndCrosses-dummy.m */; }; + B90A8CBDE5F07FD959E3821410626D06 /* Pods-NoughtsAndCrosses-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = DE9B5EA6A4147AAD3A5F1E7F902EE31C /* Pods-NoughtsAndCrosses-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BE41196F6A3903E59C3306FE3F8B43FE /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 20608D49620C157D6026B74F348507BC /* Notifications.swift */; }; + C0DB70AB368765DC64BFB5FEA75E0696 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6524314C6E13EF8F837E915AF4237778 /* ParameterEncoding.swift */; }; + C7B6DD7C0456C50289A2C381DFE9FA3F /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 413FC5CAFF8CC5E69FEB7938D8EFA262 /* MultipartFormData.swift */; }; + EFE92E8D3813DD26E78E93EEAF6D7E7E /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDE7F5914109B9EAD33EB94B70965E3A /* Request.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 62DDE0C6C0039335077DBC2C1F47B298 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 79C040AFDDCE1BCBF6D8B5EB0B85887F; + remoteInfo = Alamofire; + }; + 8E255873C3650EE22CA9B2391FBFA873 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 53895CC196FD9229460242EA4460852F; + remoteInfo = SwiftyJSON; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 13BD16F528A9440A041D50A31B8D4A4A /* Pods-NoughtsAndCrosses-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-NoughtsAndCrosses-frameworks.sh"; sourceTree = ""; }; + 17C7C311169F3CAF970644274FB0787A /* SwiftyJSON-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SwiftyJSON-dummy.m"; sourceTree = ""; }; + 20608D49620C157D6026B74F348507BC /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + 21E5EF6BB7D195D5FA6C641B07B50D4D /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + 22E8F73147901B7F30D5AF9C3924364F /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; + 26C873080C03FCB4833BC2B3063E0862 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + 29CF31B29D3B759DCFB762B564F77BF2 /* Manager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Manager.swift; path = Source/Manager.swift; sourceTree = ""; }; + 2C149463BDDA1902FCCD3124FB80B243 /* Pods-NoughtsAndCrosses.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-NoughtsAndCrosses.release.xcconfig"; sourceTree = ""; }; + 3A94BF7B506F7BF44EF3A7FAC1726DF9 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = Alamofire.modulemap; sourceTree = ""; }; + 413FC5CAFF8CC5E69FEB7938D8EFA262 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + 460531AF3E2BDFB2651B8577F41665C6 /* Pods-NoughtsAndCrosses.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-NoughtsAndCrosses.debug.xcconfig"; sourceTree = ""; }; + 478D9882C4F32157C94CC7EA13C65478 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 492EA54BAA3CE9E46499A9F3BE390712 /* Pods-NoughtsAndCrosses-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-NoughtsAndCrosses-resources.sh"; sourceTree = ""; }; + 4BA00B7770CE5C0311E922DD7CA72265 /* Upload.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Upload.swift; path = Source/Upload.swift; sourceTree = ""; }; + 51D3931E976C0FF2B3CBFD590528F74E /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; + 582C0D56CD61146874DF0CEF602D1F08 /* Stream.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Stream.swift; path = Source/Stream.swift; sourceTree = ""; }; + 5C2D373B20FED4A7FAA1E5EC993B74FA /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Source/Error.swift; sourceTree = ""; }; + 6524314C6E13EF8F837E915AF4237778 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + 6AB7F7C2BBCF479B732091AEE1D3050B /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + 70A64FD6EA90FBA31DFA9101B0FF7901 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + 7B0642CA7ADA9040C70178E4A0B79042 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 7BD1D581B483AF8736F68B34656AEA1F /* SwiftyJSON.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = SwiftyJSON.modulemap; sourceTree = ""; }; + 80479C151B14A2E9D5DC6BEAF443061D /* Pods-NoughtsAndCrosses-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-NoughtsAndCrosses-dummy.m"; sourceTree = ""; }; + 813B1E8F489400673C23422C9FECCAB8 /* Download.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Download.swift; path = Source/Download.swift; sourceTree = ""; }; + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 9F70E2D6E5D7EFD0167F569F2DC7133E /* Pods-NoughtsAndCrosses-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-NoughtsAndCrosses-acknowledgements.markdown"; sourceTree = ""; }; + 9FF202EA510C267D614F17C0950E6395 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + A5FD22D43AF77B80233D382A1DFA6B8A /* Pods_NoughtsAndCrosses.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_NoughtsAndCrosses.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + AD9A31F66E534D997F30CBABE6CDCE82 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + B4F4199950B7842066816E50F7E23BF6 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + B7A0ABA5EA98C1A6396A4AD6090D7658 /* Pods-NoughtsAndCrosses-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-NoughtsAndCrosses-acknowledgements.plist"; sourceTree = ""; }; + BA5B8F6AE942BA3D7E8C0B8732349B67 /* SwiftyJSON-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftyJSON-umbrella.h"; sourceTree = ""; }; + BAE4A28E1CBA2C4B6D06B5029FAFD7D1 /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + CEC22C73C1608DFA5D5D78BDCB218219 /* 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; }; + CFBFF681209D4E5030FF4116EFD41362 /* SwiftyJSON.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwiftyJSON.swift; path = Source/SwiftyJSON.swift; sourceTree = ""; }; + D509E73B46BBAF5DFF3E6517F2940EDB /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + DC71BA52BA5094114A735CF801251599 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + DDFAF64DF73690F6AE7DECAC758CC1B7 /* Pods-NoughtsAndCrosses.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "sourcecode.module-map"; path = "Pods-NoughtsAndCrosses.modulemap"; sourceTree = ""; }; + DE99AF16AC7077B672DAE5DAD765B367 /* SwiftyJSON.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftyJSON.xcconfig; sourceTree = ""; }; + DE9B5EA6A4147AAD3A5F1E7F902EE31C /* Pods-NoughtsAndCrosses-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-NoughtsAndCrosses-umbrella.h"; sourceTree = ""; }; + E395F6EB3479426D662CA416A2FE6174 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + E5E9972363A8ED9783531DD4DB70911B /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + E8202EA65D7F9777D78833FBE8F42BF1 /* SwiftyJSON-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftyJSON-prefix.pch"; sourceTree = ""; }; + EDE7F5914109B9EAD33EB94B70965E3A /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + FC61F6341066AC51394924B7EA2CF193 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + B1729F851F648EC60EE93CDB3C8BAEAD /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 91C09AC2A52ED69A27C8D923139A006F /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D1E5164998EECD79DEF1EACE7AA7EE39 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 0958E439A0E82F238189BEC6FC84242A /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E42CE6F9B7E1AEBCA23EC91DF206BEFF /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 4FBE18CD56428D3DD6979ABB59F9D87E /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 0693A35739DC3BB2B85E2314AB0D7E5A /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + 5C98901BFA3B820E7B5D0C076C963BBF /* Pods-NoughtsAndCrosses */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + 3DCAB2B7CDE207B3958B6CB957FCC758 /* iOS */ = { + isa = PBXGroup; + children = ( + CEC22C73C1608DFA5D5D78BDCB218219 /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 453569F1A1F9AC3BBA09D80C82226E49 /* Support Files */ = { + isa = PBXGroup; + children = ( + 3A94BF7B506F7BF44EF3A7FAC1726DF9 /* Alamofire.modulemap */, + E5E9972363A8ED9783531DD4DB70911B /* Alamofire.xcconfig */, + 9FF202EA510C267D614F17C0950E6395 /* Alamofire-dummy.m */, + B4F4199950B7842066816E50F7E23BF6 /* Alamofire-prefix.pch */, + 6AB7F7C2BBCF479B732091AEE1D3050B /* Alamofire-umbrella.h */, + E395F6EB3479426D662CA416A2FE6174 /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + 59A7347CAA7298EC422D751CD30C9667 /* Alamofire */ = { + isa = PBXGroup; + children = ( + 21E5EF6BB7D195D5FA6C641B07B50D4D /* Alamofire.swift */, + 813B1E8F489400673C23422C9FECCAB8 /* Download.swift */, + 5C2D373B20FED4A7FAA1E5EC993B74FA /* Error.swift */, + 29CF31B29D3B759DCFB762B564F77BF2 /* Manager.swift */, + 413FC5CAFF8CC5E69FEB7938D8EFA262 /* MultipartFormData.swift */, + 51D3931E976C0FF2B3CBFD590528F74E /* NetworkReachabilityManager.swift */, + 20608D49620C157D6026B74F348507BC /* Notifications.swift */, + 6524314C6E13EF8F837E915AF4237778 /* ParameterEncoding.swift */, + EDE7F5914109B9EAD33EB94B70965E3A /* Request.swift */, + 26C873080C03FCB4833BC2B3063E0862 /* Response.swift */, + D509E73B46BBAF5DFF3E6517F2940EDB /* ResponseSerialization.swift */, + BAE4A28E1CBA2C4B6D06B5029FAFD7D1 /* Result.swift */, + 70A64FD6EA90FBA31DFA9101B0FF7901 /* ServerTrustPolicy.swift */, + 582C0D56CD61146874DF0CEF602D1F08 /* Stream.swift */, + 22E8F73147901B7F30D5AF9C3924364F /* Timeline.swift */, + 4BA00B7770CE5C0311E922DD7CA72265 /* Upload.swift */, + DC71BA52BA5094114A735CF801251599 /* Validation.swift */, + 453569F1A1F9AC3BBA09D80C82226E49 /* Support Files */, + ); + path = Alamofire; + sourceTree = ""; + }; + 5C98901BFA3B820E7B5D0C076C963BBF /* Pods-NoughtsAndCrosses */ = { + isa = PBXGroup; + children = ( + 478D9882C4F32157C94CC7EA13C65478 /* Info.plist */, + DDFAF64DF73690F6AE7DECAC758CC1B7 /* Pods-NoughtsAndCrosses.modulemap */, + 9F70E2D6E5D7EFD0167F569F2DC7133E /* Pods-NoughtsAndCrosses-acknowledgements.markdown */, + B7A0ABA5EA98C1A6396A4AD6090D7658 /* Pods-NoughtsAndCrosses-acknowledgements.plist */, + 80479C151B14A2E9D5DC6BEAF443061D /* Pods-NoughtsAndCrosses-dummy.m */, + 13BD16F528A9440A041D50A31B8D4A4A /* Pods-NoughtsAndCrosses-frameworks.sh */, + 492EA54BAA3CE9E46499A9F3BE390712 /* Pods-NoughtsAndCrosses-resources.sh */, + DE9B5EA6A4147AAD3A5F1E7F902EE31C /* Pods-NoughtsAndCrosses-umbrella.h */, + 460531AF3E2BDFB2651B8577F41665C6 /* Pods-NoughtsAndCrosses.debug.xcconfig */, + 2C149463BDDA1902FCCD3124FB80B243 /* Pods-NoughtsAndCrosses.release.xcconfig */, + ); + name = "Pods-NoughtsAndCrosses"; + path = "Target Support Files/Pods-NoughtsAndCrosses"; + sourceTree = ""; + }; + 7DB346D0F39D3F0E887471402A8071AB = { + isa = PBXGroup; + children = ( + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, + BC3CA7F9E30CC8F7E2DD044DD34432FC /* Frameworks */, + 86D8AA6B1E9A5BBF1AE91BD6451D7A84 /* Pods */, + 88061F5EBF2650ECF97251C2FEDCDA78 /* Products */, + 0693A35739DC3BB2B85E2314AB0D7E5A /* Targets Support Files */, + ); + sourceTree = ""; + }; + 86D8AA6B1E9A5BBF1AE91BD6451D7A84 /* Pods */ = { + isa = PBXGroup; + children = ( + 59A7347CAA7298EC422D751CD30C9667 /* Alamofire */, + C9BFD22DAF08BC7D056B72F0924E9AFE /* SwiftyJSON */, + ); + name = Pods; + sourceTree = ""; + }; + 88061F5EBF2650ECF97251C2FEDCDA78 /* Products */ = { + isa = PBXGroup; + children = ( + AD9A31F66E534D997F30CBABE6CDCE82 /* Alamofire.framework */, + A5FD22D43AF77B80233D382A1DFA6B8A /* Pods_NoughtsAndCrosses.framework */, + 7B0642CA7ADA9040C70178E4A0B79042 /* SwiftyJSON.framework */, + ); + name = Products; + sourceTree = ""; + }; + BC3CA7F9E30CC8F7E2DD044DD34432FC /* Frameworks */ = { + isa = PBXGroup; + children = ( + 3DCAB2B7CDE207B3958B6CB957FCC758 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + C9BFD22DAF08BC7D056B72F0924E9AFE /* SwiftyJSON */ = { + isa = PBXGroup; + children = ( + CFBFF681209D4E5030FF4116EFD41362 /* SwiftyJSON.swift */, + F847E694BA44D7153C3E16A02FE345D4 /* Support Files */, + ); + path = SwiftyJSON; + sourceTree = ""; + }; + F847E694BA44D7153C3E16A02FE345D4 /* Support Files */ = { + isa = PBXGroup; + children = ( + FC61F6341066AC51394924B7EA2CF193 /* Info.plist */, + 7BD1D581B483AF8736F68B34656AEA1F /* SwiftyJSON.modulemap */, + DE99AF16AC7077B672DAE5DAD765B367 /* SwiftyJSON.xcconfig */, + 17C7C311169F3CAF970644274FB0787A /* SwiftyJSON-dummy.m */, + E8202EA65D7F9777D78833FBE8F42BF1 /* SwiftyJSON-prefix.pch */, + BA5B8F6AE942BA3D7E8C0B8732349B67 /* SwiftyJSON-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/SwiftyJSON"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 6C242DFA5C1819BCCD71C488129AA31A /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 801FBB0AAB759009AB8E2875FCB39DBE /* SwiftyJSON-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CAB3C371C9187F9E337C8BA4000C28D2 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + B90A8CBDE5F07FD959E3821410626D06 /* Pods-NoughtsAndCrosses-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EFDF3B631BBB965A372347705CA14854 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 9469DF81ECB494E84675969B5E13374C /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 03821FBFC539544504502700E8108A2D /* Pods-NoughtsAndCrosses */ = { + isa = PBXNativeTarget; + buildConfigurationList = FC912095A9E2910530A201D771BEDF17 /* Build configuration list for PBXNativeTarget "Pods-NoughtsAndCrosses" */; + buildPhases = ( + C509616D5E19772E208CD4FDEE14DBE9 /* Sources */, + E42CE6F9B7E1AEBCA23EC91DF206BEFF /* Frameworks */, + CAB3C371C9187F9E337C8BA4000C28D2 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + 61F0139618B277452755C9B8C8B8D0A5 /* PBXTargetDependency */, + 1CC5439FF924118A46434E2AF2BF626F /* PBXTargetDependency */, + ); + name = "Pods-NoughtsAndCrosses"; + productName = "Pods-NoughtsAndCrosses"; + productReference = A5FD22D43AF77B80233D382A1DFA6B8A /* Pods_NoughtsAndCrosses.framework */; + productType = "com.apple.product-type.framework"; + }; + 53895CC196FD9229460242EA4460852F /* SwiftyJSON */ = { + isa = PBXNativeTarget; + buildConfigurationList = 489F66555627B2C046A0E719C1F1B540 /* Build configuration list for PBXNativeTarget "SwiftyJSON" */; + buildPhases = ( + 773AF86FE7D6C718FB43F142773E2856 /* Sources */, + D1E5164998EECD79DEF1EACE7AA7EE39 /* Frameworks */, + 6C242DFA5C1819BCCD71C488129AA31A /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SwiftyJSON; + productName = SwiftyJSON; + productReference = 7B0642CA7ADA9040C70178E4A0B79042 /* SwiftyJSON.framework */; + productType = "com.apple.product-type.framework"; + }; + 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = 3CFB42910790CF0BDBCCEBAACD6B9367 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + 95CC2C7E06DC188A05DAAEE9CAA555A3 /* Sources */, + B1729F851F648EC60EE93CDB3C8BAEAD /* Frameworks */, + EFDF3B631BBB965A372347705CA14854 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Alamofire; + productName = Alamofire; + productReference = AD9A31F66E534D997F30CBABE6CDCE82 /* Alamofire.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 = 88061F5EBF2650ECF97251C2FEDCDA78 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */, + 03821FBFC539544504502700E8108A2D /* Pods-NoughtsAndCrosses */, + 53895CC196FD9229460242EA4460852F /* SwiftyJSON */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + 773AF86FE7D6C718FB43F142773E2856 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 9F113FEFF1016C766C59FF0C5D06FB0D /* SwiftyJSON-dummy.m in Sources */, + A31CB1F4783A8042B97B1D6ED775DAA8 /* SwiftyJSON.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 95CC2C7E06DC188A05DAAEE9CAA555A3 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ADF19C953CE2A7D0B72EC93A81FCCC26 /* Alamofire-dummy.m in Sources */, + 8EB11202167FCDDF1257AAAB1D1FB244 /* Alamofire.swift in Sources */, + 5CB05FBCB32D21E194B5ECF680CB6AE0 /* Download.swift in Sources */, + 095406039B4D371E48D08B38A2975AC8 /* Error.swift in Sources */, + 4081EA628AF0B73AC51FFB9D7AB3B89E /* Manager.swift in Sources */, + C7B6DD7C0456C50289A2C381DFE9FA3F /* MultipartFormData.swift in Sources */, + 34CCDCA848A701466256BC2927DA8856 /* NetworkReachabilityManager.swift in Sources */, + BE41196F6A3903E59C3306FE3F8B43FE /* Notifications.swift in Sources */, + C0DB70AB368765DC64BFB5FEA75E0696 /* ParameterEncoding.swift in Sources */, + EFE92E8D3813DD26E78E93EEAF6D7E7E /* Request.swift in Sources */, + 62E8346F03C03E7F4D631361F325689E /* Response.swift in Sources */, + 3EA8F215C9C1432D74E5CCA4834AA8C0 /* ResponseSerialization.swift in Sources */, + AA314156AC500125F4078EE968DB14C6 /* Result.swift in Sources */, + 7B48852C4D848FA2DA416A98F6425869 /* ServerTrustPolicy.swift in Sources */, + AE4CF87C02C042DF13ED5B21C4FDC1E0 /* Stream.swift in Sources */, + 16102E4E35FAA0FC4161282FECE56469 /* Timeline.swift in Sources */, + 5BC19E6E0F199276003F0AF96838BCE5 /* Upload.swift in Sources */, + 2D3405986FC586FA6C0A5E0B6BA7E64E /* Validation.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C509616D5E19772E208CD4FDEE14DBE9 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + B6DD6E4F2AC743E86AE312FFA8CC1604 /* Pods-NoughtsAndCrosses-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 1CC5439FF924118A46434E2AF2BF626F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = SwiftyJSON; + target = 53895CC196FD9229460242EA4460852F /* SwiftyJSON */; + targetProxy = 8E255873C3650EE22CA9B2391FBFA873 /* PBXContainerItemProxy */; + }; + 61F0139618B277452755C9B8C8B8D0A5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 79C040AFDDCE1BCBF6D8B5EB0B85887F /* Alamofire */; + targetProxy = 62DDE0C6C0039335077DBC2C1F47B298 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 32AD5F8918CA8B349E4671410FA624C9 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E5E9972363A8ED9783531DD4DB70911B /* 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; + }; + 45A7AAABFB08701C5BEF90E655CEBC99 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DE99AF16AC7077B672DAE5DAD765B367 /* SwiftyJSON.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/SwiftyJSON/SwiftyJSON-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SwiftyJSON/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/SwiftyJSON/SwiftyJSON.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = SwiftyJSON; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 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; + }; + 6951B963728EA1BEF39C9DABA5E0E25D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 2C149463BDDA1902FCCD3124FB80B243 /* Pods-NoughtsAndCrosses.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-NoughtsAndCrosses/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-NoughtsAndCrosses/Pods-NoughtsAndCrosses.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_NoughtsAndCrosses; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 6DF834E0191AD9323AD0114B113D90F9 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 460531AF3E2BDFB2651B8577F41665C6 /* Pods-NoughtsAndCrosses.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-NoughtsAndCrosses/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-NoughtsAndCrosses/Pods-NoughtsAndCrosses.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_NoughtsAndCrosses; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 75218111E718FACE36F771E8ABECDB62 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E5E9972363A8ED9783531DD4DB70911B /* 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; + }; + 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; + }; + B78EB37DCBD0BF1770D4865695A9B7FE /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DE99AF16AC7077B672DAE5DAD765B367 /* SwiftyJSON.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/SwiftyJSON/SwiftyJSON-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SwiftyJSON/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/SwiftyJSON/SwiftyJSON.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = SwiftyJSON; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 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; + }; + 489F66555627B2C046A0E719C1F1B540 /* Build configuration list for PBXNativeTarget "SwiftyJSON" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 45A7AAABFB08701C5BEF90E655CEBC99 /* Debug */, + B78EB37DCBD0BF1770D4865695A9B7FE /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + FC912095A9E2910530A201D771BEDF17 /* Build configuration list for PBXNativeTarget "Pods-NoughtsAndCrosses" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6DF834E0191AD9323AD0114B113D90F9 /* Debug */, + 6951B963728EA1BEF39C9DABA5E0E25D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; +} diff --git a/NoughtsAndCrosses/Pods/Pods.xcodeproj/xcuserdata/Katz.xcuserdatad/xcschemes/Alamofire.xcscheme b/NoughtsAndCrosses/Pods/Pods.xcodeproj/xcuserdata/Katz.xcuserdatad/xcschemes/Alamofire.xcscheme new file mode 100644 index 0000000..c0e3115 --- /dev/null +++ b/NoughtsAndCrosses/Pods/Pods.xcodeproj/xcuserdata/Katz.xcuserdatad/xcschemes/Alamofire.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/NoughtsAndCrosses/Pods/Pods.xcodeproj/xcuserdata/Katz.xcuserdatad/xcschemes/Pods-NoughtsAndCrosses.xcscheme b/NoughtsAndCrosses/Pods/Pods.xcodeproj/xcuserdata/Katz.xcuserdatad/xcschemes/Pods-NoughtsAndCrosses.xcscheme new file mode 100644 index 0000000..a0ec120 --- /dev/null +++ b/NoughtsAndCrosses/Pods/Pods.xcodeproj/xcuserdata/Katz.xcuserdatad/xcschemes/Pods-NoughtsAndCrosses.xcscheme @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/NoughtsAndCrosses/Pods/Pods.xcodeproj/xcuserdata/Katz.xcuserdatad/xcschemes/SwiftyJSON.xcscheme b/NoughtsAndCrosses/Pods/Pods.xcodeproj/xcuserdata/Katz.xcuserdatad/xcschemes/SwiftyJSON.xcscheme new file mode 100644 index 0000000..98dd31a --- /dev/null +++ b/NoughtsAndCrosses/Pods/Pods.xcodeproj/xcuserdata/Katz.xcuserdatad/xcschemes/SwiftyJSON.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/NoughtsAndCrosses/Pods/Pods.xcodeproj/xcuserdata/Katz.xcuserdatad/xcschemes/xcschememanagement.plist b/NoughtsAndCrosses/Pods/Pods.xcodeproj/xcuserdata/Katz.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..7141b6e --- /dev/null +++ b/NoughtsAndCrosses/Pods/Pods.xcodeproj/xcuserdata/Katz.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,42 @@ + + + + + SchemeUserState + + Alamofire.xcscheme + + isShown + + + Pods-NoughtsAndCrosses.xcscheme + + isShown + + + SwiftyJSON.xcscheme + + isShown + + + + SuppressBuildableAutocreation + + 03821FBFC539544504502700E8108A2D + + primary + + + 53895CC196FD9229460242EA4460852F + + primary + + + 79C040AFDDCE1BCBF6D8B5EB0B85887F + + primary + + + + + diff --git a/NoughtsAndCrosses/Pods/SwiftyJSON/LICENSE b/NoughtsAndCrosses/Pods/SwiftyJSON/LICENSE new file mode 100644 index 0000000..a7af196 --- /dev/null +++ b/NoughtsAndCrosses/Pods/SwiftyJSON/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Ruoyu Fu + +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/NoughtsAndCrosses/Pods/SwiftyJSON/README.md b/NoughtsAndCrosses/Pods/SwiftyJSON/README.md new file mode 100644 index 0000000..75d5185 --- /dev/null +++ b/NoughtsAndCrosses/Pods/SwiftyJSON/README.md @@ -0,0 +1,392 @@ +#SwiftyJSON [中文介绍](http://tangplin.github.io/swiftyjson/) + +[![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) + +SwiftyJSON makes it easy to deal with JSON data in Swift. + +1. [Why is the typical JSON handling in Swift NOT good](#why-is-the-typical-json-handling-in-swift-not-good) +1. [Requirements](#requirements) +1. [Integration](#integration) +1. [Usage](#usage) + - [Initialization](#initialization) + - [Subscript](#subscript) + - [Loop](#loop) + - [Error](#error) + - [Optional getter](#optional-getter) + - [Non-optional getter](#non-optional-getter) + - [Setter](#setter) + - [Raw object](#raw-object) + - [Literal convertibles](#literal-convertibles) +1. [Work with Alamofire](#work-with-alamofire) + +##Why is the typical JSON handling in Swift NOT good? +Swift is very strict about types. But although explicit typing is good for saving us from mistakes, it becomes painful when dealing with JSON and other areas that are, by nature, implicit about types. + +Take the Twitter API for example. Say we want to retrieve a user's "name" value of some tweet in Swift (according to Twitter's API https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline). + +The code would look like this: + +```swift + +if let statusesArray = try? NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [[String: AnyObject]], + let user = statusesArray[0]["user"] as? [String: AnyObject], + let username = user["name"] as? String { + // Finally we got the username +} + +``` + +It's not good. + +Even if we use optional chaining, it would be messy: + +```swift + +if let JSONObject = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [[String: AnyObject]], + let username = (JSONObject[0]["user"] as? [String: AnyObject])?["name"] as? String { + // There's our username +} + +``` +An unreadable mess--for something that should really be simple! + +With SwiftyJSON all you have to do is: + +```swift + +let json = JSON(data: dataFromNetworking) +if let userName = json[0]["user"]["name"].string { + //Now you got your value +} + +``` + +And don't worry about the Optional Wrapping thing. It's done for you automatically. + +```swift + +let json = JSON(data: dataFromNetworking) +if let userName = json[999999]["wrong_key"]["wrong_name"].string { + //Calm down, take it easy, the ".string" property still produces the correct Optional String type with safety +} else { + //Print the error + print(json[999999]["wrong_key"]["wrong_name"]) +} + +``` + +## Requirements + +- iOS 7.0+ / OS X 10.9+ +- Xcode 7 + +##Integration + +####CocoaPods (iOS 8+, OS X 10.9+) +You can use [Cocoapods](http://cocoapods.org/) to install `SwiftyJSON`by adding it to your `Podfile`: +```ruby +platform :ios, '8.0' +use_frameworks! + +target 'MyApp' do + pod 'SwiftyJSON', :git => 'https://github.com/SwiftyJSON/SwiftyJSON.git' +end +``` +Note that this requires CocoaPods version 36, and your iOS deployment target to be at least 8.0: + +####Carthage (iOS 8+, OS X 10.9+) +You can use [Carthage](https://github.com/Carthage/Carthage) to install `SwiftyJSON` by adding it to your `Cartfile`: +``` +github "SwiftyJSON/SwiftyJSON" +``` + +####Swift Package Manager +You can use [The Swift Package Manager](https://swift.org/package-manager) to install `SwiftyJSON` by adding the proper description to your `Package.swift` file: +```swift +import PackageDescription + +let package = Package( + name: "YOUR_PROJECT_NAME", + targets: [], + dependencies: [ + .Package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", versions: "2.3.3" ..< Version.max) + ] +) +``` + +Note that the [Swift Package Manager](https://swift.org/package-manager) is still in early design and development, for more infomation checkout its [GitHub Page](https://github.com/apple/swift-package-manager) + +####Manually (iOS 7+, OS X 10.9+) + +To use this library in your project manually you may: + +1. for Projects, just drag SwiftyJSON.swift to the project tree +2. for Workspaces, include the whole SwiftyJSON.xcodeproj + +## Usage + +####Initialization +```swift +import SwiftyJSON +``` +```swift +let json = JSON(data: dataFromNetworking) +``` +```swift +let json = JSON(jsonObject) +``` +```swift +if let dataFromString = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { + let json = JSON(data: dataFromString) +} +``` + +####Subscript +```swift +//Getting a double from a JSON Array +let name = json[0].double +``` +```swift +//Getting a string from a JSON Dictionary +let name = json["name"].stringValue +``` +```swift +//Getting a string using a path to the element +let path = [1,"list",2,"name"] +let name = json[path].string +//Just the same +let name = json[1]["list"][2]["name"].string +//Alternatively +let name = json[1,"list",2,"name"].string +``` +```swift +//With a hard way +let name = json[].string +``` +```swift +//With a custom way +let keys:[SubscriptType] = [1,"list",2,"name"] +let name = json[keys].string +``` +####Loop +```swift +//If json is .Dictionary +for (key,subJson):(String, JSON) in json { + //Do something you want +} +``` +*The first element is always a String, even if the JSON is an Array* +```swift +//If json is .Array +//The `index` is 0.. = json["list"].arrayValue +``` +```swift +//If not a Dictionary or nil, return [:] +let user: Dictionary = json["user"].dictionaryValue +``` + +####Setter +```swift +json["name"] = JSON("new-name") +json[0] = JSON(1) +``` +```swift +json["id"].int = 1234567890 +json["coordinate"].double = 8766.766 +json["name"].string = "Jack" +json.arrayObject = [1,2,3,4] +json.dictionary = ["name":"Jack", "age":25] +``` + +####Raw object +```swift +let jsonObject: AnyObject = json.object +``` +```swift +if let jsonObject: AnyObject = json.rawValue +``` +```swift +//convert the JSON to raw NSData +if let data = json.rawData() { + //Do something you want +} +``` +```swift +//convert the JSON to a raw String +if let string = json.rawString() { + //Do something you want +} +``` +####Existance +```swift +//shows you whether value specified in JSON or not +if json["name"].isExists() +``` + +####Literal convertibles +For more info about literal convertibles: [Swift Literal Convertibles](http://nshipster.com/swift-literal-convertible/) +```swift +//StringLiteralConvertible +let json: JSON = "I'm a json" +``` +```swift +//IntegerLiteralConvertible +let json: JSON = 12345 +``` +```swift +//BooleanLiteralConvertible +let json: JSON = true +``` +```swift +//FloatLiteralConvertible +let json: JSON = 2.8765 +``` +```swift +//DictionaryLiteralConvertible +let json: JSON = ["I":"am", "a":"json"] +``` +```swift +//ArrayLiteralConvertible +let json: JSON = ["I", "am", "a", "json"] +``` +```swift +//NilLiteralConvertible +let json: JSON = nil +``` +```swift +//With subscript in array +var json: JSON = [1,2,3] +json[0] = 100 +json[1] = 200 +json[2] = 300 +json[999] = 300 //Don't worry, nothing will happen +``` +```swift +//With subscript in dictionary +var json: JSON = ["name": "Jack", "age": 25] +json["name"] = "Mike" +json["age"] = "25" //It's OK to set String +json["address"] = "L.A." // Add the "address": "L.A." in json +``` +```swift +//Array & Dictionary +var json: JSON = ["name": "Jack", "age": 25, "list": ["a", "b", "c", ["what": "this"]]] +json["list"][3]["what"] = "that" +json["list",3,"what"] = "that" +let path = ["list",3,"what"] +json[path] = "that" +``` +##Work with Alamofire + +SwiftyJSON nicely wraps the result of the Alamofire JSON response handler: +```swift +Alamofire.request(.GET, url).validate().responseJSON { response in + switch response.result { + case .Success: + if let value = response.result.value { + let json = JSON(value) + print("JSON: \(json)") + } + case .Failure(let error): + print(error) + } +} +``` diff --git a/NoughtsAndCrosses/Pods/SwiftyJSON/Source/SwiftyJSON.swift b/NoughtsAndCrosses/Pods/SwiftyJSON/Source/SwiftyJSON.swift new file mode 100644 index 0000000..8a5b5d6 --- /dev/null +++ b/NoughtsAndCrosses/Pods/SwiftyJSON/Source/SwiftyJSON.swift @@ -0,0 +1,1378 @@ +// SwiftyJSON.swift +// +// Copyright (c) 2014 Ruoyu Fu, Pinglin Tang +// +// 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: - Error + +///Error domain +public let ErrorDomain: String = "SwiftyJSONErrorDomain" + +///Error code +public let ErrorUnsupportedType: Int = 999 +public let ErrorIndexOutOfBounds: Int = 900 +public let ErrorWrongType: Int = 901 +public let ErrorNotExist: Int = 500 +public let ErrorInvalidJSON: Int = 490 + +// MARK: - JSON Type + +/** +JSON's type definitions. + +See http://www.json.org +*/ +public enum Type :Int{ + + case Number + case String + case Bool + case Array + case Dictionary + case Null + case Unknown +} + +// MARK: - JSON Base + +public struct JSON { + + /** + Creates a JSON using the data. + + - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary + - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. + - parameter error: error The NSErrorPointer used to return the error. `nil` by default. + + - returns: The created JSON + */ + public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) { + do { + let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt) + self.init(object) + } catch let aError as NSError { + if error != nil { + error.memory = aError + } + self.init(NSNull()) + } + } + + /** + Create a JSON from JSON string + - parameter string: Normal json string like '{"a":"b"}' + + - returns: The created JSON + */ + public static func parse(string:String) -> JSON { + return string.dataUsingEncoding(NSUTF8StringEncoding) + .flatMap({JSON(data: $0)}) ?? JSON(NSNull()) + } + + /** + Creates a JSON using the object. + + - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. + + - returns: The created JSON + */ + public init(_ object: AnyObject) { + self.object = object + } + + /** + Creates a JSON from a [JSON] + + - parameter jsonArray: A Swift array of JSON objects + + - returns: The created JSON + */ + public init(_ jsonArray:[JSON]) { + self.init(jsonArray.map { $0.object }) + } + + /** + Creates a JSON from a [String: JSON] + + - parameter jsonDictionary: A Swift dictionary of JSON objects + + - returns: The created JSON + */ + public init(_ jsonDictionary:[String: JSON]) { + var dictionary = [String: AnyObject](minimumCapacity: jsonDictionary.count) + for (key, json) in jsonDictionary { + dictionary[key] = json.object + } + self.init(dictionary) + } + + /// Private object + private var rawArray: [AnyObject] = [] + private var rawDictionary: [String : AnyObject] = [:] + private var rawString: String = "" + private var rawNumber: NSNumber = 0 + private var rawNull: NSNull = NSNull() + /// Private type + private var _type: Type = .Null + /// prviate error + private var _error: NSError? = nil + + /// Object in JSON + public var object: AnyObject { + get { + switch self.type { + case .Array: + return self.rawArray + case .Dictionary: + return self.rawDictionary + case .String: + return self.rawString + case .Number: + return self.rawNumber + case .Bool: + return self.rawNumber + default: + return self.rawNull + } + } + set { + _error = nil + switch newValue { + case let number as NSNumber: + if number.isBool { + _type = .Bool + } else { + _type = .Number + } + self.rawNumber = number + case let string as String: + _type = .String + self.rawString = string + case _ as NSNull: + _type = .Null + case let array as [AnyObject]: + _type = .Array + self.rawArray = array + case let dictionary as [String : AnyObject]: + _type = .Dictionary + self.rawDictionary = dictionary + default: + _type = .Unknown + _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) + } + } + } + + /// json type + public var type: Type { get { return _type } } + + /// Error in JSON + public var error: NSError? { get { return self._error } } + + /// The static null json + @available(*, unavailable, renamed="null") + public static var nullJSON: JSON { get { return null } } + public static var null: JSON { get { return JSON(NSNull()) } } +} + +// MARK: - CollectionType, SequenceType, Indexable +extension JSON : Swift.CollectionType, Swift.SequenceType, Swift.Indexable { + + public typealias Generator = JSONGenerator + + public typealias Index = JSONIndex + + public var startIndex: JSON.Index { + switch self.type { + case .Array: + return JSONIndex(arrayIndex: self.rawArray.startIndex) + case .Dictionary: + return JSONIndex(dictionaryIndex: self.rawDictionary.startIndex) + default: + return JSONIndex() + } + } + + public var endIndex: JSON.Index { + switch self.type { + case .Array: + return JSONIndex(arrayIndex: self.rawArray.endIndex) + case .Dictionary: + return JSONIndex(dictionaryIndex: self.rawDictionary.endIndex) + default: + return JSONIndex() + } + } + + public subscript (position: JSON.Index) -> JSON.Generator.Element { + switch self.type { + case .Array: + return (String(position.arrayIndex), JSON(self.rawArray[position.arrayIndex!])) + case .Dictionary: + let (key, value) = self.rawDictionary[position.dictionaryIndex!] + return (key, JSON(value)) + default: + return ("", JSON.null) + } + } + + /// If `type` is `.Array` or `.Dictionary`, return `array.isEmpty` or `dictonary.isEmpty` otherwise return `true`. + public var isEmpty: Bool { + get { + switch self.type { + case .Array: + return self.rawArray.isEmpty + case .Dictionary: + return self.rawDictionary.isEmpty + default: + return true + } + } + } + + /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`. + public var count: Int { + switch self.type { + case .Array: + return self.rawArray.count + case .Dictionary: + return self.rawDictionary.count + default: + return 0 + } + } + + public func underestimateCount() -> Int { + switch self.type { + case .Array: + return self.rawArray.underestimateCount() + case .Dictionary: + return self.rawDictionary.underestimateCount() + default: + return 0 + } + } + + /** + If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty. + + - returns: Return a *generator* over the elements of JSON. + */ + public func generate() -> JSON.Generator { + return JSON.Generator(self) + } +} + +public struct JSONIndex: ForwardIndexType, _Incrementable, Equatable, Comparable { + + let arrayIndex: Int? + let dictionaryIndex: DictionaryIndex? + + let type: Type + + init(){ + self.arrayIndex = nil + self.dictionaryIndex = nil + self.type = .Unknown + } + + init(arrayIndex: Int) { + self.arrayIndex = arrayIndex + self.dictionaryIndex = nil + self.type = .Array + } + + init(dictionaryIndex: DictionaryIndex) { + self.arrayIndex = nil + self.dictionaryIndex = dictionaryIndex + self.type = .Dictionary + } + + public func successor() -> JSONIndex { + switch self.type { + case .Array: + return JSONIndex(arrayIndex: self.arrayIndex!.successor()) + case .Dictionary: + return JSONIndex(dictionaryIndex: self.dictionaryIndex!.successor()) + default: + return JSONIndex() + } + } +} + +public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool { + switch (lhs.type, rhs.type) { + case (.Array, .Array): + return lhs.arrayIndex == rhs.arrayIndex + case (.Dictionary, .Dictionary): + return lhs.dictionaryIndex == rhs.dictionaryIndex + default: + return false + } +} + +public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool { + switch (lhs.type, rhs.type) { + case (.Array, .Array): + return lhs.arrayIndex < rhs.arrayIndex + case (.Dictionary, .Dictionary): + return lhs.dictionaryIndex < rhs.dictionaryIndex + default: + return false + } +} + +public func <=(lhs: JSONIndex, rhs: JSONIndex) -> Bool { + switch (lhs.type, rhs.type) { + case (.Array, .Array): + return lhs.arrayIndex <= rhs.arrayIndex + case (.Dictionary, .Dictionary): + return lhs.dictionaryIndex <= rhs.dictionaryIndex + default: + return false + } +} + +public func >=(lhs: JSONIndex, rhs: JSONIndex) -> Bool { + switch (lhs.type, rhs.type) { + case (.Array, .Array): + return lhs.arrayIndex >= rhs.arrayIndex + case (.Dictionary, .Dictionary): + return lhs.dictionaryIndex >= rhs.dictionaryIndex + default: + return false + } +} + +public func >(lhs: JSONIndex, rhs: JSONIndex) -> Bool { + switch (lhs.type, rhs.type) { + case (.Array, .Array): + return lhs.arrayIndex > rhs.arrayIndex + case (.Dictionary, .Dictionary): + return lhs.dictionaryIndex > rhs.dictionaryIndex + default: + return false + } +} + +public struct JSONGenerator : GeneratorType { + + public typealias Element = (String, JSON) + + private let type: Type + private var dictionayGenerate: DictionaryGenerator? + private var arrayGenerate: IndexingGenerator<[AnyObject]>? + private var arrayIndex: Int = 0 + + init(_ json: JSON) { + self.type = json.type + if type == .Array { + self.arrayGenerate = json.rawArray.generate() + }else { + self.dictionayGenerate = json.rawDictionary.generate() + } + } + + public mutating func next() -> JSONGenerator.Element? { + switch self.type { + case .Array: + if let o = self.arrayGenerate?.next() { + let i = self.arrayIndex + self.arrayIndex += 1 + return (String(i), JSON(o)) + } else { + return nil + } + case .Dictionary: + if let (k, v): (String, AnyObject) = self.dictionayGenerate?.next() { + return (k, JSON(v)) + } else { + return nil + } + default: + return nil + } + } +} + +// MARK: - Subscript + +/** +* To mark both String and Int can be used in subscript. +*/ +public enum JSONKey { + case Index(Int) + case Key(String) +} + +public protocol JSONSubscriptType { + var jsonKey:JSONKey { get } +} + +extension Int: JSONSubscriptType { + public var jsonKey:JSONKey { + return JSONKey.Index(self) + } +} + +extension String: JSONSubscriptType { + public var jsonKey:JSONKey { + return JSONKey.Key(self) + } +} + +extension JSON { + + /// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error. + private subscript(index index: Int) -> JSON { + get { + if self.type != .Array { + var r = JSON.null + r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) + return r + } else if index >= 0 && index < self.rawArray.count { + return JSON(self.rawArray[index]) + } else { + var r = JSON.null + r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) + return r + } + } + set { + if self.type == .Array { + if self.rawArray.count > index && newValue.error == nil { + self.rawArray[index] = newValue.object + } + } + } + } + + /// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. + private subscript(key key: String) -> JSON { + get { + var r = JSON.null + if self.type == .Dictionary { + if let o = self.rawDictionary[key] { + r = JSON(o) + } else { + r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) + } + } else { + r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) + } + return r + } + set { + if self.type == .Dictionary && newValue.error == nil { + self.rawDictionary[key] = newValue.object + } + } + } + + /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. + private subscript(sub sub: JSONSubscriptType) -> JSON { + get { + switch sub.jsonKey { + case .Index(let index): return self[index: index] + case .Key(let key): return self[key: key] + } + } + set { + switch sub.jsonKey { + case .Index(let index): self[index: index] = newValue + case .Key(let key): self[key: key] = newValue + } + } + } + + /** + Find a json in the complex data structuresby using the Int/String's array. + + - parameter path: The target json's path. Example: + + let json = JSON[data] + let path = [9,"list","person","name"] + let name = json[path] + + The same as: let name = json[9]["list"]["person"]["name"] + + - returns: Return a json found by the path or a null json with error + */ + public subscript(path: [JSONSubscriptType]) -> JSON { + get { + return path.reduce(self) { $0[sub: $1] } + } + set { + switch path.count { + case 0: + return + case 1: + self[sub:path[0]].object = newValue.object + default: + var aPath = path; aPath.removeAtIndex(0) + var nextJSON = self[sub: path[0]] + nextJSON[aPath] = newValue + self[sub: path[0]] = nextJSON + } + } + } + + /** + Find a json in the complex data structures by using the Int/String's array. + + - parameter path: The target json's path. Example: + + let name = json[9,"list","person","name"] + + The same as: let name = json[9]["list"]["person"]["name"] + + - returns: Return a json found by the path or a null json with error + */ + public subscript(path: JSONSubscriptType...) -> JSON { + get { + return self[path] + } + set { + self[path] = newValue + } + } +} + +// MARK: - LiteralConvertible + +extension JSON: Swift.StringLiteralConvertible { + + public init(stringLiteral value: StringLiteralType) { + self.init(value) + } + + public init(extendedGraphemeClusterLiteral value: StringLiteralType) { + self.init(value) + } + + public init(unicodeScalarLiteral value: StringLiteralType) { + self.init(value) + } +} + +extension JSON: Swift.IntegerLiteralConvertible { + + public init(integerLiteral value: IntegerLiteralType) { + self.init(value) + } +} + +extension JSON: Swift.BooleanLiteralConvertible { + + public init(booleanLiteral value: BooleanLiteralType) { + self.init(value) + } +} + +extension JSON: Swift.FloatLiteralConvertible { + + public init(floatLiteral value: FloatLiteralType) { + self.init(value) + } +} + +extension JSON: Swift.DictionaryLiteralConvertible { + + public init(dictionaryLiteral elements: (String, AnyObject)...) { + self.init(elements.reduce([String : AnyObject](minimumCapacity: elements.count)){(dictionary: [String : AnyObject], element:(String, AnyObject)) -> [String : AnyObject] in + var d = dictionary + d[element.0] = element.1 + return d + }) + } +} + +extension JSON: Swift.ArrayLiteralConvertible { + + public init(arrayLiteral elements: AnyObject...) { + self.init(elements) + } +} + +extension JSON: Swift.NilLiteralConvertible { + + public init(nilLiteral: ()) { + self.init(NSNull()) + } +} + +// MARK: - Raw + +extension JSON: Swift.RawRepresentable { + + public init?(rawValue: AnyObject) { + if JSON(rawValue).type == .Unknown { + return nil + } else { + self.init(rawValue) + } + } + + public var rawValue: AnyObject { + return self.object + } + + public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData { + guard NSJSONSerialization.isValidJSONObject(self.object) else { + throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"]) + } + + return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt) + } + + public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? { + switch self.type { + case .Array, .Dictionary: + do { + let data = try self.rawData(options: opt) + return NSString(data: data, encoding: encoding) as? String + } catch _ { + return nil + } + case .String: + return self.rawString + case .Number: + return self.rawNumber.stringValue + case .Bool: + return self.rawNumber.boolValue.description + case .Null: + return "null" + default: + return nil + } + } +} + +// MARK: - Printable, DebugPrintable + +extension JSON: Swift.Printable, Swift.DebugPrintable { + + public var description: String { + if let string = self.rawString(options:.PrettyPrinted) { + return string + } else { + return "unknown" + } + } + + public var debugDescription: String { + return description + } +} + +// MARK: - Array + +extension JSON { + + //Optional [JSON] + public var array: [JSON]? { + get { + if self.type == .Array { + return self.rawArray.map{ JSON($0) } + } else { + return nil + } + } + } + + //Non-optional [JSON] + public var arrayValue: [JSON] { + get { + return self.array ?? [] + } + } + + //Optional [AnyObject] + public var arrayObject: [AnyObject]? { + get { + switch self.type { + case .Array: + return self.rawArray + default: + return nil + } + } + set { + if let array = newValue { + self.object = array + } else { + self.object = NSNull() + } + } + } +} + +// MARK: - Dictionary + +extension JSON { + + //Optional [String : JSON] + public var dictionary: [String : JSON]? { + if self.type == .Dictionary { + return self.rawDictionary.reduce([String : JSON](minimumCapacity: count)) { (dictionary: [String : JSON], element: (String, AnyObject)) -> [String : JSON] in + var d = dictionary + d[element.0] = JSON(element.1) + return d + } + } else { + return nil + } + } + + //Non-optional [String : JSON] + public var dictionaryValue: [String : JSON] { + return self.dictionary ?? [:] + } + + //Optional [String : AnyObject] + public var dictionaryObject: [String : AnyObject]? { + get { + switch self.type { + case .Dictionary: + return self.rawDictionary + default: + return nil + } + } + set { + if let v = newValue { + self.object = v + } else { + self.object = NSNull() + } + } + } +} + +// MARK: - Bool + +extension JSON: Swift.BooleanType { + + //Optional bool + public var bool: Bool? { + get { + switch self.type { + case .Bool: + return self.rawNumber.boolValue + default: + return nil + } + } + set { + if let newValue = newValue { + self.object = NSNumber(bool: newValue) + } else { + self.object = NSNull() + } + } + } + + //Non-optional bool + public var boolValue: Bool { + get { + switch self.type { + case .Bool, .Number, .String: + return self.object.boolValue + default: + return false + } + } + set { + self.object = NSNumber(bool: newValue) + } + } +} + +// MARK: - String + +extension JSON { + + //Optional string + public var string: String? { + get { + switch self.type { + case .String: + return self.object as? String + default: + return nil + } + } + set { + if let newValue = newValue { + self.object = NSString(string:newValue) + } else { + self.object = NSNull() + } + } + } + + //Non-optional string + public var stringValue: String { + get { + switch self.type { + case .String: + return self.object as? String ?? "" + case .Number: + return self.object.stringValue + case .Bool: + return (self.object as? Bool).map { String($0) } ?? "" + default: + return "" + } + } + set { + self.object = NSString(string:newValue) + } + } +} + +// MARK: - Number +extension JSON { + + //Optional number + public var number: NSNumber? { + get { + switch self.type { + case .Number, .Bool: + return self.rawNumber + default: + return nil + } + } + set { + self.object = newValue ?? NSNull() + } + } + + //Non-optional number + public var numberValue: NSNumber { + get { + switch self.type { + case .String: + let decimal = NSDecimalNumber(string: self.object as? String) + if decimal == NSDecimalNumber.notANumber() { // indicates parse error + return NSDecimalNumber.zero() + } + return decimal + case .Number, .Bool: + return self.object as? NSNumber ?? NSNumber(int: 0) + default: + return NSNumber(double: 0.0) + } + } + set { + self.object = newValue + } + } +} + +//MARK: - Null +extension JSON { + + public var null: NSNull? { + get { + switch self.type { + case .Null: + return self.rawNull + default: + return nil + } + } + set { + self.object = NSNull() + } + } + public func exists() -> Bool{ + if let errorValue = error where errorValue.code == ErrorNotExist{ + return false + } + return true + } +} + +//MARK: - URL +extension JSON { + + //Optional URL + public var URL: NSURL? { + get { + switch self.type { + case .String: + if let encodedString_ = self.rawString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) { + return NSURL(string: encodedString_) + } else { + return nil + } + default: + return nil + } + } + set { + self.object = newValue?.absoluteString ?? NSNull() + } + } +} + +// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 + +extension JSON { + + public var double: Double? { + get { + return self.number?.doubleValue + } + set { + if let newValue = newValue { + self.object = NSNumber(double: newValue) + } else { + self.object = NSNull() + } + } + } + + public var doubleValue: Double { + get { + return self.numberValue.doubleValue + } + set { + self.object = NSNumber(double: newValue) + } + } + + public var float: Float? { + get { + return self.number?.floatValue + } + set { + if let newValue = newValue { + self.object = NSNumber(float: newValue) + } else { + self.object = NSNull() + } + } + } + + public var floatValue: Float { + get { + return self.numberValue.floatValue + } + set { + self.object = NSNumber(float: newValue) + } + } + + public var int: Int? { + get { + return self.number?.longValue + } + set { + if let newValue = newValue { + self.object = NSNumber(integer: newValue) + } else { + self.object = NSNull() + } + } + } + + public var intValue: Int { + get { + return self.numberValue.integerValue + } + set { + self.object = NSNumber(integer: newValue) + } + } + + public var uInt: UInt? { + get { + return self.number?.unsignedLongValue + } + set { + if let newValue = newValue { + self.object = NSNumber(unsignedLong: newValue) + } else { + self.object = NSNull() + } + } + } + + public var uIntValue: UInt { + get { + return self.numberValue.unsignedLongValue + } + set { + self.object = NSNumber(unsignedLong: newValue) + } + } + + public var int8: Int8? { + get { + return self.number?.charValue + } + set { + if let newValue = newValue { + self.object = NSNumber(char: newValue) + } else { + self.object = NSNull() + } + } + } + + public var int8Value: Int8 { + get { + return self.numberValue.charValue + } + set { + self.object = NSNumber(char: newValue) + } + } + + public var uInt8: UInt8? { + get { + return self.number?.unsignedCharValue + } + set { + if let newValue = newValue { + self.object = NSNumber(unsignedChar: newValue) + } else { + self.object = NSNull() + } + } + } + + public var uInt8Value: UInt8 { + get { + return self.numberValue.unsignedCharValue + } + set { + self.object = NSNumber(unsignedChar: newValue) + } + } + + public var int16: Int16? { + get { + return self.number?.shortValue + } + set { + if let newValue = newValue { + self.object = NSNumber(short: newValue) + } else { + self.object = NSNull() + } + } + } + + public var int16Value: Int16 { + get { + return self.numberValue.shortValue + } + set { + self.object = NSNumber(short: newValue) + } + } + + public var uInt16: UInt16? { + get { + return self.number?.unsignedShortValue + } + set { + if let newValue = newValue { + self.object = NSNumber(unsignedShort: newValue) + } else { + self.object = NSNull() + } + } + } + + public var uInt16Value: UInt16 { + get { + return self.numberValue.unsignedShortValue + } + set { + self.object = NSNumber(unsignedShort: newValue) + } + } + + public var int32: Int32? { + get { + return self.number?.intValue + } + set { + if let newValue = newValue { + self.object = NSNumber(int: newValue) + } else { + self.object = NSNull() + } + } + } + + public var int32Value: Int32 { + get { + return self.numberValue.intValue + } + set { + self.object = NSNumber(int: newValue) + } + } + + public var uInt32: UInt32? { + get { + return self.number?.unsignedIntValue + } + set { + if let newValue = newValue { + self.object = NSNumber(unsignedInt: newValue) + } else { + self.object = NSNull() + } + } + } + + public var uInt32Value: UInt32 { + get { + return self.numberValue.unsignedIntValue + } + set { + self.object = NSNumber(unsignedInt: newValue) + } + } + + public var int64: Int64? { + get { + return self.number?.longLongValue + } + set { + if let newValue = newValue { + self.object = NSNumber(longLong: newValue) + } else { + self.object = NSNull() + } + } + } + + public var int64Value: Int64 { + get { + return self.numberValue.longLongValue + } + set { + self.object = NSNumber(longLong: newValue) + } + } + + public var uInt64: UInt64? { + get { + return self.number?.unsignedLongLongValue + } + set { + if let newValue = newValue { + self.object = NSNumber(unsignedLongLong: newValue) + } else { + self.object = NSNull() + } + } + } + + public var uInt64Value: UInt64 { + get { + return self.numberValue.unsignedLongLongValue + } + set { + self.object = NSNumber(unsignedLongLong: newValue) + } + } +} + +//MARK: - Comparable +extension JSON : Swift.Comparable {} + +public func ==(lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.Number, .Number): + return lhs.rawNumber == rhs.rawNumber + case (.String, .String): + return lhs.rawString == rhs.rawString + case (.Bool, .Bool): + return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue + case (.Array, .Array): + return lhs.rawArray as NSArray == rhs.rawArray as NSArray + case (.Dictionary, .Dictionary): + return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary + case (.Null, .Null): + return true + default: + return false + } +} + +public func <=(lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.Number, .Number): + return lhs.rawNumber <= rhs.rawNumber + case (.String, .String): + return lhs.rawString <= rhs.rawString + case (.Bool, .Bool): + return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue + case (.Array, .Array): + return lhs.rawArray as NSArray == rhs.rawArray as NSArray + case (.Dictionary, .Dictionary): + return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary + case (.Null, .Null): + return true + default: + return false + } +} + +public func >=(lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.Number, .Number): + return lhs.rawNumber >= rhs.rawNumber + case (.String, .String): + return lhs.rawString >= rhs.rawString + case (.Bool, .Bool): + return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue + case (.Array, .Array): + return lhs.rawArray as NSArray == rhs.rawArray as NSArray + case (.Dictionary, .Dictionary): + return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary + case (.Null, .Null): + return true + default: + return false + } +} + +public func >(lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.Number, .Number): + return lhs.rawNumber > rhs.rawNumber + case (.String, .String): + return lhs.rawString > rhs.rawString + default: + return false + } +} + +public func <(lhs: JSON, rhs: JSON) -> Bool { + + switch (lhs.type, rhs.type) { + case (.Number, .Number): + return lhs.rawNumber < rhs.rawNumber + case (.String, .String): + return lhs.rawString < rhs.rawString + default: + return false + } +} + +private let trueNumber = NSNumber(bool: true) +private let falseNumber = NSNumber(bool: false) +private let trueObjCType = String.fromCString(trueNumber.objCType) +private let falseObjCType = String.fromCString(falseNumber.objCType) + +// MARK: - NSNumber: Comparable + +extension NSNumber { + var isBool:Bool { + get { + let objCType = String.fromCString(self.objCType) + if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) + || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){ + return true + } else { + return false + } + } + } +} + +func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) == NSComparisonResult.OrderedSame + } +} + +func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { + return !(lhs == rhs) +} + +func <(lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) == NSComparisonResult.OrderedAscending + } +} + +func >(lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) == NSComparisonResult.OrderedDescending + } +} + +func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) != NSComparisonResult.OrderedDescending + } +} + +func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { + + switch (lhs.isBool, rhs.isBool) { + case (false, true): + return false + case (true, false): + return false + default: + return lhs.compare(rhs) != NSComparisonResult.OrderedAscending + } +} diff --git a/NoughtsAndCrosses/Pods/Target Support Files/Alamofire/Alamofire-dummy.m b/NoughtsAndCrosses/Pods/Target Support Files/Alamofire/Alamofire-dummy.m new file mode 100644 index 0000000..a6c4594 --- /dev/null +++ b/NoughtsAndCrosses/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/NoughtsAndCrosses/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch b/NoughtsAndCrosses/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch new file mode 100644 index 0000000..aa992a4 --- /dev/null +++ b/NoughtsAndCrosses/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch @@ -0,0 +1,4 @@ +#ifdef __OBJC__ +#import +#endif + diff --git a/NoughtsAndCrosses/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h b/NoughtsAndCrosses/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h new file mode 100644 index 0000000..6b71676 --- /dev/null +++ b/NoughtsAndCrosses/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/NoughtsAndCrosses/Pods/Target Support Files/Alamofire/Alamofire.modulemap b/NoughtsAndCrosses/Pods/Target Support Files/Alamofire/Alamofire.modulemap new file mode 100644 index 0000000..d1f125f --- /dev/null +++ b/NoughtsAndCrosses/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/NoughtsAndCrosses/Pods/Target Support Files/Alamofire/Alamofire.xcconfig b/NoughtsAndCrosses/Pods/Target Support Files/Alamofire/Alamofire.xcconfig new file mode 100644 index 0000000..772ef0b --- /dev/null +++ b/NoughtsAndCrosses/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/NoughtsAndCrosses/Pods/Target Support Files/Alamofire/Info.plist b/NoughtsAndCrosses/Pods/Target Support Files/Alamofire/Info.plist new file mode 100644 index 0000000..ebdce25 --- /dev/null +++ b/NoughtsAndCrosses/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.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Info.plist b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Info.plist new file mode 100644 index 0000000..2243fe6 --- /dev/null +++ b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/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/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses-acknowledgements.markdown b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses-acknowledgements.markdown new file mode 100644 index 0000000..88aaa93 --- /dev/null +++ b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses-acknowledgements.markdown @@ -0,0 +1,51 @@ +# 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. + + +## SwiftyJSON + +The MIT License (MIT) + +Copyright (c) 2014 Ruoyu Fu + +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/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses-acknowledgements.plist b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses-acknowledgements.plist new file mode 100644 index 0000000..6ed051b --- /dev/null +++ b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses-acknowledgements.plist @@ -0,0 +1,85 @@ + + + + + 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 + The MIT License (MIT) + +Copyright (c) 2014 Ruoyu Fu + +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 + SwiftyJSON + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses-dummy.m b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses-dummy.m new file mode 100644 index 0000000..8c171ed --- /dev/null +++ b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_NoughtsAndCrosses : NSObject +@end +@implementation PodsDummy_Pods_NoughtsAndCrosses +@end diff --git a/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses-frameworks.sh b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses-frameworks.sh new file mode 100755 index 0000000..9609b6f --- /dev/null +++ b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses-frameworks.sh @@ -0,0 +1,93 @@ +#!/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/SwiftyJSON/SwiftyJSON.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" + install_framework "$BUILT_PRODUCTS_DIR/SwiftyJSON/SwiftyJSON.framework" +fi diff --git a/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses-resources.sh b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses-resources.sh new file mode 100755 index 0000000..0a15615 --- /dev/null +++ b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses-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/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses-umbrella.h b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses-umbrella.h new file mode 100644 index 0000000..70bebcf --- /dev/null +++ b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses-umbrella.h @@ -0,0 +1,6 @@ +#import + + +FOUNDATION_EXPORT double Pods_NoughtsAndCrossesVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_NoughtsAndCrossesVersionString[]; + diff --git a/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses.debug.xcconfig b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses.debug.xcconfig new file mode 100644 index 0000000..2a514de --- /dev/null +++ b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses.debug.xcconfig @@ -0,0 +1,10 @@ +EMBEDDED_CONTENT_CONTAINS_SWIFT = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON" +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/SwiftyJSON/SwiftyJSON.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "SwiftyJSON" +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/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses.modulemap b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses.modulemap new file mode 100644 index 0000000..dcac512 --- /dev/null +++ b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses.modulemap @@ -0,0 +1,6 @@ +framework module Pods_NoughtsAndCrosses { + umbrella header "Pods-NoughtsAndCrosses-umbrella.h" + + export * + module * { export * } +} diff --git a/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses.release.xcconfig b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses.release.xcconfig new file mode 100644 index 0000000..2a514de --- /dev/null +++ b/NoughtsAndCrosses/Pods/Target Support Files/Pods-NoughtsAndCrosses/Pods-NoughtsAndCrosses.release.xcconfig @@ -0,0 +1,10 @@ +EMBEDDED_CONTENT_CONTAINS_SWIFT = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON" +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/SwiftyJSON/SwiftyJSON.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "SwiftyJSON" +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/NoughtsAndCrosses/Pods/Target Support Files/SwiftyJSON/Info.plist b/NoughtsAndCrosses/Pods/Target Support Files/SwiftyJSON/Info.plist new file mode 100644 index 0000000..ecb8f03 --- /dev/null +++ b/NoughtsAndCrosses/Pods/Target Support Files/SwiftyJSON/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.3.2 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/NoughtsAndCrosses/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-dummy.m b/NoughtsAndCrosses/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-dummy.m new file mode 100644 index 0000000..3159bec --- /dev/null +++ b/NoughtsAndCrosses/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_SwiftyJSON : NSObject +@end +@implementation PodsDummy_SwiftyJSON +@end diff --git a/NoughtsAndCrosses/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch b/NoughtsAndCrosses/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch new file mode 100644 index 0000000..aa992a4 --- /dev/null +++ b/NoughtsAndCrosses/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch @@ -0,0 +1,4 @@ +#ifdef __OBJC__ +#import +#endif + diff --git a/NoughtsAndCrosses/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-umbrella.h b/NoughtsAndCrosses/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-umbrella.h new file mode 100644 index 0000000..ce00ad0 --- /dev/null +++ b/NoughtsAndCrosses/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-umbrella.h @@ -0,0 +1,6 @@ +#import + + +FOUNDATION_EXPORT double SwiftyJSONVersionNumber; +FOUNDATION_EXPORT const unsigned char SwiftyJSONVersionString[]; + diff --git a/NoughtsAndCrosses/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.modulemap b/NoughtsAndCrosses/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.modulemap new file mode 100644 index 0000000..6f41751 --- /dev/null +++ b/NoughtsAndCrosses/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.modulemap @@ -0,0 +1,6 @@ +framework module SwiftyJSON { + umbrella header "SwiftyJSON-umbrella.h" + + export * + module * { export * } +} diff --git a/NoughtsAndCrosses/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.xcconfig b/NoughtsAndCrosses/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.xcconfig new file mode 100644 index 0000000..6165caf --- /dev/null +++ b/NoughtsAndCrosses/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON +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/NoughtsAndCrosses/UIViewControllerExtensions.swift b/NoughtsAndCrosses/UIViewControllerExtensions.swift new file mode 100644 index 0000000..5185dae --- /dev/null +++ b/NoughtsAndCrosses/UIViewControllerExtensions.swift @@ -0,0 +1,66 @@ +// +// UIViewControllerExtensions.swift +// NoughtsAndCrosses +// +// Created by Julian Hulme on 2016/06/05. +// Copyright © 2016 Julian Hulme. All rights reserved. +// + +import Foundation +import UIKit + +public let LOADING_OVERLAY_VIEW_TAG = 987432 + +extension UIViewController { + + + //MARK: Loading screen actions + func addLoadingOverlay () { + + + self.makeViewDropKeyboard() + let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate + + //add an overlay screen + let overlayImage = UIImageView(frame: appDelegate.window!.frame) + overlayImage.backgroundColor = UIColor.blackColor() + overlayImage.alpha = 0.5 + overlayImage.tag = LOADING_OVERLAY_VIEW_TAG + //self.view.userInteractionEnabled = false + appDelegate.window!.userInteractionEnabled = false + + let loadingSpinner = UIActivityIndicatorView(frame: overlayImage.frame) + loadingSpinner.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge + + +// loadingSpinner.center = CGPoint(x:self.overlay.bounds.size.width / 2, y:self.loadingView.bounds.size.height / 2) + + loadingSpinner.startAnimating() + overlayImage.addSubview(loadingSpinner) + + + return appDelegate.window!.addSubview(overlayImage) + } + + func removeLoadingOverlay() { + + let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate + appDelegate.window!.userInteractionEnabled = true + for view in appDelegate.window!.subviews { + if (view.tag == LOADING_OVERLAY_VIEW_TAG) { + view.removeFromSuperview() + } + } + + + } + + func makeViewDropKeyboard() { + print("makeViewDropTapped") + self.view.endEditing(true); + self.resignFirstResponder() + } + + + +} \ No newline at end of file diff --git a/NoughtsAndCrosses/WebService.swift b/NoughtsAndCrosses/WebService.swift new file mode 100644 index 0000000..56f6e33 --- /dev/null +++ b/NoughtsAndCrosses/WebService.swift @@ -0,0 +1,139 @@ +// +// WebService.swift +// NoughtsAndCrosses +// +// Created by Julian Hulme on 2016/06/04. +// Copyright © 2016 Julian Hulme. All rights reserved. +// + +import Foundation +import UIKit +import Alamofire +import SwiftyJSON + +class WebService { + + + //MARK:- Utility request creation methods + func createMutableRequest(url:NSURL!,method:String!,parameters:Dictionary?) -> Request { + + // build request + let headers = ["access-Token":UserController.sharedInstance.getLoggedInUser()!.token, "client": UserController.sharedInstance.getLoggedInUser()!.client, "uid":UserController.sharedInstance.getLoggedInUser()!.email, "token-type":"bearer"] + let request = Alamofire.request(Method(rawValue:method)!, url, parameters: parameters, encoding: .URL, headers: headers) + + + return request + } + + func createMutableAnonRequest(url:NSURL!,method:String!,parameters:Dictionary?) -> Request { + + + // build request + let request = Alamofire.request(.POST, url, parameters: parameters, encoding: .URL) + + return request + } + + + func datafy(value: AnyObject, prettyPrinted: Bool = false) -> NSData? { + + if NSJSONSerialization.isValidJSONObject(value) { + if let data = try? NSJSONSerialization.dataWithJSONObject(value, options: NSJSONWritingOptions.PrettyPrinted) { + if let string = NSString(data: data, encoding: NSUTF8StringEncoding) { + return string.dataUsingEncoding(NSUTF8StringEncoding)! as NSData + } + } + } + return nil + } + + func executeRequest (urlRequest:Request, presentingViewController:UIViewController? = nil, requestCompletionFunction:(Int,JSON) -> ()) { + + //add a loading overlay over the presenting view controller, as we are about to wait for a web request + presentingViewController?.addLoadingOverlay() + + urlRequest.responseJSON { returnedData -> Void in //execute the request and give us JSON response data + + //the web service is now done. Remove the loading overlay + presentingViewController?.removeLoadingOverlay() + + //Handle the response from the web service + let success = returnedData.result.isSuccess + if (success) { + + var json = JSON(returnedData.result.value!) + let serverResponseCode = returnedData.response!.statusCode //since the web service was a success, we know there is a .response value, so we can request the value gets unwrapped with .response! + + let headerData = returnedData.response?.allHeaderFields + + + + if let validToken = returnedData.response!.allHeaderFields["Access-Token"] { + let tokenJson:JSON = JSON(validToken) + json["data"]["token"] = tokenJson + } + if let validClient = returnedData.response!.allHeaderFields["Client"] as? String { + let clientJson:JSON = JSON(validClient) + json["data"]["client"] = clientJson + } + + if (self.handleCommonResponses(serverResponseCode, presentingViewController: presentingViewController)) { + //print to the console that we experienced a common erroneos response + print("A common bad server response was found, error has been displayed") + + } + + //execute the completion function specified by the class that called this executeRequest function + //the + requestCompletionFunction(serverResponseCode,json) + + } else { //response code is nil - The web service couldn't connect to the internet. Show a "Connection Error" alert, assuming the presentingViewController was given (a UIViewController provided as the presentingViewController parameter provides the ability to show an alert) + let alert = self.connectionErrorAlert() + presentingViewController?.presentViewController(alert, animated: true, completion: nil) + //execute the completion function specified by the class that called this executeRequest function + requestCompletionFunction(0,JSON("")) + } + } + } + + + //used by the executeRequest function to show that the app experienced a connection error + func connectionErrorAlert() -> UIAlertController { + let alert = UIAlertController(title:"Connection Error", message:"Not connected", preferredStyle: UIAlertControllerStyle.Alert) + alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) + return alert + } + + //used by the executeRequest function to show that the app experienced a backend server error + func server500Alert() -> UIAlertController { + let alert = UIAlertController(title:"Oh Dear", message:"There was an problem handling your request", preferredStyle: UIAlertControllerStyle.Alert) + alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) + return alert + } + + //used by the executeRequest function to check if the app should show any common network errors in an alert + //returns true if an error and the corresponding alert was activated, or false if no errors were found + func handleCommonResponses(responseCode:Int, presentingViewController:UIViewController?) -> Bool { + //handle session expiry + if (responseCode == 302) { + + //we are not going to experience this response, yet. This code will never execute + return true + + + } else if (responseCode == 500) { + + if let vc = presentingViewController { + + let alert = server500Alert() + vc.presentViewController(alert, animated: true, completion: nil) + return true + } + + + } + + return false //returning false indicates that no errors were detected + } + +} \ No newline at end of file