From 1b312c22c0b75416f697f24ce27cb10fba9ce304 Mon Sep 17 00:00:00 2001 From: Burcu Geneci Date: Thu, 2 Aug 2018 20:26:50 +0300 Subject: [PATCH 1/5] EVReflection pod installed. --- Podfile | 2 +- Podfile.lock | 17 +- Pods/EVReflection/LICENSE | 27 + Pods/EVReflection/README.md | 595 ++++++ .../Source/ConversionOptions.swift | 63 + .../Source/DeserializationStatus.swift | 53 + .../Source/EVArrayExtension.swift | 250 +++ .../Source/EVCustomReflectable.swift | 15 + .../Source/EVDictionaryExtension.swift | 88 + Pods/EVReflection/Source/EVObject.swift | 200 +++ Pods/EVReflection/Source/EVReflectable.swift | 639 +++++++ Pods/EVReflection/Source/EVReflection.swift | 1597 +++++++++++++++++ .../Source/EVWorkaroundHelpers.swift | 106 ++ Pods/EVReflection/Source/PrintOptions.swift | 75 + Pods/Manifest.lock | 17 +- Pods/Pods.xcodeproj/project.pbxproj | 388 +++- .../xcschemes/EVReflection.xcscheme | 60 + .../xcschemes/Pods-ProjectX.xcscheme | 4 +- .../xcschemes/xcschememanagement.plist | 13 +- .../EVReflection/EVReflection-dummy.m | 5 + .../EVReflection/EVReflection-prefix.pch | 12 + .../EVReflection/EVReflection-umbrella.h | 16 + .../EVReflection/EVReflection.modulemap | 6 + .../EVReflection/EVReflection.xcconfig | 11 + .../EVReflection/Info.plist | 26 + .../Pods-ProjectX-acknowledgements.markdown | 31 + .../Pods-ProjectX-acknowledgements.plist | 37 + .../Pods-ProjectX/Pods-ProjectX-frameworks.sh | 7 + .../Pods-ProjectX.debug.xcconfig | 5 + .../Pods-ProjectX.release.xcconfig | 5 + .../Pods-ProjectXTests.debug.xcconfig | 2 + .../Pods-ProjectXTests.release.xcconfig | 2 + .../Pods-ProjectXUITests.debug.xcconfig | 2 + .../Pods-ProjectXUITests.release.xcconfig | 2 + ProjectX.xcodeproj/project.pbxproj | 19 + .../xcschemes/xcschememanagement.plist | 2 +- .../UserInterfaceState.xcuserstate | Bin 14059 -> 16558 bytes 37 files changed, 4312 insertions(+), 87 deletions(-) create mode 100755 Pods/EVReflection/LICENSE create mode 100755 Pods/EVReflection/README.md create mode 100644 Pods/EVReflection/Source/ConversionOptions.swift create mode 100644 Pods/EVReflection/Source/DeserializationStatus.swift create mode 100755 Pods/EVReflection/Source/EVArrayExtension.swift create mode 100644 Pods/EVReflection/Source/EVCustomReflectable.swift create mode 100755 Pods/EVReflection/Source/EVDictionaryExtension.swift create mode 100755 Pods/EVReflection/Source/EVObject.swift create mode 100755 Pods/EVReflection/Source/EVReflectable.swift create mode 100755 Pods/EVReflection/Source/EVReflection.swift create mode 100755 Pods/EVReflection/Source/EVWorkaroundHelpers.swift create mode 100644 Pods/EVReflection/Source/PrintOptions.swift create mode 100644 Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/EVReflection.xcscheme create mode 100644 Pods/Target Support Files/EVReflection/EVReflection-dummy.m create mode 100644 Pods/Target Support Files/EVReflection/EVReflection-prefix.pch create mode 100644 Pods/Target Support Files/EVReflection/EVReflection-umbrella.h create mode 100644 Pods/Target Support Files/EVReflection/EVReflection.modulemap create mode 100644 Pods/Target Support Files/EVReflection/EVReflection.xcconfig create mode 100644 Pods/Target Support Files/EVReflection/Info.plist diff --git a/Podfile b/Podfile index 7a7f4ca..3ff166c 100644 --- a/Podfile +++ b/Podfile @@ -4,7 +4,7 @@ target 'ProjectX' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! - + pod "EVReflection" # Pods for ProjectX target 'ProjectXTests' do diff --git a/Podfile.lock b/Podfile.lock index f5c842b..16acd90 100644 --- a/Podfile.lock +++ b/Podfile.lock @@ -1,3 +1,18 @@ -PODFILE CHECKSUM: 44822adf25116fba9612f9a6e4184f5ab4db9a7f +PODS: + - EVReflection (5.6.2): + - EVReflection/Core (= 5.6.2) + - EVReflection/Core (5.6.2) + +DEPENDENCIES: + - EVReflection + +SPEC REPOS: + https://github.com/cocoapods/specs.git: + - EVReflection + +SPEC CHECKSUMS: + EVReflection: 640322f8a3aaf78cbc3c23892476b6adb636ebf0 + +PODFILE CHECKSUM: 37c990d763bcdd56cefd04cd5de41c1753bf9fd2 COCOAPODS: 1.5.2 diff --git a/Pods/EVReflection/LICENSE b/Pods/EVReflection/LICENSE new file mode 100755 index 0000000..98fe3a9 --- /dev/null +++ b/Pods/EVReflection/LICENSE @@ -0,0 +1,27 @@ +MIT 3 License + +Copyright (c) 2015, EVICT B.V. +All rights reserved. +http://evict.nl, mailto://edwin@evict.nl + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: +* Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. +* Neither the name of EVICT B.V. nor the +names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Pods/EVReflection/README.md b/Pods/EVReflection/README.md new file mode 100755 index 0000000..b161d56 --- /dev/null +++ b/Pods/EVReflection/README.md @@ -0,0 +1,595 @@ +# EVReflection + + +[![Issues](https://img.shields.io/github/issues-raw/evermeer/EVReflection.svg?style=flat)](https://github.com/evermeer/EVReflection/issues) +[![Coverage](https://img.shields.io/badge/coverage-80%25-yellow.svg?style=flat)](https://raw.githubusercontent.com/evermeer/EVReflection/master/UnitTests/coverage.png) +[![Documentation](https://img.shields.io/badge/documented-97%25-green.svg?style=flat)](http://cocoadocs.org/docsets/EVReflection/3.7.0/) +[![Stars](https://img.shields.io/github/stars/evermeer/EVReflection.svg?style=flat)](https://github.com/evermeer/EVReflection/stargazers) +[![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/matteocrippa/awesome-swift#json) +[![Downloads](https://img.shields.io/cocoapods/dt/EVReflection.svg?style=flat)](https://cocoapods.org/pods/EVReflection) + + +[![Version](https://img.shields.io/cocoapods/v/EVReflection.svg?style=flat)](http://cocoadocs.org/docsets/EVReflection) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Language](https://img.shields.io/badge/language-swift%204-f48041.svg?style=flat)](https://developer.apple.com/swift) +[![Platform](https://img.shields.io/cocoapods/p/EVReflection.svg?style=flat)](http://cocoadocs.org/docsets/EVReflection) +[![License](https://img.shields.io/cocoapods/l/EVReflection.svg?style=flat)](http://cocoadocs.org/docsets/EVReflection) + +[![Git](https://img.shields.io/badge/GitHub-evermeer-blue.svg?style=flat)](https://github.com/evermeer) +[![Twitter](https://img.shields.io/badge/twitter-@evermeer-blue.svg?style=flat)](http://twitter.com/evermeer) +[![LinkedIn](https://img.shields.io/badge/linkedin-Edwin%20Vermeer-blue.svg?style=flat)](http://nl.linkedin.com/in/evermeer/en) +[![Website](https://img.shields.io/badge/website-evict.nl-blue.svg?style=flat)](http://evict.nl) +[![eMail](https://img.shields.io/badge/email-edwin@evict.nl-blue.svg?style=flat)](mailto:edwin@evict.nl?SUBJECT=About%20EVReflection) + +# General information + +If you have a question and don't want to create an issue, then we can [![Join the chat at https://gitter.im/evermeer/EVReflection](https://badges.gitter.im/evermeer/EVReflection.svg)](https://gitter.im/evermeer/EVReflection?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +At this moment the master branch is for Swift 4.0 If you want to continue using EVReflection in an older version, then use the corresponding branch. +Run the unit tests to see EVReflection in action. + +EVReflection is used in [EVCloudKitDao](https://github.com/evermeer/EVCloudKitDao) and [EVWordPressAPI](https://github.com/evermeer/EVWordPressAPI) + +In most cases EVReflection is very easy to use. Just take a look the section [It's easy to use](https://github.com/evermeer/EVReflection#its-easy-to-use). But if you do want to do non standard specific things, then EVReflection will offer you an extensive range of functionality. + +### Available extensions +There are extension available for using EVReflection with [XMLDictionairy](https://github.com/nicklockwood/XMLDictionary), [Realm](https://realm.io), [CloudKit](https://developer.apple.com/library/content/documentation/DataManagement/Conceptual/CloudKitQuickStart/Introduction/Introduction.html), [Alamofire](https://github.com/Alamofire/Alamofire) and [Moya](https://github.com/Moya/Moya) with [RxSwift](https://github.com/ReactiveX/RxSwift) or [ReactiveSwift](https://github.com/ReactiveSwift/ReactiveSwift) + +- [XML](https://github.com/evermeer/EVReflection/tree/master/Source/XML) +- [CloudKit](https://github.com/evermeer/EVReflection/tree/master/Source/CloudKit) +- [CoreData](https://github.com/evermeer/EVReflection/tree/master/Source/CoreData) +- [Realm](https://github.com/evermeer/EVReflection/tree/master/Source/Realm) +- [Alamofire](https://github.com/evermeer/EVReflection/tree/master/Source/Alamofire) +- [AlamofireXML](https://github.com/evermeer/EVReflection/tree/master/Source/XML) +- [Moya](https://github.com/evermeer/EVReflection/tree/master/Source/Alamofire/Moya) +- [MoyaXML](https://github.com/evermeer/EVReflection/tree/master/Source/Alamofire/Moya/XML) +- [MoyaRxSwift](https://github.com/evermeer/EVReflection/tree/master/Source/Alamofire/Moya/RxSwift) +- [MoyaRxSwiftXML](https://github.com/evermeer/EVReflection/tree/master/Source/Alamofire/Moya/RxSwift/XML) +- [MoyaReactiveSwift](https://github.com/evermeer/EVReflection/tree/master/Source/Alamofire/Moya/ReactiveSwift) +- [MoyaReactiveSwiftXML](https://github.com/evermeer/EVReflection/tree/master/Source/Alamofire/Moya/ReactiveSwift/XML) + +All these extens can be installed by adding something like this in your podfile: + +``` +pod 'EVReflection/MoyaRxSwift' +``` + +## Index + +- [Main features of EVReflection](https://github.com/evermeer/EVReflection#main-features-of-evreflection) +- [It's easy to use](https://github.com/evermeer/EVReflection#its-easy-to-use) +- [If you have XML instead of JSON](https://github.com/evermeer/EVReflection#if-you-have-xml-instead-of-json) +- [Using EVReflection in your own App](https://github.com/evermeer/EVReflection#using-evreflection-in-your-own-app) +- [More Sample code](https://github.com/evermeer/EVReflection#more-sample-code) +- [Extending existing objects](https://github.com/evermeer/EVReflection#extending-existing-objects) +- [Conversion options](https://github.com/evermeer/EVReflection#conversion-options) +- [Automatic keyword mapping for Swift keywords](https://github.com/evermeer/EVReflection#automatic-keyword-mapping-for-swift-keywords) +- [Automatic keyword mapping PascalCase or camelCase to snake_case](https://github.com/evermeer/EVReflection#automatic-keyword-mapping-pascalcase-or-camelcase-to-snake_case) +- [Custom keyword mapping](https://github.com/evermeer/EVReflection#custom-keyword-mapping) +- [Custom property converters](https://github.com/evermeer/EVReflection#custom-property-converters) +- [Custom object converter](https://github.com/evermeer/EVReflection#custom-object-converter) +- [Custom type converters](https://github.com/evermeer/EVReflection#custom-type-converter) +- [Encoding and Decoding](https://github.com/evermeer/EVReflection#encoding-and-decoding) +- [Skip the serialization or deserialization of specific values](https://github.com/evermeer/EVReflection#skip-the-serialization-or-deserialization-of-specific-values) +- [Property validators](https://github.com/evermeer/EVReflection#property-validators) +- [Print options](https://github.com/evermeer/EVReflection#print-options) +- [Deserialization class level validations](https://github.com/evermeer/EVReflection#deserialization-class-level-validations) +- [What to do when you use object inheritance](https://github.com/evermeer/EVReflection#what-to-do-when-you-use-object-inheritance) +- [Known issues](https://github.com/evermeer/EVReflection#known-issues) +- [License](https://github.com/evermeer/EVReflection#license) +- [My other libraries](https://github.com/evermeer/EVReflection#my-other-libraries) + +## Main features of EVReflection: +- Parsing objects based on NSObject to and from a dictionary. (also see the XML and .plist samples!) +- Parsing objects to and from a JSON string. +- Support NSCoding function encodeWithCoder and decodeObjectWithCoder +- Supporting Printable, Hashable and Equatable while using all properties. +- Mapping objects from one type to an other +- Support for property mapping, converters, validators and key cleanup + +## It's easy to use: + +Defining an object. You only have to set EVObject as it's base class (or extend an NSObject with EVReflectable): +```swift +class User: EVObject { + var id: Int = 0 + var name: String = "" + var friends: [User]? = [] +} +``` + +Parsing JSON to an object: +```swift +let json:String = "{\"id\": 24, \"name\": \"Bob Jefferson\", \"friends\": [{\"id\": 29, \"name\": \"Jen Jackson\"}]}" +let user = User(json: json) +``` + +Parsing JSON to an array of objects: +```swift +let json:String = "[{\"id\": 27, \"name\": \"Bob Jefferson\"}, {\"id\": 29, \"name\": \"Jen Jackson\"}]" +let array = [User](json: json) +``` + +Parsing from and to a dictionary: +```swift +let dict = user.toDictionary() +let newUser = User(dictionary: dict) +XCTAssert(user == newUser, "Pass") +``` + +Saving and loading an object to and from a file: +```swift +user.saveToTemp("temp.dat") +let result = User(fileNameInTemp: "temp.dat") +XCTAssert(theObject == result, "Pass") +``` + +Mapping object to another type: +```swift +let administrator: Administrator = user.mapObjectTo() +``` + + +## If you have XML instead of JSON + +If you want to do the same but you have XML, then you can achieve that using the XML subspec 'pod EVReflection/XML' It is a simple way to parse XML. With that your code will look like this: + +```swift +let xml = "27Bob20Jen" +let user = User(xmlString: xml) +``` + +## Using EVReflection in your own App + +'EVReflection' is available through the dependency manager [CocoaPods](http://cocoapods.org). +You do have to use cocoapods version 0.36 or later + +You can just add EVReflection to your workspace by adding the following 2 lines to your Podfile: + +``` +use_frameworks! +pod "EVReflection" +``` + +You can also use the Swift2.2 or Swift2.3 version of EVReflection. You can get that version by using the podfile command: +``` +use_frameworks! +pod "EVReflection"', :git => 'https://github.com/evermeer/EVReflection.git', :branch => 'Swift2.2' +``` + +Version 0.36 of cocoapods will make a dynamic framework of all the pods that you use. Because of that it's only supported in iOS 8.0 or later. When using a framework, you also have to add an import at the top of your swift file like this: + +```swift +import EVReflection +``` + +If you want support for older versions than iOS 8.0, then you can also just copy the files from the pod folder to your project. You do have to use the Swift2.3 version or older. iOS 7 support is dropped from Swift 3. + +Be aware that when you have your object definitions in a framework and not in your main app, then you have to let EVReflection know that it should also look in that framework for your classes. This can easilly be done by using the following one liner (for instance in the appdelegate) +```swift +EVReflection.setBundleIdentifier(YourDataObject.self) +``` + + +## More Sample code +Clone EVReflection to your desktop to see these and more unit tests + +```swift +func testEquatable() { + var theObjectA = TestObject2() + theObjectA.objectValue = "value1" + var theObjectB = TestObject2() + theObjectB.objectValue = "value1" + XCTAssert(theObjectA == theObjectB, "Pass") + + theObjectB.objectValue = "value2" + XCTAssert(theObjectA != theObjectB, "Pass") +} + +func testHashable() { + var theObject = TestObject2() + theObject.objectValue = "value1" + var hash1 = theObject.hash + NSLog("hash = \(hash)") +} + +func testPrintable() { + var theObject = TestObject2() + theObject.objectValue = "value1" + NSLog("theObject = \(theObject)") +} + +func testArrayFunctions() { + let dictionaryArray: [NSDictionary] = yourGetDictionaryArrayFunction() + let userArray = [User](dictionaryArray: dictionaryArray) + let newDictionaryArray = userArray.toDictionaryArray() +} + +func testMapping() { + let player = GamePlayer() + player.name = "It's Me" + + let administrator = GameAdministrator(usingValuesFrom: player) +} +``` + +Direct conversion from a NSDictionary (or an array of NSDictionaries) to json and back. +```swift +let dict1: NSDictionary = [ + "requestId": "request", + "postcode": "1111AA", + "houseNumber": "1" +] +let json = dict1.toJsonString() +let dict2 = NSMutableDictionary(json: json) +print("dict:\n\(dict1)\n\njson:\n\(json)\n\ndict2:\n\(dict2)") + +// You can do the same with arrays +let array:[NSDictionary] = [dict1, dict2] +let jsonArray = array.toJsonStringArray() +let array2 = [NSDictionary](jsonArray: jsonArray) +print("json array: \n\(jsonArray)\n\narray2:\n\(array2)") +``` + + +This is how you can parse a .plist into an object model. See EVReflectionIssue124.swift to see it working. +```swift + if let path = Bundle(for: type(of: self)).path(forResource: "EVReflectionIssue124", ofType: "plist") { + if let data = NSDictionary(contentsOfFile: path) { + let plistObject = Wrapper(dictionary: data) + print(plistObject) + } + } +``` + +If you want to parse XML, then you can use the pod subxpec EVReflection/XML +```swift + let xml: String = "itemData" + let xmlObject = MyObject(xml: xml) + print(xmlObject) +``` + +## Extending existing objects: +It is possible to extend other objects with the EVReflectable protocol instead of changing the base class to EVObject. This will let you add the power of EVReflection to objects that also need another framework. In some cases you still need some aditional code. For a sample see the Realm and NSManagedObject subspecs. The most basic way to extend your objects is like this: + +```swift +import EVReflection +extension MyObject : EVReflectable { } +``` + +## Extra information: + +### Conversion options +With almost any EVReflection function you can specify what kind of conversion options should be used. This is done using an option set. You can use the following conversion options: + +- None - Do not use any conversion function. +- [PropertyConverter](https://github.com/evermeer/EVReflection#custom-property-converters) : If specified the function propertyConverters on the EVObject will be called +- [PropertyMapping](https://github.com/evermeer/EVReflection#custom-keyword-mapping) : If specified the function propertyMapping on the EVObject will be called +- [SkipPropertyValue](https://github.com/evermeer/EVReflection#skip-the-serialization-or-deserialization-of-specific-values) : If specified the function skipPropertyValue on the EVObject will be called +- [KeyCleanup](https://github.com/evermeer/EVReflection#automatic-keyword-mapping-pascalcase-or-camelcase-to-snake_case) : If specified the automatic pascalCase and snake_case property key mapping will be called. +- [Encoding](https://github.com/evermeer/EVReflection#encoding-and-decoding) : For if you want class level functionality for encoding values (like base64, unicode, encription, ...) +- [Decoding](https://github.com/evermeer/EVReflection#encoding-and-decoding) : For if you want class level functionality for decoding values (like base64, unicode, encription, ...) + +In EVReflection all functions will use a default conversion option specific to it's function. The following 4 default conversion types are used: +- DefaultNSCoding = [None] +- DefaultComparing = [PropertyConverter, PropertyMapping, SkipPropertyValue] +- DefaultDeserialize = [PropertyConverter, PropertyMapping, SkipPropertyValue, KeyCleanup, Decoding] +- DefaultSerialize = [PropertyConverter, PropertyMapping, SkipPropertyValue, Encoding] + +If you want to change one of the default conversion types, then you can do that using something like: +```swift +ConversionOptions.DefaultNSCoding = [.PropertyMapping] +``` + + +### Automatic keyword mapping for Swift keywords +If you have JSON fields that are Swift keywords, then prefix the property with an underscore. So the JSON value for self will be stored in the property `\_self`. At this moment the following keywords are handled: + +"self", "description", "class", "deinit", "enum", "extension", "func", "import", "init", "let", "protocol", "static", "struct", "subscript", "typealias", "var", "break", "case", "continue", "default", "do", "else", "fallthrough", "if", "in", "for", "return", "switch", "where", "while", "as", "dynamicType", "is", "new", "super", "Self", "Type", "__COLUMN__", "__FILE__", "__FUNCTION__", "__LINE__", "associativity", "didSet", "get", "infix", "inout", "left", "mutating", "none", "nonmutating", "operator", "override", "postfix", "precedence", "prefix", "right", "set", "unowned", "unowned", "safe", "unowned", "unsafe", "weak", "willSet", "private", "public" + +### Automatic keyword mapping PascalCase or camelCase to snake_case +When creating objects from JSON EVReflection will automatically detect if snake_case (keys are all lowercase and words are separated by an underscore) should be converted to PascalCase or camelCase property names. See [Conversion options](https://github.com/evermeer/EVReflection#conversion-options) for when this function will be called. + +When exporting object to a dictionary or JSON string you will have an option to specify that you want a conversion to snake_case or not. The default is .DefaultDeserialize which will also convert to snake case. + +```swift +let jsonString = myObject.toJsonString([.DefaultSerialize]) +let dict = myObject.toDictionary([PropertyConverter, PropertyMapping, SkipPropertyValue]) +``` + + +### Custom keyword mapping +It's also possible to create a custom property mapping. You can define if an import should be ignored, if an export should be ignored or you can map a property name to another key name (for the dictionary and json). For this you only need to implement the propertyMapping function in the object. See [Conversion options](https://github.com/evermeer/EVReflection#conversion-options) for when this function will be called. + +```swift +public class TestObject5: EVObject { + var Name: String = "" // Using the default mapping + var propertyInObject: String = "" // will be written to or read from keyInJson + var ignoredProperty: String = "" // Will not be written or read to/from json + + override public func propertyMapping() -> [(keyInObject: String?, keyInResource: String?)] { + return [(keyInObject: "ignoredProperty",keyInResource: nil), (keyInObject: "propertyInObject",keyInResource: "keyInJson")] + } +} +``` + +### Custom property converters +You can also use your own property converters. For this you need to implement the propertyConverters function in your object. For each property you can create a custom getter and setter that will then be used by EVReflection. In the sample below the JSON texts 'Sure' and 'Nah' will be converted to true or false for the property isGreat. See [Conversion options](https://github.com/evermeer/EVReflection#conversion-options) for when this function will be called. +```swift +public class TestObject6: EVObject { + var isGreat: Bool = false + + override func propertyConverters() -> [(key: String, decodeConverter: ((Any?) -> ()), encodeConverter: (() -> Any?))] { + return [ + ( // We want a custom converter for the field isGreat + key: "isGreat" + // isGreat will be true if the json says 'Sure' + , decodeConverter: { self.isGreat = ($0 as? String == "Sure") } + // The json will say 'Sure if isGreat is true, otherwise it will say 'Nah' + , encodeConverter: { return self.isGreat ? "Sure": "Nah"}) + ] + } +} +``` + +### Encoding and decoding +You can add generic cod to encode or decode multiple or all properties in an object. This can be used for instance for base64, unicode and encription. Here is a base64 sample: + +```swift +class SimleEncodingDecodingObject : EVObject{ + var firstName: String? + var lastName: String? + var street: String? + var city: String? + + override func decodePropertyValue(value: Any, key: String) -> Any? { + return (value as? String)?.base64Decoded?.string ?? value + } + + override func encodePropertyValue(value: Any, key: String) -> Any { + return (value as? String)?.base64Encoded.string ?? value + } +} + + +extension String { +var data: Data { return Data(utf8) } +var base64Encoded: Data { return data.base64EncodedData() } +var base64Decoded: Data? { return Data(base64Encoded: self) } +} + +extension Data { +var string: String? { return String(data: self, encoding: .utf8) } +} +``` + + + +### Custom object converter +If you want to serialize an object to a dictionary or json but the structure should be different than the object itself, then instead of using propertyConverers, you can also convert the entire object by implementing the customConverter function. In the example below the entire object will be serialized to just a string. You could also return a dictionary that represents the custom structure or an array if the object should have been an array + +```swift +override func customConverter() -> AnyObject? { + return "Object not serialized" +} +``` + + +### Custom type converter +If you have a custom type that requires special conversion, then you can extend it with the EVCustomReflectable protocol. A good implementation for this can be found in the Realm subspec for the List type. The converter is implemented like this: + +```swift +extension List : EVCustomReflectable { + public func constructWith(value: Any?) -> EVCustomReflectable { + if let array = value as? [NSDictionary] { + self.removeAll() + for dict in array { + if let element: T = EVReflection.fromDictionary(dict, anyobjectTypeString: _rlmArray.objectClassName) as? T { + self.append(element) + } + } + } + return self + } + public func toCodableValue() -> Any { + return self.enumerated().map { ($0.element as? EVReflectable)?.toDictionary() ?? NSDictionary() } + } +} +``` + +For the usage, please have a look at [the Realm unittest](https://github.com/evermeer/EVReflection/blob/master/UnitTests/RealmTests/RealmTests.swift) + + +### Skip the serialization or deserialization of specific values +When there is a need to not (de)serialize specific values like nil NSNull or empty strings you can implement the skipPropertyValue function and return true if the value needs to be skipped. See [Conversion options](https://github.com/evermeer/EVReflection#conversion-options) for when this function will be called. + +```swift +class TestObjectSkipValues: EVObject { + var value1: String? + var value2: [String]? + var value3: NSNumber? + + override func skipPropertyValue(value: Any, key: String) -> Bool { + if let value = value as? String where value.characters.count == 0 || value == "null" { + print("Ignoring empty string for key \(key)") + return true + } else if let value = value as? NSArray where value.count == 0 { + print("Ignoring empty NSArray for key\(key)") + return true + } else if value is NSNull { + print("Ignoring NSNull for key \(key)") + return true + } + return false + } +} +``` + +### Property validators +Before setting a value the value will always be validated using the standard validateValue KVO function. This means that for every property you can also create a validation function for that property. See the sample below where there is a validateName function for the name property. + +```swift +enum MyValidationError: ErrorType { + case TypeError, + LengthError +} + +public class GameUser: EVObject { + var name: String? + var memberSince: NSDate? + var objectIsNotAValue: TestObject? + + func validateName(value:AutoreleasingUnsafeMutablePointer) throws { + if let theValue = value.memory as? String { + if theValue.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) < 3 { + NSLog("Validating name is not long enough \(theValue)") + throw MyValidationError.LengthError + } + NSLog("Validating name OK \(theValue)") + } else { + NSLog("Validating name is not a string: \(value.memory)") + throw MyValidationError.TypeError + } + } +} +``` + +### Print options +You should be able to solve all problems with parsing your json to an object. If you get warnings and you know they don't matter and you want to stop them from printin you can suppress all print warings by calling the followin line of code: + +```swift +PrintOptions.Active = .None +``` + +If you then want to turn on the print output, then just call: + +``` +PrintOptions.Active = .All +``` + +It's also possible to enable printing for specific warning types. Here is the line of code that is equal to setting it to .All. Just leave out the type that you want to suppress. + +``` +PrintOptions.Active = [.UnknownKeypath, .IncorrectKey, .ShouldExtendNSObject, .IsInvalidJson, .MissingProtocol, .MissingKey, .InvalidType, .InvalidValue, .InvalidClass, .EnumWithoutAssociatedValue] +``` + + +### Deserialization class level validations +There is also support for class level validation when deserializing to an object. There are helper functions for making keys required or not allowed. You can also add custom messages. Here is some sample code about how you can implement such a validation + +```swift +public class ValidateObject: EVObject { + var requiredKey1: String? + var requiredKey2: String? + var optionalKey1: String? + + override public func initValidation(dict: NSDictionary) { + self.initMayNotContainKeys(["error"], dict: dict) + self.initMustContainKeys(["requiredKey1", "requiredKey2"], dict: dict) + if dict.valueForKey("requiredKey1") as? String == dict.valueForKey("optionalKey1") as? String { + // this could also be called in your property specific validators + self.addStatusMessage(.Custom, message: "optionalKey1 should not be the same as requiredKey1") + } + } +} +``` +You could then test this validation with code like: +```swift +func testValidation() { + // Test missing required key + let json = "{\"requiredKey1\": \"Value1\"}" + let test = ValidateObject(json: json) + XCTAssertNotEqual(test.evReflectionStatus(), .None, "We should have a not .None status") + XCTAssertEqual(test.evReflectionStatuses.count, 1, "We should have 1 validation result") + for (status, message) in test.evReflectionStatuses { + print("Validation result: Status = \(status), Message = \(message)") + } +} +``` + +### What to do when you use object inheritance +You can deserialize json to an object that uses inheritance. When the properties are specified as the base class, then the correct specific object type will be returned by the function `getSpecificType`. See the sample code below or the unit test in EVReflectionInheritanceTests.swift + +```swift +class Quz: EVObject { + var fooArray: Array = [] + var fooBar: Foo? + var fooBaz: Foo? +} + +class Foo: EVObject { + var allFoo: String = "all Foo" + + // What you need to do to get the correct type for when you deserialize inherited classes + override func getSpecificType(_ dict: NSDictionary) -> EVReflectable { + if dict["justBar"] != nil { + return Bar() + } else if dict["justBaz"] != nil { + return Baz() + } + return self + } +} + +class Bar : Foo { + var justBar: String = "For bar only" +} + +class Baz: Foo { + var justBaz: String = "For baz only" +} +``` + + +### Known issues +EVReflection is trying to handle all types. With some types there are limitations in Swift. So far there is a workaround for any of these limitations. Here is an overview: + +#### It's not possible in Swift to use .setObjectForKey for: +- nullable type fields like Int? +- properties based on an enum +- an Array of nullable objects like [MyObject?] +- a Set like Set +- generic properties like var myVal:T = T() +- structs like CGRect or CGPoint + +For all these issues there are workarounds. The easiest workaround is just using a difrent type like: + +- Instead of an Int? you could use NSNumber? +- Instead of [MyObject?] use [MyObject] +- Instead of Set use [MyObject] +- Instead of 'var status: StatysType' use 'var status:Int' and save the rawValue +- Instead of a generic property use a specific property that can hold the data (a dictionary?) +- Instead of using a struct, create your own object model for that struct + +If you want to keep on using the same type, You can override the setValue forUndefinedKey in the object itself. See WorkaroundsTests.swift and WorkaroundSwiftGenericsTests.swift to see the workaround for all these types in action. + +#### Generic properties +For generic properties the protocol EVGenericsKVC is required. see WorkaroundSwiftGenericsTests.swift + +#### Arrays with nullable objects or Set's +For arrays with nullable objects or Set's like [MyObj?] or Set the protocol EVArrayConvertable is required. see WorkaroundsTests.swift + +#### Swift Dictionaries +For Swift Dictionaries (and not NSDictionary) the protocol EVDictionaryConvertable is required. See WorkaroundsTests.swift + +## License + +EVReflection is available under the MIT 3 license. See the LICENSE file for more info. + +## My other libraries: +Also see my other public source iOS libraries: + +- [EVReflection](https://github.com/evermeer/EVReflection) - Reflection based (Dictionary, CKRecord, JSON and XML) object mapping with extensions for Alamofire and Moya with RxSwift or ReactiveSwift +- [EVCloudKitDao](https://github.com/evermeer/EVCloudKitDao) - Simplified access to Apple's CloudKit +- [EVFaceTracker](https://github.com/evermeer/EVFaceTracker) - Calculate the distance and angle of your device with regards to your face in order to simulate a 3D effect +- [EVURLCache](https://github.com/evermeer/EVURLCache) - a NSURLCache subclass for handling all web requests that use NSURLReques +- [AlamofireOauth2](https://github.com/evermeer/AlamofireOauth2) - A swift implementation of OAuth2 using Alamofire +- [EVWordPressAPI](https://github.com/evermeer/EVWordPressAPI) - Swift Implementation of the WordPress (Jetpack) API using AlamofireOauth2, AlomofireJsonToObjects and EVReflection (work in progress) +- [PassportScanner](https://github.com/evermeer/PassportScanner) - Scan the MRZ code of a passport and extract the firstname, lastname, passport number, nationality, date of birth, expiration date and personal numer. +- [AttributedTextView](https://github.com/evermeer/AttributedTextView) - Easiest way to create an attributed UITextView with support for multiple links (url, hashtags, mentions). + +## Evolution of EVReflection (Gource Visualization) +[![Evolution of EVReflection (Gource Visualization)](https://img.youtube.com/vi/FIETlttIFh8/0.jpg)](https://www.youtube.com/watch?v=FIETlttIFh8) diff --git a/Pods/EVReflection/Source/ConversionOptions.swift b/Pods/EVReflection/Source/ConversionOptions.swift new file mode 100644 index 0000000..cde8372 --- /dev/null +++ b/Pods/EVReflection/Source/ConversionOptions.swift @@ -0,0 +1,63 @@ +// +// ConversionOptions.swift +// EVReflection +// +// Created by Edwin Vermeer on 9/5/16. +// Copyright © 2015 evict. All rights reserved. +// + + +/** + For specifying what conversion options should be executed + */ +public struct ConversionOptions: OptionSet, CustomStringConvertible { + /// The numeric representation of the options + public let rawValue: Int + /** + Initialize with a raw value + + - parameter rawValue: the numeric representation + + - returns: The ConversionOptions + */ + public init(rawValue: Int) { self.rawValue = rawValue } + + /// No conversion options + public static let None = ConversionOptions(rawValue: 0) + /// Execute property converters + public static let PropertyConverter = ConversionOptions(rawValue: 1) + /// Execute property mapping + public static let PropertyMapping = ConversionOptions(rawValue: 2) + /// Skip specific property values + public static let SkipPropertyValue = ConversionOptions(rawValue: 4) + /// Do a key cleanup (CameCase, snake_case) + public static let KeyCleanup = ConversionOptions(rawValue: 8) + /// Execute the decoding function for all values + public static let Decoding = ConversionOptions(rawValue: 16) + /// Execute an encoding function on all values + public static let Encoding = ConversionOptions(rawValue: 32) + + // Just for bein able to show all + public static var All: ConversionOptions = [PropertyConverter, PropertyMapping, SkipPropertyValue, KeyCleanup, Decoding, Encoding] + /// Default used for NSCoding + public static var DefaultNSCoding: ConversionOptions = [None] + /// Default used for comparing / hashing functions + public static var DefaultComparing: ConversionOptions = [PropertyConverter, PropertyMapping, SkipPropertyValue] + /// Default used for deserialization + public static var DefaultDeserialize: ConversionOptions = [PropertyConverter, PropertyMapping, SkipPropertyValue, KeyCleanup, Decoding] + /// Default used for serialization + public static var DefaultSerialize: ConversionOptions = [PropertyConverter, PropertyMapping, SkipPropertyValue, Encoding] + + /// Get a nice description of the ConversionOptions + public var description: String { + let strings = ["PropertyConverter", "PropertyMapping", "SkipPropertyValue", "KeyCleanup", "Decoding", "Encoding"] + var members = [String]() + for (flag, string) in strings.enumerated() where contains(ConversionOptions(rawValue:1<<(flag + 1))) { + members.append(string) + } + if members.count == 0 { + members.append("None") + } + return members.description + } +} diff --git a/Pods/EVReflection/Source/DeserializationStatus.swift b/Pods/EVReflection/Source/DeserializationStatus.swift new file mode 100644 index 0000000..d986ef0 --- /dev/null +++ b/Pods/EVReflection/Source/DeserializationStatus.swift @@ -0,0 +1,53 @@ +// +// DeserializationStatus.swift +// EVReflection +// +// Created by Edwin Vermeer on 9/5/16. +// Copyright © 2015 evict. All rights reserved. +// + +/** + Type of status messages after deserialization + */ +public struct DeserializationStatus: OptionSet, CustomStringConvertible { + /// The numeric representation of the options + public let rawValue: Int + /** + Initialize with a raw value + + - parameter rawValue: the numeric representation + + - returns: the DeserializationStatus + */ + public init(rawValue: Int) { self.rawValue = rawValue } + + /// No status message + public static let None = DeserializationStatus(rawValue: 0) + /// Incorrect key error + public static let IncorrectKey = DeserializationStatus(rawValue: 1) + /// Missing key error + public static let MissingKey = DeserializationStatus(rawValue: 2) + /// Invalid type error + public static let InvalidType = DeserializationStatus(rawValue: 4) + /// Invalid value error + public static let InvalidValue = DeserializationStatus(rawValue: 8) + /// Invalid class error + public static let InvalidClass = DeserializationStatus(rawValue: 16) + /// Missing protocol error + public static let MissingProtocol = DeserializationStatus(rawValue: 32) + /// Custom status message + public static let Custom = DeserializationStatus(rawValue: 64) + + /// Get a nice description of the DeserializationStatus + public var description: String { + let strings = ["IncorrectKey", "MissingKey", "InvalidType", "InvalidValue", "InvalidClass", "MissingProtocol", "Custom"] + var members = [String]() + for (flag, string) in strings.enumerated() where contains(DeserializationStatus(rawValue:1<<(flag))) { + members.append(string) + } + if members.count == 0 { + members.append("None") + } + return members.description + } +} diff --git a/Pods/EVReflection/Source/EVArrayExtension.swift b/Pods/EVReflection/Source/EVArrayExtension.swift new file mode 100755 index 0000000..63b6b3d --- /dev/null +++ b/Pods/EVReflection/Source/EVArrayExtension.swift @@ -0,0 +1,250 @@ +// +// ArrayExtension.swift +// EVReflection +// +// Created by Edwin Vermeer on 9/2/15. +// Copyright © 2015 evict. All rights reserved. +// + +import Foundation + +/** +Extending Array with an some EVReflection functions where the elements can be of type NSObject +*/ +public extension Array where Element: NSObject { + + /** + Initialize an array based on a json string + + - parameter json: The json string + - parameter conversionOptions: Option set for the various conversion options. + */ + public init(json: String?, conversionOptions: ConversionOptions = .DefaultDeserialize, forKeyPath: String? = nil) { + self.init() + let arrayTypeInstance = getArrayTypeInstance(self) + let newArray = EVReflection.arrayFromJson(type: arrayTypeInstance, json: json, conversionOptions: conversionOptions, forKeyPath: forKeyPath) + for item in newArray { + self.append(item) + } + } + + + /** + Initialize an array based on a json string + + - parameter json: The json string + - parameter conversionOptions: Option set for the various conversion options. + */ + public init(data: Data?, conversionOptions: ConversionOptions = .DefaultDeserialize, forKeyPath: String? = nil) { + self.init() + let arrayTypeInstance = getArrayTypeInstance(self) + let newArray = EVReflection.arrayFromData(nil, type:arrayTypeInstance, data: data, conversionOptions: conversionOptions, forKeyPath: forKeyPath) + for item in newArray { + self.append(item) + } + } + + /** + Initialize an array based on a dictionary + + - parameter json: The json string + - parameter conversionOptions: Option set for the various conversion options. + */ + public init(dictionaryArray: [NSDictionary], conversionOptions: ConversionOptions = .DefaultDeserialize) { + self.init() + for item in dictionaryArray { + let arrayTypeInstance = getArrayTypeInstance(self) + EVReflection.setPropertiesfromDictionary(item, anyObject: arrayTypeInstance) + self.append(arrayTypeInstance) + } + } + + /** + Initialize an array based on a dictionary + + - parameter json: The json string + - parameter conversionOptions: Option set for the various conversion options. + */ + public init(dictionary: NSDictionary, forKeyPath: String, conversionOptions: ConversionOptions = .DefaultDeserialize) { + self.init() + + guard let dictionaryArray = dictionary.value(forKeyPath: forKeyPath) as? [NSDictionary] else { + evPrint(.UnknownKeypath, "ERROR: The forKeyPath '\(forKeyPath)' resulted in an empty array") + return + } + + for item in dictionaryArray { + let arrayTypeInstance = getArrayTypeInstance(self) + EVReflection.setPropertiesfromDictionary(item, anyObject: arrayTypeInstance) + self.append(arrayTypeInstance) + } + } + + + /** + Get the type of the object where this array is for + + - parameter arr: this array + + - returns: The object type + */ + public func getArrayTypeInstance(_ arr: Array) -> T { + return arr.getTypeInstance() + } + + /** + Get the type of the object where this array is for + + - returns: The object type + */ + public func getTypeInstance( + ) -> T { + let nsobjectype: NSObject.Type = T.self + let nsobject: NSObject = nsobjectype.init() + if let obj = nsobject as? T { + return obj + } + // Could not instantiate array item instance. + return T() + } + + /** + Get the string representation of the type of the object where this array is for + + - returns: The object type + */ + public func getTypeAsString() -> String { + let item = self.getTypeInstance() + return NSStringFromClass(type(of:item)) + } +} + + +/** + Extending Array with an some EVReflection functions where the elements can be of type EVReflectable + */ +public extension Array where Element: EVReflectable { + /** + Convert this array to a json string + + - parameter conversionOptions: Option set for the various conversion options. + - parameter prettyPrinted: Define if you want enters and indents + + - returns: The json string + */ + public func toJsonString(_ conversionOptions: ConversionOptions = .DefaultSerialize, prettyPrinted: Bool = false) -> String { + return "[\n" + self.map({($0).toJsonString(conversionOptions, prettyPrinted: prettyPrinted)}).joined(separator: ", \n") + "\n]" + } + + /** + Convert this array to a json data + + - parameter conversionOptions: Option set for the various conversion options. + - parameter prettyPrinted: Define if you want enters and indents + - parameter encoding: The string encoding defaulsts to .utf8 + + - returns: The json data + */ + public func toJsonData(_ conversionOptions: ConversionOptions = .DefaultSerialize, prettyPrinted: Bool = false, encoding: String.Encoding = .utf8) -> Data { + return self.toJsonString(conversionOptions, prettyPrinted: prettyPrinted).data(using: encoding) ?? Data() + } + + /** + Returns the dictionary representation of this array. + + - parameter conversionOptions: Option set for the various conversion options. + + - returns: The array of dictionaries + */ + public func toDictionaryArray(_ conversionOptions: ConversionOptions = .DefaultSerialize) -> NSArray { + return self.map({($0).toDictionary(conversionOptions)}) as NSArray + } +} + + +/** + Extending Array with an some EVReflection functions where the elements can be of type NSObject + */ +public extension Array where Element: NSDictionary { + + /** + Initialize a dictionary array based on a json string + + - parameter json: The json string + */ + public init(jsonArray: String) { + self.init() + + let dictArray = EVReflection.dictionaryArrayFromJson(jsonArray) + + for item in dictArray { + self.append(item as! Element) + } + } + + /** + Initialize a dictionary array based on a json string + + - parameter json: The json string + */ + public init(dataArray: Data) { + self.init(jsonArray: String(data: dataArray, encoding: .utf8) ?? "") + } + + /** + Convert this array to a json string + + - parameter conversionOptions: Option set for the various conversion options. + + - returns: The json string + */ + public func toJsonStringArray(prettyPrinted: Bool = false) -> String { + let jsonArray: [String] = self.map { ($0 as NSDictionary).toJsonString(prettyPrinted: prettyPrinted) as String } + return "[\n" + jsonArray.joined(separator: ", \n") + "\n]" + } + +} + +public extension NSArray { + func nestedArrayMap(_ element: (NSDictionary)->T) -> [[T]] { + return (self.map { + (($0 as? NSArray)?.map { + element($0 as? NSDictionary ?? NSDictionary()) + }) ?? [] + }) + } + + func doubleNestedArrayMap(_ element: (NSDictionary)->T) -> [[[T]]] { + return (self.map { + (($0 as? NSArray)?.nestedArrayMap { element($0) }) ?? [[]] + }) + } + + func tripleNestedArrayMap(_ element: (NSDictionary)->T) -> [[[[T]]]] { + return (self.map { + (($0 as? NSArray)?.doubleNestedArrayMap { element($0) }) ?? [[[]]] + }) + } + + func quadrupleNestedArrayMap(_ element: (NSDictionary)->T) -> [[[[[T]]]]] { + return (self.map { + (($0 as? NSArray)?.tripleNestedArrayMap { element($0) }) ?? [[[[]]]] + }) + } + + func quintupleNestedArrayMap(_ element: (NSDictionary)->T) -> [[[[[[T]]]]]] { + return (self.map { + (($0 as? NSArray)?.quadrupleNestedArrayMap { element($0) }) ?? [[[[[]]]]] + }) + } + + func sextupleNestedArrayMap(_ element: (NSDictionary)->T) -> [[[[[[[T]]]]]]] { + return (self.map { + (($0 as? NSArray)?.quintupleNestedArrayMap { element($0) }) ?? [[[[[[]]]]]] + }) + } + + // If you need deeper nesting, whell, then you probably see the pattern above that you need to implement :-) + // just name them septuple, octuple, nonuple and decuple + // I'm not sure how far swift can handle it, but you should not want something like that. +} diff --git a/Pods/EVReflection/Source/EVCustomReflectable.swift b/Pods/EVReflection/Source/EVCustomReflectable.swift new file mode 100644 index 0000000..cc72372 --- /dev/null +++ b/Pods/EVReflection/Source/EVCustomReflectable.swift @@ -0,0 +1,15 @@ +// +// EVCustomReflectable.swift +// EVReflection +// +// Created by Edwin Vermeer on 27/10/2016. +// Copyright © 2016 evict. All rights reserved. +// + +import Foundation + +// Protocol that can be used for sub objects to define that parsing will be done in the parent using the 'setValue forKey' function +public protocol EVCustomReflectable { + func constructWith(value: Any?) -> EVCustomReflectable + func toCodableValue() -> Any +} diff --git a/Pods/EVReflection/Source/EVDictionaryExtension.swift b/Pods/EVReflection/Source/EVDictionaryExtension.swift new file mode 100755 index 0000000..08dc7a7 --- /dev/null +++ b/Pods/EVReflection/Source/EVDictionaryExtension.swift @@ -0,0 +1,88 @@ +// +// DictionaryExtension.swift +// EVReflection +// +// Created by Edwin Vermeer on 9/2/15. +// Copyright © 2015 evict. All rights reserved. +// + +import Foundation + + +/** + Dictionary extension for creating a json strin from an array of enum values + */ +public extension NSMutableDictionary { + + /** + Initialize a Dictionary based on a json string + */ + convenience init(json: String) { + self.init() + let jsonDict = EVReflection.dictionaryFromJson(json) + for (key, value) in jsonDict { + self[key] = value + } + } + + /** + Initialize a Dictionary based on json data + */ + convenience init(data: Data) { + self.init(json: String(data: data, encoding: .utf8) ?? "") + } +} + +public extension NSDictionary { + /** + Create a json string based on this dictionary + + - parameter prettyPrinted: compact of pretty printed + */ + public func toJsonString(prettyPrinted: Bool = false) -> String { + let data = self.toJsonData(prettyPrinted: prettyPrinted) + return String(data: data, encoding: .utf8) ?? "" + } + + /** + Create a json data based on this dictionary + + - parameter prettyPrinted: compact of pretty printed + */ + public func toJsonData(prettyPrinted: Bool = false) -> Data { + do { + if prettyPrinted { + return try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) + } + return try JSONSerialization.data(withJSONObject: self, options: []) + } catch { } + return Data() + } +} + + +public extension NSMutableDictionary { + + /** + Merge a 2nd dictionary into this one + + - parameter dictionary: The 2nd dictionary that will be merged into this one + */ + public func unionInPlace(dictionary: NSDictionary) { + for (key, value) in dictionary { + self[key] = value + } + } + + /** + Merge a sequence into this dictionary + + - parameter dictionary: The sequence that will be merged into this dictionary + */ + public func unionInPlace(sequence: S) where + S.Iterator.Element == (Key,Value) { + for (key, value) in sequence { + self[key] = value + } + } +} diff --git a/Pods/EVReflection/Source/EVObject.swift b/Pods/EVReflection/Source/EVObject.swift new file mode 100755 index 0000000..950d53a --- /dev/null +++ b/Pods/EVReflection/Source/EVObject.swift @@ -0,0 +1,200 @@ +// +// EVObject.swift +// +// Created by Edwin Vermeer on 5/2/15. +// Copyright (c) 2015 evict. All rights reserved. +// + +import Foundation + + +/** + Object that implements EVReflectable and NSCoding. Use this object as your base class + instead of NSObject and you wil automatically have support for all these protocols. + */ +@objcMembers +open class EVObject: NSObject, NSCoding, EVReflectable { + // These are redundant in Swift 2+: CustomDebugStringConvertible, CustomStringConvertible, Hashable, Equatable + + /** + Implementation of the setValue forUndefinedKey so that we can catch exceptions for when we use an optional Type like Int? in our object. Instead of using Int? you should use NSNumber? + + This method is in EVObject and not in NSObject extension because you would get the error: method conflicts with previous declaration with the same Objective-C selector + + - parameter value: The value that you wanted to set + - parameter key: The name of the property that you wanted to set + */ + open override func setValue(_ value: Any!, forUndefinedKey key: String) { + if let kvc = self as? EVGenericsKVC { + kvc.setGenericValue(value as AnyObject?, forUndefinedKey: key) + } else { + self.addStatusMessage(.IncorrectKey, message: "The class '\(EVReflection.swiftStringFromClass(self))' is not key value coding-compliant for the key '\(key)'") + evPrint(.IncorrectKey, "\nWARNING: The class '\(EVReflection.swiftStringFromClass(self))' is not key value coding-compliant for the key '\(key)'\n There is no support for optional type, array of optionals or enum properties.\nAs a workaround you can implement the function 'setValue forUndefinedKey' for this. See the unit tests for more information\n") + + } + } + + /** + Implementation of the NSObject isEqual comparisson method + + This method is in EVObject and not in NSObject extension because you would get the error: method conflicts with previous declaration with the same Objective-C selector + + - parameter object: The object where you want to compare with + + - returns: Returns true if the object is the same otherwise false + */ + + open override func isEqual(_ object: Any?) -> Bool { // for isEqual: + if let obj = object as? EVObject { + return EVReflection.areEqual(self, rhs: obj) + } + return false + } + + /** + Returns the pritty description of this object + + - returns: The pritty description + */ + open override var description: String { + get { + return EVReflection.description(self, prettyPrinted: true) + } + } + + /** + Returns the pritty description of this object + + - returns: The pritty description + */ + open override var debugDescription: String { + get { + return EVReflection.description(self, prettyPrinted: true) + } + } + + /** + This basic init override is needed so we can use EVObject as a base class. + */ + public required override init() { + super.init() + } + + /** + Decode any object + + This method is in EVObject and not in NSObject because you would get the error: Initializer requirement 'init(coder:)' can + only be satisfied by a `required` initializer in the definition of non-final class 'NSObject' + + -parameter coder: The NSCoder that will be used for decoding the object. + */ + public convenience required init?(coder: NSCoder) { + self.init() + EVReflection.decodeObjectWithCoder(self, aDecoder: coder, conversionOptions: .DefaultNSCoding) + } + + + /** + Encode this object using a NSCoder + + - parameter aCoder: The NSCoder that will be used for encoding the object + */ + open func encode(with aCoder: NSCoder) { + EVReflection.encodeWithCoder(self , aCoder: aCoder, conversionOptions: .DefaultNSCoding) + } + + + //MARK - Default implementation of protocol functions that we can override + + + /** + By default there is no aditional validation. Override this function to add your own class level validation rules + + - parameter dict: The dictionary with keys where the initialisation is called with + */ + open func initValidation(_ dict: NSDictionary) { + } + + /** + Override this method when you want custom property mapping. + + This method is in EVObject and not in extension of NSObject because a functions from extensions cannot be overwritten yet + + - returns: Return an array with value pairs of the object property name and json key name. + */ + open func propertyMapping() -> [(keyInObject: String?, keyInResource: String?)] { + return [] + } + + /** + Override this method when you want custom property value conversion + + This method is in EVObject and not in extension of NSObject because a functions from extensions cannot be overwritten yet + + - returns: Returns an array where each item is a combination of the folowing 3 values: A string for the property name where the custom conversion is for, a setter function and a getter function. + */ + open func propertyConverters() -> [(key: String, decodeConverter: ((Any?)->()), encodeConverter: (() -> Any?))] { + return [] + } + + /** + You can add general value decoding to an object when you implement this function. You can for instance use it to base64 decode, url decode, html decode, unicode, etc. + + - parameter value: The value that we will be decoded + - parameter key: The key for the value + + - returns: The decoded value + */ + open func decodePropertyValue(value: Any, key: String) -> Any? { + return value + } + + /** + You can add general value encoding to an object when you implement this function. You can for instance use it to base64 encode, url encode, html encode, unicode, etc. + + - parameter value: The value that we will be encoded + - parameter key: The key for the value + + - returns: The encoded value. + */ + open func encodePropertyValue(value: Any, key: String) -> Any { + return value + } + + /** + This is a general functon where you can filter for specific values (like nil or empty string) when creating a dictionary + + - parameter value: The value that we will test + - parameter key: The key for the value + + - returns: True if the value needs to be ignored. + */ + open func skipPropertyValue(_ value: Any, key: String) -> Bool { + return false + } + + /** + When a property is declared as a base type for multiple inherited classes, then this function will let you pick the right specific type based on the suplied dictionary. + + - parameter dict: The dictionary for the specific type + + - returns: The specific type + */ + open func getSpecificType(_ dict: NSDictionary) -> EVReflectable? { + return nil + } + + + /** + Return a custom object for the object + + - returns: The custom object (single value, dictionary or array) + */ + open func customConverter() -> AnyObject? { + return nil + } + +} + + + diff --git a/Pods/EVReflection/Source/EVReflectable.swift b/Pods/EVReflection/Source/EVReflectable.swift new file mode 100755 index 0000000..83de69e --- /dev/null +++ b/Pods/EVReflection/Source/EVReflectable.swift @@ -0,0 +1,639 @@ +// +// EVReflectable.swift +// EVReflection +// +// Created by Edwin Vermeer on 27/10/2016. +// Copyright © 2016 evict. All rights reserved. +// + +import Foundation + +// MARK: - Protocol with the overridable functions. All functionality is added to this in the extension below. +public protocol EVReflectable: class, NSObjectProtocol { + /** + By default there is no aditional validation. Override this function to add your own class level validation rules + + - parameter dict: The dictionary with keys where the initialisation is called with + */ + func initValidation(_ dict: NSDictionary) + + /** + Override this method when you want custom property mapping. + + This method is in EVObject and not in extension of NSObject because a functions from extensions cannot be overwritten yet + + - returns: Return an array with value pairs of the object property name and json key name. + */ + func propertyMapping() -> [(keyInObject: String?, keyInResource: String?)] + + /** + Override this method when you want custom property value conversion + + This method is in EVObject and not in extension of NSObject because a functions from extensions cannot be overwritten yet + + - returns: Returns an array where each item is a combination of the folowing 3 values: A string for the property name where the custom conversion is for, a setter function and a getter function. + */ + func propertyConverters() -> [(key: String, decodeConverter: ((Any?)->()), encodeConverter: (() -> Any?))] + + /** + This is a general functon where you can filter for specific values (like nil or empty string) when creating a dictionary + + - parameter value: The value that we will test + - parameter key: The key for the value + + - returns: True if the value needs to be ignored. + */ + func skipPropertyValue(_ value: Any, key: String) -> Bool + + /** + You can add general value decoding to an object when you implement this function. You can for instance use it to base64 decode, url decode, html decode, unicode, etc. + + - parameter value: The value that we will be decoded + - parameter key: The key for the value + + - returns: The decoded value + */ + func decodePropertyValue(value: Any, key: String) -> Any? + + /** + You can add general value encoding to an object when you implement this function. You can for instance use it to base64 encode, url encode, html encode, unicode, etc. + + - parameter value: The value that we will be encoded + - parameter key: The key for the value + + - returns: The encoded value. + */ + func encodePropertyValue(value: Any, key: String) -> Any + + /** + Get the type of this object. + + - parameter dict: The dictionary for the specific type + + - returns: The specific type + */ + func getType(_ dict: NSDictionary) -> EVReflectable + + /** + When a property is declared as a base type for multiple inherited classes, then this function will let you pick the right specific type based on the suplied dictionary. + + - parameter dict: The dictionary for the specific type + + - returns: The specific type + */ + func getSpecificType(_ dict: NSDictionary) -> EVReflectable? + + /** + Return a custom object for the object + + - returns: The custom object that will be parsed (single value, dictionary or array) + */ + func customConverter() -> AnyObject? + + /** + Declaration for Equatable == + + - parameter lhs: The object at the left side of the == + - parameter rhs: The object at the right side of the == + + - returns: True if the objects are the same, otherwise false. + */ + static func ==(lhs: EVReflectable, rhs: EVReflectable) -> Bool + + /** + Delclaration for Equatable != + + - parameter lhs: The object at the left side of the == + - parameter rhs: The object at the right side of the == + + - returns: False if the objects are the the same, otherwise true. + */ + static func !=(lhs: EVReflectable, rhs: EVReflectable) -> Bool + + /** + Protocol container property for the reflection statusses + */ + var evReflectionStatuses: [(DeserializationStatus, String)] { get set } +} + + +// MARK: - extending EVReflectable with the initialisation functions (which need NSObject) + +var EVReflectableStatusesObjectKey = "EVReflectableStatuses" +extension EVReflectable where Self: NSObject { + /** + Trick for storing a property in a protocol only + */ + public var evReflectionStatuses: [(DeserializationStatus, String)] { + get { + var statuses: [(DeserializationStatus, String)]? = objc_getAssociatedObject(self, &EVReflectableStatusesObjectKey) as? [(DeserializationStatus, String)] + if let statuses = statuses { + return statuses + } else { + statuses = [(DeserializationStatus, String)]() + objc_setAssociatedObject(self, &EVReflectableStatusesObjectKey, statuses, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) + return statuses! + } + } + set { + objc_setAssociatedObject(self, &EVReflectableStatusesObjectKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) + } + } + + + /** + init for creating an object whith the property values of a dictionary. + + - parameter dictionary: The dictionary that will be used to create this object + - parameter conversionOptions: Option set for the various conversion options. + */ + public init(dictionary: NSDictionary, conversionOptions: ConversionOptions = .DefaultDeserialize, forKeyPath: String? = nil) { + self.init() + if let v = self as? EVCustomReflectable { + let _ = v.constructWith(value: dictionary) + } else { + EVReflection.setPropertiesfromDictionary(dictionary, anyObject: self, conversionOptions: conversionOptions, forKeyPath: forKeyPath) + } + } + + /** + init for creating an object whith the contents of a json string. + + - parameter json: The json string that will be used to create this object + - parameter conversionOptions: Option set for the various conversion options. + */ + public init(json: String?, conversionOptions: ConversionOptions = .DefaultDeserialize, forKeyPath: String? = nil) { + self.init() + let dictionary = EVReflection.dictionaryFromJson(json) + if let v = self as? EVCustomReflectable { + let _ = v.constructWith(value: dictionary) + } else { + EVReflection.setPropertiesfromDictionary(dictionary, anyObject: self, conversionOptions: conversionOptions, forKeyPath: forKeyPath) + } + } + + /** + init for creating an object whith the property values of json Data. + + - parameter dictionary: The dictionary that will be used to create this object + - parameter conversionOptions: Option set for the various conversion options. + */ + public init(data: Data, conversionOptions: ConversionOptions = .DefaultDeserialize, forKeyPath: String? = nil) { + self.init() + let dictionary: NSDictionary = (((try! JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary)) ?? NSDictionary())! + if let v = self as? EVCustomReflectable { + let _ = v.constructWith(value: dictionary) + } else { + EVReflection.setPropertiesfromDictionary(dictionary, anyObject: self, conversionOptions: conversionOptions, forKeyPath: forKeyPath) + } + } + + + /** + Initialize this object from an archived file from the temp directory + + - parameter fileNameInTemp: The filename + - parameter conversionOptions: Option set for the various conversion options. + */ + public init(fileNameInTemp: String, conversionOptions: ConversionOptions = .DefaultNSCoding) { + self.init() + let filePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(fileNameInTemp) + if let temp = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? EVReflectable { + if let v = self as? EVCustomReflectable { + let dictionary = temp.toDictionary(conversionOptions) + let _ = v.constructWith(value: dictionary) + } else { + EVReflection.setPropertiesfromDictionary( temp.toDictionary(conversionOptions), anyObject: self, conversionOptions: conversionOptions) + } + } + } + + /** + Initialize this object from an archived file from the documents directory + + - parameter fileNameInDocuments: The filename + - parameter conversionOptions: Option set for the various conversion options. + */ + public init(fileNameInDocuments: String, conversionOptions: ConversionOptions = .DefaultNSCoding) { + self.init() + let filePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(fileNameInDocuments) + if let temp = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? EVReflectable { + if let v = self as? EVCustomReflectable { + let dictionary = temp.toDictionary(conversionOptions) + let _ = v.constructWith(value: dictionary) + } else { + EVReflection.setPropertiesfromDictionary( temp.toDictionary(conversionOptions), anyObject: self, conversionOptions: conversionOptions) + } + } + } + + /** + init for creating an object whith the property values of an other object. + + - parameter usingValuesFrom: The object of whicht the values will be used to create this object + - parameter conversionOptions: Option set for the various conversion options. + */ + public init(usingValuesFrom: EVReflectable, conversionOptions: ConversionOptions = .None) { + self.init() + let dict = usingValuesFrom.toDictionary() + if let v = self as? EVCustomReflectable { + let _ = v.constructWith(value: dict) + } else { + EVReflection.setPropertiesfromDictionary(dict, anyObject: self, conversionOptions: conversionOptions) + } + + } + + /** + Returns the hashvalue of this object + + - returns: The hashvalue of this object + */ + public var hashValue: Int { + get { + return Int(EVReflection.hashValue(self)) + } + } + + /** + Function for returning the hash for the NSObject based functionality + + - returns: The hashvalue of this object + */ + public var hash: Int { + get { + return self.hashValue + } + } + +} + + +// MARK: - extending EVReflectable with most of EVReflection functionality + + +extension EVReflectable { + /** + Implementation for Equatable == + + - parameter lhs: The object at the left side of the == + - parameter rhs: The object at the right side of the == + + - returns: True if the objects are the same, otherwise false. + */ + static public func == (lhs: EVReflectable, rhs: EVReflectable) -> Bool { + if let lhso = lhs as? NSObject, let rhso = rhs as? NSObject { + return EVReflection.areEqual(lhso, rhs: rhso) + } + return lhs.isEqual(rhs) + } + + /** + Implementation for Equatable != + + - parameter lhs: The object at the left side of the == + - parameter rhs: The object at the right side of the == + + - returns: False if the objects are the the same, otherwise true. + */ + static public func != (lhs: EVReflectable, rhs: EVReflectable) -> Bool { + if let lhso = lhs as? NSObject, let rhso = rhs as? NSObject { + return !EVReflection.areEqual(lhso, rhs: rhso) + } + return !lhs.isEqual(rhs) + } + + // MARK: - extending the base implementation for the overridable functions + + + /** + By default there is no aditional validation. Override this function to add your own class level validation rules + + - parameter dict: The dictionary with keys where the initialisation is called with + */ + public func initValidation(_ dict: NSDictionary) { + } + + /** + Override this method when you want custom property mapping. + + This method is in EVObject and not in extension of NSObject because a functions from extensions cannot be overwritten yet + + - returns: Return an array with value pairs of the object property name and json key name. + */ + public func propertyMapping() -> [(keyInObject: String?, keyInResource: String?)] { + return [] + } + + /** + Override this method when you want custom property value conversion + + This method is in EVObject and not in extension of NSObject because a functions from extensions cannot be overwritten yet + + - returns: Returns an array where each item is a combination of the folowing 3 values: A string for the property name where the custom conversion is for, a setter function and a getter function. + */ + public func propertyConverters() -> [(key: String, decodeConverter: ((Any?)->()), encodeConverter: (() -> Any?))] { + return [] + } + + /** + This is a general functon where you can filter for specific values (like nil or empty string) when creating a dictionary + + - parameter value: The value that we will test + - parameter key: The key for the value + + - returns: True if the value needs to be ignored. + */ + public func skipPropertyValue(_ value: Any, key: String) -> Bool { + return false + } + + /** + You can add general value decoding to an object when you implement this function. You can for instance use it to base64 decode, url decode, html decode, unicode, etc. + + - parameter value: The value that we will be decoded + - parameter key: The key for the value + + - returns: The decoded value + */ + public func decodePropertyValue(value: Any, key: String) -> Any? { + return value + } + + /** + You can add general value encoding to an object when you implement this function. You can for instance use it to base64 encode, url encode, html encode, unicode, etc. + + - parameter value: The value that we will be encoded + - parameter key: The key for the value + + - returns: The encoded value. + */ + public func encodePropertyValue(value: Any, key: String) -> Any { + return value + } + + /** + Return a custom object for the object + + - returns: The custom object that will be parsed (single value, dictionary or array) + */ + public func customConverter() -> AnyObject? { + return nil + } + + /** + Get the type of this object + + - parameter dict: The dictionary for the specific type + + - returns: The specific type + */ + public func getType(_ dict: NSDictionary) -> EVReflectable { + return self + } + + /** + When a property is declared as a base type for multiple inherited classes, then this function will let you pick the right specific type based on the suplied dictionary. + + - parameter dict: The dictionary for the specific type + + - returns: The specific type + */ + public func getSpecificType(_ dict: NSDictionary) -> EVReflectable? { + return nil + } + + // MARK: - extension methods + + + /** + Save this object to a file in the temp directory + + - parameter fileName: The filename + + - returns: Nothing + */ + @discardableResult + public func saveToTemp(_ fileName: String) -> Bool { + let filePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(fileName) + return NSKeyedArchiver.archiveRootObject(self, toFile: filePath) + } + + + + #if os(tvOS) + // Save to documents folder is not supported on tvOS + #else + /** + Save this object to a file in the documents directory + + - parameter fileName: The filename + + - returns: true if successfull + */ + @discardableResult + public func saveToDocuments(_ fileName: String) -> Bool { + let filePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(fileName) + return NSKeyedArchiver.archiveRootObject(self, toFile: filePath) + } + #endif + + + /** + Returns the dictionary representation of this object. + + - parameter conversionOptions: Option set for the various conversion options. + + - returns: The dictionary + */ + public func toDictionary(_ conversionOptions: ConversionOptions = .DefaultSerialize) -> NSDictionary { + if let obj = self as? NSObject { + let (reflected, _) = EVReflection.toDictionary(obj, conversionOptions: conversionOptions) + return reflected + } + evPrint(.ShouldExtendNSObject, "ERROR: You should only extend object with EVReflectable that are derived from NSObject!") + return NSDictionary() + } + + /** + Convert this object to a json string + + - parameter conversionOptions: Option set for the various conversion options. + + - returns: The json string + */ + public func toJsonString(_ conversionOptions: ConversionOptions = .DefaultSerialize, prettyPrinted: Bool = false) -> String { + let data = self.toJsonData(conversionOptions, prettyPrinted: prettyPrinted) + return String(data: data, encoding: .utf8) ?? "{}" + } + + /** + Convert this object to a json Data + + - parameter conversionOptions: Option set for the various conversion options. + + - returns: The json Data + */ + public func toJsonData(_ conversionOptions: ConversionOptions = .DefaultSerialize, prettyPrinted: Bool = false) -> Data { + var dict: NSDictionary + + // Custom or standard toDictionary + if let v = self as? EVCustomReflectable { + dict = v.toCodableValue() as? NSDictionary ?? NSDictionary() + } else { + dict = self.toDictionary(conversionOptions) + } + + if let v = self as? NSObject { + dict = EVReflection.convertDictionaryForJsonSerialization(dict, theObject: v) + } + + do { + if prettyPrinted { + return try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) + } + return try JSONSerialization.data(withJSONObject: dict, options: []) + } catch { } + return Data() + } + + + /** + method for instantiating an array from a json string. + + - parameter json: The json string + - parameter conversionOptions: Option set for the various conversion options. + + - returns: An array of objects + */ + public static func arrayFromJson(_ json: String?, conversionOptions: ConversionOptions = .DefaultDeserialize) -> [T] where T:NSObject { + return EVReflection.arrayFromJson(type: T(), json: json, conversionOptions: conversionOptions) + } + + /** + Auto map an opbject to an object of an other type. + Properties with the same name will be mapped automattically. + Automattic cammpelCase, PascalCase, snake_case conversion + Supports propperty mapping and conversion when using EVReflectable as a protocol + + - parameter conversionOptions: Option set for the various conversion options. + + - returns: The targe object with the mapped values + */ + public func mapObjectTo(_ conversionOptions: ConversionOptions = .DefaultDeserialize) -> T where T:NSObject { + let nsobjectype: NSObject.Type = T.self as NSObject.Type + let nsobject: NSObject = nsobjectype.init() + let dict = self.toDictionary() + let result = EVReflection.setPropertiesfromDictionary(dict, anyObject: nsobject, conversionOptions: conversionOptions) + return result as? T ?? T() + } + + /** + Get the type for a given property name or `nil` if there aren't any properties matching said name. + + - parameter propertyName: The property name + + - returns: The type for the property + */ + public func typeForKey(_ propertyName: String) -> Any.Type? { + let mirror = Mirror(reflecting: self) + return typeForKey(propertyName, mirror: mirror) + } + + /** + get the type of a property + + - parameter propertyName: The property key + - parameter mirror: The mirror of this object + + - returns: The type of the property + */ + fileprivate func typeForKey(_ propertyName: String, mirror: Mirror) -> Any.Type? { + for (label, value) in mirror.children { + if propertyName == label { + return Mirror(reflecting: value).subjectType + } + } + + guard let superclassMirror = mirror.superclassMirror else { + return nil + } + + return typeForKey(propertyName, mirror: superclassMirror) + } + + + /** + Convert a Swift dictionary to a NSDictionary. + + - parameter key: Key of the property that is the dictionary. Can be used when overriding this function + - parameter dict: The Swift dictionary + + - returns: The dictionary converted to a NSDictionary + */ + public func convertDictionary(_ key: String, dict: Any) -> NSDictionary { + let returnDict = NSMutableDictionary() + for (key, value) in dict as? NSDictionary ?? NSDictionary() { + returnDict[key as? String ?? ""] = value + } + return returnDict + } + + + // MARK: - extending serialization status functions + + + /** + Validation function that you will probably call from the initValidation function. This function will make sure + the passed on keys are not in the dictionary used for initialisation. + The result of this validation is stored in evReflectionStatus. + + - parameter keys: The fields that may not be in the dictionary (like an error key) + - parameter dict: The dictionary that is passed on from the initValidation function + */ + public func initMayNotContainKeys(_ keys: [String], dict: NSDictionary) { + for key in keys { + if dict[key] != nil { + addStatusMessage(.IncorrectKey, message: "Invalid key: \(key)") + } + } + } + + /** + Validation function that you will probably call from the initValidation function. This function will make sure + the passed on keys are in the dictionary used for initialisation. + The result of this validation is stored in evReflectionStatus. + + - parameter keys: The fields that may not be in the dictionary (like an error key) + - parameter dict: The dictionary that is passed on from the initValidation function + */ + public func initMustContainKeys(_ keys: [String], dict: NSDictionary) { + for key in keys { + if dict[key] == nil { + addStatusMessage(.MissingKey, message: "Missing key: \(key)") + } + } + } + /** + Return a merged status out of the status array + + - returns: the deserialization status for the object + */ + public func evReflectionStatus() -> DeserializationStatus { + var status: DeserializationStatus = .None + for (s, _) in self.evReflectionStatuses { + status = [status, s] + } + return status + } + + /** + function for adding a new status message to the evReflectionStatus array + + - parameter type: A string to specify the message type + - parameter message: The message for the status. + */ + public func addStatusMessage(_ type: DeserializationStatus, message: String) { + self.evReflectionStatuses.append((type, message)) + } +} diff --git a/Pods/EVReflection/Source/EVReflection.swift b/Pods/EVReflection/Source/EVReflection.swift new file mode 100755 index 0000000..298cdb6 --- /dev/null +++ b/Pods/EVReflection/Source/EVReflection.swift @@ -0,0 +1,1597 @@ +// +// EVReflection.swift +// +// Created by Edwin Vermeer on 28-09-14. +// Copyright (c) 2014 EVICT BV. All rights reserved. +// + +import Foundation + + +/** + Reflection methods + */ +final public class EVReflection { + + // MARK: - From and to Dictrionary parsing + + + /** + Create an object from a dictionary + + - parameter dictionary: The dictionary that will be converted to an object + - parameter anyobjectTypeString: The string representation of the object type that will be created + - parameter conversionOptions: Option set for the various conversion options. + + - returns: The object that is created from the dictionary + */ + public class func fromDictionary(_ dictionary: NSDictionary, anyobjectTypeString: String, conversionOptions: ConversionOptions = .DefaultDeserialize) -> NSObject? { + if var nsobject = swiftClassFromString(anyobjectTypeString) { + if let evResult = nsobject as? EVReflectable { + if let type = evResult.getType(dictionary) as? NSObject { + nsobject = type + } + if let specific = evResult.getSpecificType(dictionary) as? NSObject { + nsobject = specific + } else if let evResult = nsobject as? EVGenericsKVC { + nsobject = evResult.getGenericType() + } + } + nsobject = setPropertiesfromDictionary(dictionary, anyObject: nsobject, conversionOptions: conversionOptions) + return nsobject + } + return nil + } + + + /** + Set object properties from a dictionary + + - parameter dictionary: The dictionary that will be converted to an object + - parameter anyObject: The object where the properties will be set + - parameter conversionOptions: Option set for the various conversion options. + + - returns: The object that is created from the dictionary + */ + @discardableResult + public class func setPropertiesfromDictionary(_ dictionary: NSDictionary, anyObject: T, conversionOptions: ConversionOptions = .DefaultDeserialize, forKeyPath: String? = nil) -> T where T: NSObject { + + guard let dict = ((forKeyPath == nil) ? dictionary : dictionary.value(forKeyPath: forKeyPath!) as? NSDictionary) else { + evPrint(.UnknownKeypath, "ERROR: The forKeyPath '\(forKeyPath ?? "")' did not return a dictionary") + return anyObject + } + + (anyObject as? EVReflectable)?.initValidation(dict) + let (keyMapping, _, types) = getKeyMapping(anyObject, dictionary: dict, conversionOptions: .None) + for (k, v) in dict { + let keyInObject: String? = (keyMapping.first { $0.keyInResource == k as? String })?.keyInObject + if keyInObject != nil { + let original: Any? = getValue(anyObject, key: keyInObject!) + let dictKey: String = cleanupKey(anyObject, key: k as? String ?? "", tryMatch: types) ?? "" + let valid : Bool + let dictValue : Any? + + if conversionOptions.contains(.PropertyConverter) && (anyObject as? EVReflectable)?.propertyConverters().filter({$0.key == keyInObject}).first != nil { + valid = false + dictValue = nil + } else { + (dictValue, valid) = dictionaryAndArrayConversion(anyObject, key: keyInObject!, fieldType: types[dictKey] as? String ?? types[keyInObject!] as? String, original: original, theDictValue: v as Any?, conversionOptions: conversionOptions) + } + + if let value: Any = valid ? dictValue : (v as Any) { + if var custom = original as? EVCustomReflectable { + custom = custom.constructWith(value: value) + } + setObjectValue(anyObject, key: keyInObject!, theValue: value, typeInObject: types[keyInObject!] as? String, valid: valid, conversionOptions: conversionOptions) + } + } + } + return anyObject + } + + public class func getValue(_ fromObject: NSObject, key: String) -> Any? { + return (Mirror(reflecting: fromObject).children.filter({$0.0 == key}).first)?.value + } + + /** + Based on an object and a dictionary create a keymapping plus a dictionary of properties plus a dictionary of types + + - parameter anyObject: the object for the mapping + - parameter dictionary: the dictionary that has to be mapped + - parameter conversionOptions: Option set for the various conversion options. + + - returns: The mapping, keys and values of all properties to items in a dictionary + */ + fileprivate static func getKeyMapping(_ anyObject: T, dictionary: NSDictionary, conversionOptions: ConversionOptions = .DefaultDeserialize) -> (keyMapping: [(keyInObject: String?, keyInResource: String?)], properties: NSDictionary, types: NSDictionary) where T: NSObject { + let (properties, types) = toDictionary(anyObject, conversionOptions: conversionOptions, isCachable: true) + var keyMapping: [(keyInObject: String?, keyInResource: String?)] = [] + if let reflectable = anyObject as? EVReflectable { + keyMapping = reflectable.propertyMapping() + } + // Add the mapping from the keys in the object. + for (objectKey, _) in properties { + if (keyMapping.first { $0.keyInObject == objectKey as? String }) == nil { + if let dictKey = cleanupKey(anyObject, key: objectKey as? String ?? "", tryMatch: dictionary) { + keyMapping.append((objectKey as? String, dictKey)) + } else { + keyMapping.append((objectKey as? String, objectKey as? String)) + } + } + } + // Also add the unknown mapping, these have to be handled in setValue forUndefinedKey + for item in dictionary { + var isAdded = false + if (keyMapping.first { $0.keyInResource == (item.key as? String ?? "") }) == nil { + if let reflectable = anyObject as? EVReflectable { + if let mapping = reflectable.propertyMapping().filter({$0.keyInResource == item.key as? String}).first { + keyMapping.append(mapping) + isAdded = true + } + } + if !isAdded { + keyMapping.append((item.key as? String, item.key as? String)) + } + } + } + return (keyMapping, properties, types) + } + + + fileprivate static let properiesCache = NSCache() + fileprivate static let typesCache = NSCache() + + /** + Convert an object to a dictionary while cleaning up the keys + + - parameter theObject: The object that will be converted to a dictionary + - parameter conversionOptions: Option set for the various conversion options. + + - returns: The dictionary that is created from theObject plus a dictionary of propery types. + */ + public class func toDictionary(_ theObject: NSObject, conversionOptions: ConversionOptions = .DefaultSerialize, isCachable: Bool = false, parents: [NSObject] = []) -> (NSDictionary, NSDictionary) { + var pdict: NSDictionary? + var tdict: NSDictionary? + + var i = 1 + for parent in parents { + if parent === theObject { + pdict = NSMutableDictionary() + pdict!.setValue("\(i)", forKey: "_EVReflection_parent_") + tdict = NSMutableDictionary() + tdict!.setValue("NSString", forKey: "_EVReflection_parent_") + return (pdict!, tdict!) + } + i = i + 1 + } + var theParents = parents + theParents.append(theObject) + + var p: NSDictionary = NSDictionary() + var t: NSDictionary = NSDictionary() + let key: NSString = "\(swiftStringFromClass(theObject)).\(conversionOptions.rawValue)" as NSString + if isCachable, let cachedVersionProperty = properiesCache.object(forKey: key), let cachedVersionTypes = typesCache.object(forKey: key) { + p = cachedVersionProperty + t = cachedVersionTypes + } else { + let reflected = Mirror(reflecting: theObject) + var (properties, types) = reflectedSub(theObject, reflected: reflected, conversionOptions: conversionOptions, isCachable: isCachable, parents: theParents) + if conversionOptions.contains(.KeyCleanup) { + (properties, types) = cleanupKeysAndValues(theObject, properties:properties, types:types) + } + p = properties + t = types + if isCachable { + properiesCache.setObject(p, forKey: key) + typesCache.setObject(t, forKey: key) + } + } + return (p, t) + } + + + // MARK: - From and to JSON parsing + + /** + Return a dictionary representation for the json string + + - parameter json: The json string that will be converted + + - returns: The dictionary representation of the json + */ + public class func dictionaryFromJson(_ json: String?) -> NSDictionary { + let result = NSMutableDictionary() + if json == nil { + evPrint(.IsInvalidJson, "ERROR: nil is not valid json!") + } else if let jsonData = json!.data(using: String.Encoding.utf8) { + do { + if let jsonDic = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary { + return jsonDic + } + } catch { + evPrint(.IsInvalidJson, "ERROR: Invalid json! \(error.localizedDescription)") + } + } + + return result + } + + /** + Return an array of dictionaries as the representation for the json string + + - parameter json: The json string that will be converted + + - returns: The dictionary representation of the json + */ + public class func dictionaryArrayFromJson(_ json: String?) -> [NSDictionary] { + let result = [NSDictionary]() + if json == nil { + evPrint(.IsInvalidJson, "ERROR: nil is not valid json!") + } else if let jsonData = json!.data(using: String.Encoding.utf8) { + do { + if let jsonDic = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as? [NSDictionary] { + return jsonDic + } + } catch { + evPrint(.IsInvalidJson, "ERROR: Invalid json! \(error.localizedDescription)") + } + } + + return result + } + + + /** + Return an array representation for the json string + + - parameter type: An instance of the type where the array will be created of. + - parameter json: The json string that will be converted + - parameter conversionOptions: Option set for the various conversion options. + + - returns: The array of dictionaries representation of the json + */ + public class func arrayFromData(_ theObject: NSObject? = nil, type: T, data: Data?, conversionOptions: ConversionOptions = .DefaultDeserialize, forKeyPath: String? = nil) -> [T] { + var result = [T]() + if data == nil { + evPrint(.IsInvalidJson, "ERROR: json data is nil!") + return result + } + + do { + var serialized = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) + if serialized is NSDictionary { + if forKeyPath == nil { + evPrint(.IsInvalidJson, "ERROR: The root of the json is an object and not an array. Specify a forKeyPath to get an item as an array") + return result + } else { + serialized = (serialized as! NSDictionary).value(forKeyPath: forKeyPath!) as? [NSDictionary] ?? [] + } + } + + if let jsonDic: [Dictionary] = serialized as? [Dictionary] { + let nsobjectype: NSObject.Type? = T.self as? NSObject.Type + if nsobjectype == nil { + evPrint(.ShouldExtendNSObject, "ERROR: EVReflection can only be used with types with NSObject as it's minimal base type") + return result + } + result = jsonDic.map({ + let nsobject: NSObject = nsobjectype!.init() + return (setPropertiesfromDictionary($0 as NSDictionary, anyObject: nsobject, conversionOptions: conversionOptions) as? T)! + }) + } + } catch { + evPrint(.IsInvalidJson, "ERROR: Invalid json! \(error.localizedDescription)") + } + return result + } + + /** + Return an array representation for the json string + + - parameter type: An instance of the type where the array will be created of. + - parameter json: The json string that will be converted + - parameter conversionOptions: Option set for the various conversion options. + + - returns: The array of dictionaries representation of the json + */ + public class func arrayFromJson(type: T, json: String?, conversionOptions: ConversionOptions = .DefaultDeserialize, forKeyPath: String? = nil) -> [T] { + let result = [T]() + if json == nil { + evPrint(.IsInvalidJson, "ERROR: nil is not valid json!") + return result + } + guard let data = json!.data(using: String.Encoding.utf8) else { + evPrint(.IsInvalidJson, "ERROR: Could not get Data from json string using utf8 encoding") + return result + } + return arrayFromData(type: type, data: data, conversionOptions: conversionOptions, forKeyPath: forKeyPath) + } + + /** + Return a Json string representation of this object + + - parameter theObject: The object that will be loged + - parameter conversionOptions: Option set for the various conversion options. + + - returns: The string representation of the object + */ + public class func toJsonString(_ theObject: NSObject, conversionOptions: ConversionOptions = .DefaultSerialize, prettyPrinted: Bool = false) -> String { + let data = toJsonData(theObject, conversionOptions: conversionOptions, prettyPrinted: prettyPrinted) + return String(data: data, encoding: .utf8) ?? "" + } + + /** + Return a Json Data representation of this object + + - parameter theObject: The object that will be loged + - parameter conversionOptions: Option set for the various conversion options. + + - returns: The Data representation of the object + */ + public class func toJsonData(_ theObject: NSObject, conversionOptions: ConversionOptions = .DefaultSerialize, prettyPrinted: Bool = false) -> Data { + var dict: NSDictionary + + // Custom or standard toDictionary + if let v = theObject as? EVCustomReflectable { + dict = v.toCodableValue() as? NSDictionary ?? NSDictionary() + } else { + let (dictionary, _) = EVReflection.toDictionary(theObject, conversionOptions: conversionOptions) + dict = dictionary + } + + dict = convertDictionaryForJsonSerialization(dict, theObject: theObject) + do { + if prettyPrinted { + return try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) + } + return try JSONSerialization.data(withJSONObject: dict, options: []) + } catch { } + return Data() + } + + + + // MARK: - Adding functionality to objects + + /** + Dump the content of this object to the output + + - parameter theObject: The object that will be loged + */ + public class func logObject(_ theObject: EVReflectable, prettyPrinted: Bool = true) { + NSLog(description(theObject, prettyPrinted: prettyPrinted)) + } + + /** + Return a string representation of this object + + - parameter theObject: The object that will be loged + - parameter conversionOptions: Option set for the various conversion options. + + - returns: The string representation of the object + */ + public class func description(_ theObject: EVReflectable, conversionOptions: ConversionOptions = .DefaultSerialize, prettyPrinted: Bool = true) -> String { + if let obj = theObject as? NSObject { + return "\(swiftStringFromClass(obj)) = \(theObject.toJsonString(prettyPrinted: prettyPrinted))" + } + evPrint(.ShouldExtendNSObject, "ERROR: \(String(reflecting: theObject)) should have NSObject as it's base type.") + return "\(String(reflecting: theObject))" + } + + + /** + Create a hashvalue for the object + + - parameter theObject: The object for what you want a hashvalue + + - returns: the hashvalue for the object + */ + public class func hashValue(_ theObject: NSObject) -> Int { + let (hasKeys, _) = toDictionary(theObject, conversionOptions: .DefaultComparing) + return Int(hasKeys.map {$1}.reduce(0) {(31 &* $0) &+ ($1 as AnyObject).hash}) + } + + + /** + Encode any object + + - parameter theObject: The object that we want to encode. + - parameter aCoder: The NSCoder that will be used for encoding the object. + - parameter conversionOptions: Option set for the various conversion options. + */ + public class func encodeWithCoder(_ theObject: NSObject, aCoder: NSCoder, conversionOptions: ConversionOptions = .DefaultNSCoding) { + let (hasKeys, _) = toDictionary(theObject, conversionOptions: conversionOptions) + for (key, value) in hasKeys { + aCoder.encode(value, forKey: key as? String ?? "") + } + } + + /** + Decode any object + + - parameter theObject: The object that we want to decode. + - parameter aDecoder: The NSCoder that will be used for decoding the object. + - parameter conversionOptions: Option set for the various conversion options. + */ + public class func decodeObjectWithCoder(_ theObject: NSObject, aDecoder: NSCoder, conversionOptions: ConversionOptions = .DefaultNSCoding) { + let (hasKeys, _) = toDictionary(theObject, conversionOptions: conversionOptions, isCachable: true) + let dict = NSMutableDictionary() + for (key, _) in hasKeys { + if aDecoder.containsValue(forKey: (key as? String)!) { + let newValue: AnyObject? = aDecoder.decodeObject(forKey: (key as? String)!) as AnyObject? + if !(newValue is NSNull) { + dict[(key as? String)!] = newValue + } + } + } + EVReflection.setPropertiesfromDictionary(dict, anyObject: theObject, conversionOptions: conversionOptions) + } + + /** + Compare all fields of 2 objects + + - parameter lhs: The first object for the comparisson + - parameter rhs: The second object for the comparisson + + - returns: true if the objects are the same, otherwise false + */ + public class func areEqual(_ lhs: NSObject, rhs: NSObject) -> Bool { + if swiftStringFromClass(lhs) != swiftStringFromClass(rhs) { + return false + } + + let (lhsdict, _) = toDictionary(lhs, conversionOptions: .DefaultComparing) + let (rhsdict, _) = toDictionary(rhs, conversionOptions: .DefaultComparing) + + return dictionariesAreEqual(lhsdict, rhsdict: rhsdict) + } + + /** + Compare 2 dictionaries + + - parameter lhsdict: Compare this dictionary + - parameter rhsdict: Compare with this dictionary + + - returns: Are the dictionaries equal or not + */ + public class func dictionariesAreEqual(_ lhsdict: NSDictionary, rhsdict: NSDictionary) -> Bool { + for (key, value) in rhsdict { + if let compareTo = lhsdict[(key as? String)!] { + if let dateCompareTo = compareTo as? Date, let dateValue = value as? Date { + let t1 = Int64(dateCompareTo.timeIntervalSince1970) + let t2 = Int64(dateValue.timeIntervalSince1970) + if t1 != t2 { + return false + } + } else if let array = compareTo as? NSArray, let arr = value as? NSArray { + if arr.count != array.count { + return false + } + for (index, arrayValue) in array.enumerated() { + if arrayValue as? NSDictionary != nil { + if !dictionariesAreEqual((arrayValue as? NSDictionary)!, rhsdict: (arr[index] as? NSDictionary)!) { + return false + } + } else { + if !(arrayValue as AnyObject).isEqual(arr[index]) { + return false + } + } + } + } else if !(compareTo as AnyObject).isEqual(value) { + return false + } + } + } + return true + } + + // MARK: - Reflection helper functions + + /** + Get the app name from the 'Bundle name' and if that's empty, then from the 'Bundle identifier' otherwise we assume it's a EVReflection unit test and use that bundle identifier + + - parameter forObject: Pass an object to this method if you know a class from the bundele where you want the name for. + + - returns: A cleaned up name of the app. + */ + public class func getCleanAppName(_ forObject: NSObject? = nil) -> String { + // if an object was specified, then always use the bundle name of that class + if forObject != nil { + return nameForBundle(Bundle(for: type(of: forObject!))) + } + + // If no object was specified but an identifier was set, then use that identifier. + if EVReflection.bundleIdentifier != nil { + return EVReflection.bundleIdentifier! + } + + // use the bundle name from the main bundle, if that's not set use the identifier + return nameForBundle(Bundle.main) + } + + /** + Get the app name from the 'Bundle name' and if that's empty, then from the 'Bundle identifier' otherwise we assume it's a EVReflection unit test and use that bundle identifier + + - parameter aClass: Pass an AnyClass to this method if you know a class from the bundele where you want the name for. + + - returns: A cleaned up name of the app. + */ + public class func getCleanAppName(_ aClass: AnyClass?) -> String { + // if an object was specified, then always use the bundle name of that class + if aClass != nil { + return nameForBundle(Bundle(for: aClass!)) + } + + // If no object was specified but an identifier was set, then use that identifier. + if EVReflection.bundleIdentifier != nil { + return EVReflection.bundleIdentifier! + } + + // use the bundle name from the main bundle, if that's not set use the identifier + return nameForBundle(Bundle.main) + } + + + /// Variable that can be set using setBundleIdentifier + fileprivate static var bundleIdentifier: String? = nil + + /// Variable that can be set using setBundleIdentifiers + fileprivate static var bundleIdentifiers: [String]? = nil + + /** + This method can be used in unit tests to force the bundle where classes can be found + + - parameter forClass: The class that will be used to find the appName for in which we can find classes by string. + */ + public class func setBundleIdentifier(_ forClass: AnyClass) { + EVReflection.bundleIdentifier = nameForBundle(Bundle(for:forClass)) + } + + /** + This method can be used in unit tests to force the bundle where classes can be found + + - parameter identifier: The identifier that will be used. + */ + public class func setBundleIdentifier(_ identifier: String) { + EVReflection.bundleIdentifier = identifier + } + + + /** + This method can be used in project where models are split between multiple modules. + + - parameter classes: classes that that will be used to find the appName for in which we can find classes by string. + */ + public class func setBundleIdentifiers(_ classes: Array) { + bundleIdentifiers = [] + for aClass in classes { + bundleIdentifiers?.append(nameForBundle(Bundle(for: aClass))) + } + } + + /** + This method can be used in project where models are split between multiple modules. + + - parameter identifiers: The array of identifiers that will be used. + */ + public class func setBundleIdentifiers(_ identifiers: Array) { + bundleIdentifiers = [] + for identifier in identifiers { + bundleIdentifiers?.append(identifier) + } + } + + fileprivate static func nameForBundle(_ bundle: Bundle) -> String { + // get the bundle name from what is set in the infoDictionary + var appName = bundle.infoDictionary?[kCFBundleExecutableKey as String] as? String ?? "" + + // If it was not set, then use the bundleIdentifier (which is the same as kCFBundleIdentifierKey) + if appName == "" { + appName = bundle.bundleIdentifier ?? "" + appName = appName.split(whereSeparator: {$0 == "."}).map({ String($0) }).last ?? "" + } + + // First character may not be a number + if appName.prefix(1) >= "0" && appName.prefix(1) <= "9" { + appName = "_" + String(appName.dropFirst()) + } + + // Clean up special characters + return appName.components(separatedBy: illegalCharacterSet).joined(separator: "_") + } + + + /// This dateformatter will be used when a conversion from string to NSDate is required + fileprivate static var dateFormatter: DateFormatter? = nil + + /** + This function can be used to force using an alternat dateformatter for converting String to NSDate + + - parameter formatter: The new DateFormatter + */ + public class func setDateFormatter(_ formatter: DateFormatter?) { + dateFormatter = formatter + } + + /** + This function is used for getting the dateformatter and defaulting to a standard if it's not set + + - returns: The dateformatter + */ + fileprivate class func getDateFormatter() -> DateFormatter { + if let formatter = dateFormatter { + return formatter + } + dateFormatter = DateFormatter() + dateFormatter!.locale = Locale(identifier: "en_US_POSIX") + dateFormatter!.timeZone = TimeZone(secondsFromGMT: 0) + dateFormatter!.dateFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ssZ" + return dateFormatter! + } + + /** + Get the swift Class type from a string + + - parameter className: The string representation of the class (name of the bundle dot name of the class) + + - returns: The Class type + */ + public class func swiftClassTypeFromString(_ className: String) -> AnyClass? { + if let c = NSClassFromString(className) { + return c + } + + // The default did not work. try a combi of appname and classname + if className.range(of: ".", options: NSString.CompareOptions.caseInsensitive) == nil { + let appName = getCleanAppName() + if let c = NSClassFromString("\(appName).\(className)") { + return c + } + } + + if let bundleIdentifiers = bundleIdentifiers { + for aBundle in bundleIdentifiers { + if let existingClass = NSClassFromString("\(aBundle).\(className)") { + return existingClass + } + } + } + + return nil + } + + /** + Get the swift Class from a string + + - parameter className: The string representation of the class (name of the bundle dot name of the class) + + - returns: The Class type + */ + public class func swiftClassFromString(_ className: String) -> NSObject? { + return (swiftClassTypeFromString(className) as? NSObject.Type)?.init() + } + + /** + Get the class name as a string from a swift class + + - parameter theObject: An object for whitch the string representation of the class will be returned + + - returns: The string representation of the class (name of the bundle dot name of the class) + */ + public class func swiftStringFromClass(_ theObject: NSObject) -> String { + return NSStringFromClass(type(of: theObject)).replacingOccurrences(of: getCleanAppName(theObject) + ".", with: "", options: NSString.CompareOptions.caseInsensitive, range: nil) + } + + /** + Get the class name as a string from a swift class + + - parameter aClass: An AnyClass for whitch the string representation of the class will be returned + + - returns: The string representation of the class (name of the bundle dot name of the class) + */ + public class func swiftStringFromClass(_ aClass: AnyClass) -> String { + return NSStringFromClass(aClass).replacingOccurrences(of: getCleanAppName(aClass) + ".", with: "", options: NSString.CompareOptions.caseInsensitive, range: nil) + } + + + /** + Helper function to convert an Any to AnyObject + + - parameter parentObject: Only needs to be set to the object that has this property when the value is from a property that is an array of optional values + - parameter key: Only needs to be set to the name of the property when the value is from a property that is an array of optional values + - parameter anyValue: Something of type Any is converted to a type NSObject + - parameter conversionOptions: Option set for the various conversion options. + + - returns: The value where the Any is converted to AnyObject plus the type of that value as a string + */ + public class func valueForAny(_ parentObject: Any? = nil, key: String? = nil, anyValue: Any, conversionOptions: ConversionOptions = .DefaultDeserialize, isCachable: Bool = false, parents: [NSObject] = []) -> (value: AnyObject, type: String, isObject: Bool) { + var theValue = anyValue + var valueType: String = "" + + var mi: Mirror = Mirror(reflecting: theValue) + + if mi.displayStyle == .optional { + if mi.children.count == 1 { + theValue = mi.children.first!.value + mi = Mirror(reflecting: theValue) + valueType = String(reflecting:type(of: theValue)) + } else if mi.children.count == 0 { + valueType = String(reflecting:type(of: theValue)) + var subtype: String = String(valueType[(valueType.components(separatedBy: "<") [0] + "<").endIndex...]) + subtype = String(subtype[.. String { + if type.split(separator: "<").count > 1 { + // Remove the Array or Set prefix + let prefix = type.split(separator: "<") [0] + "<" + var subtype = String(type[prefix.endIndex...]) + subtype = String(subtype[.." + } + + if type.contains(".") { + var parts = type.components(separatedBy: ".") + if parts.count == 2 { + return parts[1] + } + let c = String(repeating:"C", count: parts.count - 1) + var rv = "_Tt\(c)\(parts[0].count)\(parts[0])" + parts.remove(at: 0) + for part in parts { + rv = "\(rv)\(part.count)\(part)" + } + return rv + } + return type + } + + + public class func valueForAnyDetail(_ parentObject: Any? = nil, key: String? = nil, theValue: Any, valueType: String) -> (value: AnyObject, type: String, isObject: Bool) { + + if theValue is NSNumber { + return (theValue as! NSNumber, "NSNumber", false) + } + if theValue is Int64 { + return (NSNumber(value: theValue as! Int64), "NSNumber", false) + } + if theValue is UInt64 { + return (NSNumber(value: theValue as! UInt64), "NSNumber", false) + } + if theValue is Int32 { + return (NSNumber(value: theValue as! Int32), "NSNumber", false) + } + if theValue is UInt32 { + return (NSNumber(value: theValue as! UInt32), "NSNumber", false) + } + if theValue is Int16 { + return (NSNumber(value: theValue as! Int16), "NSNumber", false) + } + if theValue is UInt16 { + return (NSNumber(value: theValue as! UInt16), "NSNumber", false) + } + if theValue is Int8 { + return (NSNumber(value: theValue as! Int8), "NSNumber", false) + } + if theValue is UInt8 { + return (NSNumber(value: theValue as! UInt8), "NSNumber", false) + } + if theValue is NSString { + return (theValue as! NSString, "NSString", false) + } + if theValue is Date { + return (theValue as AnyObject, "NSDate", false) + } + if theValue is UUID { + return ((theValue as! UUID).uuidString as AnyObject, "NSString", false) + } + if theValue is Array { + return (theValue as AnyObject, valueType, false) + } + if theValue is EVCustomReflectable { + let value: AnyObject = (theValue as! EVCustomReflectable).toCodableValue() as AnyObject + return (value, valueType, false) + } + + if theValue is EVReflectable && theValue is NSObject { + if valueType.contains("<") { + return (theValue as! EVReflectable, swiftStringFromClass(theValue as! NSObject), true) + } + return (theValue as! EVReflectable, valueType, true) + } + if theValue is NSObject { + if valueType.contains("<") { + return (theValue as! NSObject, swiftStringFromClass(theValue as! NSObject), true) + } + if valueType != "_SwiftValue" { + // isObject is false to prevent parsing of objects like CKRecord, CKRecordId and other objects. + return (theValue as! NSObject, valueType, false) + } + } + if valueType.hasPrefix("Swift.Array<") && parentObject is EVArrayConvertable { + return ((parentObject as! EVArrayConvertable).convertArray(key ?? "_unknownKey", array: theValue), valueType, false) + } + + (parentObject as? EVReflectable)?.addStatusMessage(.InvalidType, message: "valueForAny unkown type \(valueType) for value: \(theValue).") + evPrint(.InvalidType, "ERROR: valueForAny unkown type \(valueType) for key: \(key ?? "") and value: \(theValue).") + return (NSNull(), "NSNull", false) + } + + fileprivate static func convertStructureToDictionary(_ theValue: Any, conversionOptions: ConversionOptions, isCachable: Bool, parents: [NSObject] = []) -> NSDictionary { + let reflected = Mirror(reflecting: theValue) + let (addProperties, _) = reflectedSub(theValue, reflected: reflected, conversionOptions: conversionOptions, isCachable: isCachable, parents: parents) + return addProperties + } + + + /** + Try to set a value of a property with automatic String to and from Number conversion + + - parameter anyObject: the object where the value will be set + - parameter key: the name of the property + - parameter theValue: the value that will be set + - parameter typeInObject: the type of the value + - parameter valid: False if a vaue is expected and a dictionary + - parameter conversionOptions: Option set for the various conversion options. + */ + public static func setObjectValue(_ anyObject: T, key: String, theValue: Any?, typeInObject: String? = nil, valid: Bool, conversionOptions: ConversionOptions = .DefaultDeserialize, parents: [NSObject] = []) where T: NSObject { + + guard var value = theValue , (value as? NSNull) == nil else { + return + } + + if conversionOptions.contains(.PropertyConverter) { + if let (_, propertySetter, _) = (anyObject as? EVReflectable)?.propertyConverters().filter({$0.0 == key}).first { + propertySetter(value) + return + } + } + + if conversionOptions.contains(.Decoding), let ro = anyObject as? EVReflectable { + if let v = ro.decodePropertyValue(value: value, key: key) { + value = v + } + } + + // Let us put a number into a string property by taking it's stringValue + let (_, type, _) = valueForAny("", key: key, anyValue: value, conversionOptions: conversionOptions, isCachable: false, parents: parents) + if (typeInObject == "String" || typeInObject == "NSString") && type == "NSNumber" { + if let convertedValue = value as? NSNumber { + value = convertedValue.stringValue as AnyObject + } + } else if typeInObject == "NSNumber" && (type == "String" || type == "NSString") { + if let convertedValue = (value as? String)?.lowercased() { + if convertedValue == "true" || convertedValue == "yes" { + value = 1 as AnyObject + } else if convertedValue == "false" || convertedValue == "no" { + value = 0 as AnyObject + } else { + value = NSNumber(value: Double(convertedValue) ?? 0 as Double) + } + } + } else if typeInObject == "UUID" && (type == "String" || type == "NSString") { + value = UUID(uuidString: value as? String ?? "") as AnyObject? ?? UUID() as AnyObject + } else if typeInObject == "NSURL" && (type == "String" || type == "NSString") { + value = NSURL(string: value as? String ?? "")! as AnyObject + } else if (typeInObject == "NSDate" || typeInObject == "Date") && (type == "String" || type == "NSString") { + if let convertedValue = value as? String { + if let date = getDateFormatter().date(from: convertedValue) { + value = date as AnyObject + } else if let date = Date(fromDateTimeString: convertedValue) { + value = date as AnyObject + } else { + (anyObject as? EVReflectable)?.addStatusMessage(.InvalidValue, message: "The dateformatter returend nil for value \(convertedValue)") + evPrint(.InvalidValue, "WARNING: The dateformatter returend nil for value \(convertedValue)") + return + } + } + } else if typeInObject == "AnyObject" { + + } + + if !(value is NSArray) && (typeInObject ?? "").contains("Swift.Array") { + value = NSArray(array: [value]) + } + + if typeInObject == "Struct" { + anyObject.setValue(value, forUndefinedKey: key) + } else { + if !valid { + anyObject.setValue(theValue, forUndefinedKey: key) + return + } + + // Call your own object validators that comply to the format: validate:Error: + do { + if !(value is NSNull) { + var setValue: AnyObject? = value as AnyObject? + let validateFunction = "validate" + key.prefix(1).uppercased() + key.dropFirst() + ":error:" + if (anyObject as AnyObject).responds(to: Selector(validateFunction)) { + try anyObject.validateValue(&setValue, forKey: key) + } + anyObject.setValue(setValue, forKey: key) + } + } catch _ { + (anyObject as? EVReflectable)?.addStatusMessage(.InvalidValue, message: "Not a valid value for object `\(NSStringFromClass(Swift.type(of: (anyObject as AnyObject))))`, type `\(type)`, key `\(key)`, value `\(value)`") + evPrint(.InvalidValue, "INFO: Not a valid value for object `\(NSStringFromClass(Swift.type(of: (anyObject as AnyObject))))`, type `\(type)`, key `\(key)`, value `\(value)`") + } + /* TODO: Do I dare? ... For nullable types like Int? we could use this instead of the workaround. + // Asign pointerToField based on specific type + + // Look up the ivar, and it's offset + let ivar: Ivar = class_getInstanceVariable(anyObject.dynamicType, key) + let fieldOffset = ivar_getOffset(ivar) + + // Pointer arithmetic to get a pointer to the field + let pointerToInstance = unsafeAddressOf(anyObject) + let pointerToField = UnsafeMutablePointer(pointerToInstance + fieldOffset) + + // Set the value using the pointer + pointerToField.memory = value! + */ + } + } + + + // MARK: - Private helper functions + + /** + Create a dictionary of all property - key mappings + + - parameter theObject: the object for what we want the mapping + - parameter properties: dictionairy of all the properties + - parameter types: dictionairy of all property types. + + - returns: dictionairy of the property mappings + */ + fileprivate class func cleanupKeysAndValues(_ theObject: NSObject, properties: NSDictionary, types: NSDictionary) -> (NSDictionary, NSDictionary) { + let newProperties = NSMutableDictionary() + let newTypes = NSMutableDictionary() + for (key, _) in properties { + if let newKey = cleanupKey(theObject, key: (key as? String)!, tryMatch: nil) { + newProperties[newKey] = properties[(key as? String)!] + newTypes[newKey] = types[(key as? String)!] + } + } + return (newProperties, newTypes) + } + + + /** + Try to map a property name to a json/dictionary key by applying some rules like property mapping, snake case conversion or swift keyword fix. + + - parameter anyObject: the object where the key is part of + - parameter key: the key to clean up + - parameter tryMatch: dictionary of keys where a mach will be tried to + + - returns: the cleaned up key + */ + fileprivate class func cleanupKey(_ anyObject: NSObject, key: String, tryMatch: NSDictionary?) -> String? { + var newKey: String = key + + if tryMatch?[newKey] != nil { + return newKey + } + + // Step 1 - clean up keywords + if newKey.first == "_" { + if keywords.contains(String(newKey[newKey.index(newKey.startIndex, offsetBy: 1)...])) { + newKey = String(newKey[newKey.index(newKey.startIndex, offsetBy: 1)...]) + if tryMatch?[newKey] != nil { + return newKey + } + } + } + + // Step 2 - replace illegal characters + if let t = tryMatch { + for (key, _) in t { + var k = key + if let kIsString = k as? String { + k = processIllegalCharacters(kIsString) + } + if k as? String == newKey { + return key as? String + } + } + } + + // Step 3 - from CmelCase or pascalCase + newKey = CamelCaseToPascalCase(newKey) + if tryMatch?[newKey] != nil { + return newKey + } + + // Step 4 - from PascalCase or camelCase + newKey = PascalCaseToCamelCase(newKey) + if tryMatch?[newKey] != nil { + return newKey + } + + // Step 5 - from camelCase to snakeCase + newKey = camelCaseToUnderscores(newKey) + if tryMatch?[newKey] != nil { + return newKey + } + + if tryMatch != nil { + return nil + } + + return newKey + } + + /// Character that will be replaced by _ from the keys in a dictionary / json + fileprivate static let illegalCharacterSet = CharacterSet(charactersIn: " -&%#@!$^*()<>?.,:;") + /// processIllegalCharacters Cache + fileprivate static var processIllegalCharactersCache = NSCache() + + /** + Replace illegal characters to an underscore + + - parameter input: key + + - returns: processed string with illegal characters converted to underscores + */ + internal static func processIllegalCharacters(_ input: String) -> String { + var p: NSString = "" + if let cachedVersion = processIllegalCharactersCache.object(forKey: input as NSString) { + // use the cached version + p = cachedVersion + } else { + // create it from scratch then store in the cache + p = input.components(separatedBy: illegalCharacterSet).joined(separator: "_") as NSString + processIllegalCharactersCache.setObject(p, forKey: input as NSString) + } + return p as String + } + + /// camelCaseToUnderscoresCache Cache + fileprivate static var camelCaseToUnderscoresCache = NSCache() + + /** + Convert a CamelCase to Underscores + + - parameter input: the CamelCase string + + - returns: the underscore string + */ + internal static func camelCaseToUnderscores(_ input: String) -> String { + if input.count == 0 { + return input + } + + var p: NSString = "" + if let cachedVersion = camelCaseToUnderscoresCache.object(forKey: input as NSString) { + p = cachedVersion + } else { + var output: String = String(input.first!).lowercased() + let uppercase: CharacterSet = CharacterSet.uppercaseLetters + for character in input[input.index(input.startIndex, offsetBy: 1)...] { + if uppercase.contains(UnicodeScalar(String(character).utf16.first!)!) { + output += "_\(String(character).lowercased())" + } else { + output += "\(String(character))" + } + } + p = output as NSString + camelCaseToUnderscoresCache.setObject(p, forKey: input as NSString) + } + return p as String + } + + + + /** + Convert a CamelCase to pascalCase + + - parameter input: the CamelCase string + + - returns: the pascalCase string + */ + internal static func PascalCaseToCamelCase(_ input: String) -> String { + if input.count > 1 { + return String(describing: input.first!).lowercased() + input[input.index(after: input.startIndex)...] + } + return input.lowercased() + } + + + /** + Convert a PascalCase to camelCase + + - parameter input: the CamelCase string + + - returns: the pascalCase string + */ + internal static func CamelCaseToPascalCase(_ input: String) -> String { + if input.count > 1 { + return String(describing: input.first!).uppercased() + input[input.index(after: input.startIndex)...] + } + return input.uppercased() + } + + /// List of swift keywords for cleaning up keys + fileprivate static let keywords = ["self", "description", "class", "deinit", "enum", "extension", "func", "import", "init", "let", "protocol", "static", "struct", "subscript", "typealias", "var", "break", "case", "continue", "default", "do", "else", "fallthrough", "if", "in", "for", "return", "switch", "where", "while", "as", "dynamicType", "is", "new", "super", "Self", "Type", "__COLUMN__", "__FILE__", "__FUNCTION__", "__LINE__", "associativity", "didSet", "get", "infix", "inout", "left", "mutating", "none", "nonmutating", "operator", "override", "postfix", "precedence", "prefix", "right", "set", "unowned", "unowned", "safe", "unowned", "unsafe", "weak", "willSet", "private", "public", "internal", "zone"] + + + fileprivate static func arrayConversion(_ anyObject: NSObject, key: String, fieldType: String?, original: Any?, theDictValue: Any?, conversionOptions: ConversionOptions = .DefaultDeserialize) -> NSArray { + //Swift.Array>> + let dictValue: NSArray? = theDictValue as? NSArray + if fieldType?.hasPrefix("Swift.Array (Any?, Bool) { + var dictValue = theDictValue + var valid = true + if let type = fieldType { + if type.hasPrefix("Swift.Array<") && dictValue is NSArray { + dictValue = arrayConversion(anyObject, key: key, fieldType: fieldType, original: original, theDictValue: theDictValue, conversionOptions: conversionOptions) + } + if type.hasPrefix("Swift.Array<") && dictValue as? NSDictionary != nil { + if (dictValue as? NSDictionary)?.count == 1 { + // XMLDictionary fix + let onlyElement = (dictValue as? NSDictionary)?.makeIterator().next() + //let t: String = ((onlyElement?.key as? String) ?? "") + if onlyElement?.value as? NSArray != nil && type.hasPrefix("Swift.Array<") { // && type.lowercased().hasSuffix("\(t)>") + dictValue = onlyElement?.value as? NSArray + dictValue = dictArrayToObjectArray(anyObject, key: key, type: type, array: (dictValue as? [NSDictionary] as NSArray?) ?? [NSDictionary]() as NSArray, conversionOptions: conversionOptions) as NSArray + } else { + // Single object array fix + var array: [NSDictionary] = [NSDictionary]() + array.append(dictValue as? NSDictionary ?? NSDictionary()) + dictValue = dictArrayToObjectArray(anyObject, key: key, type: type, array: array as NSArray, conversionOptions: conversionOptions) as NSArray + } + } else { + // Single object array fix + var array: [NSDictionary] = [NSDictionary]() + array.append(dictValue as? NSDictionary ?? NSDictionary()) + dictValue = dictArrayToObjectArray(anyObject, key: key, type: type, array: array as NSArray, conversionOptions: conversionOptions) as NSArray + } + } else if let _ = type.range(of: "_NativeDictionaryStorageOwner"), let dict = dictValue as? NSDictionary, let org = anyObject as? EVReflectable { + dictValue = org.convertDictionary(key, dict: dict) + } else if type != "NSDictionary" && type != "__NSDictionary0" && type != "AnyObject" && dictValue as? NSDictionary != nil { //TODO this too? && original is NSObject + let (dict, isValid) = dictToObject(type, original: original as? NSObject, dict: dictValue as? NSDictionary ?? NSDictionary(), conversionOptions: conversionOptions) + dictValue = dict ?? dictValue + valid = isValid + } else if type.range(of: "") == nil && type.range(of: "") == nil && dictValue as? [NSDictionary] != nil { + // Array of objects + if !(original is EVCustomReflectable) { + dictValue = dictArrayToObjectArray(anyObject, key: key, type: type, array: dictValue as? [NSDictionary] as NSArray? ?? [NSDictionary]() as NSArray, conversionOptions: conversionOptions) as NSArray + } + } else if dictValue is String && original is NSObject && original is EVReflectable { + // fixing the conversion from XML without properties + let (dict, isValid) = dictToObject(type, original:original as? NSObject, dict: ["__text": dictValue as? String ?? ""], conversionOptions: conversionOptions) + dictValue = dict ?? dictValue + valid = isValid + } else if !type.hasPrefix("Swift.Array<") && !type.hasPrefix("Swift.Set<") { + if let array = dictValue as? NSArray { + if anyObject is EVCustomReflectable { + return (array, true) + } + if let org = anyObject as? EVReflectable { + org.addStatusMessage(.InvalidType, message: "Did not expect an array for \(key). Will use the first item instead.") + evPrint(.InvalidType, "WARNING: Did not expect an array for \(key). Will use the first item instead.") + } + if array.count > 0 { + return (array[0] as AnyObject?, true) + } + return (NSNull(), true) + } + } + } else { + + } + return (dictValue, valid) + } + + /** + Set sub object properties from a dictionary + + - parameter type: The object type that will be created + - parameter original: The original value in the object which is used to create a return object + - parameter dict: The dictionary that will be converted to an object + - parameter conversionOptions: Option set for the various conversion options. + + - returns: The object that is created from the dictionary + */ + fileprivate class func dictToObject(_ type: String, original: T?, dict: NSDictionary, conversionOptions: ConversionOptions = .DefaultDeserialize) -> (T?, Bool) where T: NSObject { + if var returnObject = original { + if type != "NSNumber" && type != "NSString" && type != "NSDate" && type != "Struct" && type.contains("Dictionary<") == false { + returnObject = setPropertiesfromDictionary(dict, anyObject: returnObject, conversionOptions: conversionOptions) + } else { + if type.contains("Dictionary<") == false && type != "Struct" { + (original as? EVReflectable)?.addStatusMessage(.InvalidClass, message: "Cannot set values on type \(type) from dictionary \(dict)") + evPrint(.InvalidClass, "WARNING: Cannot set values on type \(type) from dictionary \(dict)") + } + return (returnObject, false) + } + + return (returnObject, true) + } + + var useType = type + if type.hasPrefix("Swift.Optional<") { + var subtype: String = String(type[(type.components(separatedBy: "<") [0] + "<").endIndex...]) + subtype = String(subtype[.. NSArray { + var subtype = "" + if type.components(separatedBy: "<").count > 1 { + // Remove the Array prefix + subtype = String(type[(type.components(separatedBy: "<") [0] + "<").endIndex...]) + subtype = String(subtype[.. NSObject? { + var org = swiftClassFromString(type) + if let evResult = org as? EVReflectable { + if let type = evResult.getType(item as? NSDictionary ?? NSDictionary()) as? NSObject { + org = type + } + if let specific = evResult.getSpecificType(item as? NSDictionary ?? NSDictionary()) as? NSObject { + org = specific + } else if let evResult = anyObject as? EVGenericsKVC { + org = evResult.getGenericType() + } + } + return org + } + + /** + for parsing an object to a dictionary. including properties from it's super class (recursive) + + - parameter theObject: The object as is + - parameter reflected: The object parsed using the reflect method. + - parameter conversionOptions: Option set for the various conversion options. + + - returns: The dictionary that is created from the object plus an dictionary of property types. + */ + fileprivate class func reflectedSub(_ theObject: Any, reflected: Mirror, conversionOptions: ConversionOptions = .DefaultDeserialize, isCachable: Bool, parents: [NSObject] = []) -> (NSDictionary, NSDictionary) { + let propertiesDictionary = NSMutableDictionary() + let propertiesTypeDictionary = NSMutableDictionary() + // First add the super class propperties + if let superReflected = reflected.superclassMirror { + let (addProperties, addPropertiesTypes) = reflectedSub(theObject, reflected: superReflected, conversionOptions: conversionOptions, isCachable: isCachable, parents: parents) + for (k, v) in addProperties { + if k as? String != "evReflectionStatuses" { + propertiesDictionary.setValue(v, forKey: k as? String ?? "") + propertiesTypeDictionary[k as? String ?? ""] = addPropertiesTypes[k as? String ?? ""] + } + } + } + for property in reflected.children { + if let originalKey: String = property.label { + var skipThisKey = false + var mapKey = originalKey + if mapKey.contains(".") { + mapKey = mapKey.components(separatedBy: ".")[0] // remover the .storage for lazy properties + } + + if originalKey == "evReflectionStatuses" { + skipThisKey = true + } + + if conversionOptions.contains(.PropertyMapping) { + if let reflectable = theObject as? EVReflectable { + if let mapping = reflectable.propertyMapping().filter({$0.keyInObject == originalKey}).first { + if mapping.keyInResource == nil { + skipThisKey = true + } else { + mapKey = mapping.keyInResource! + } + } + } + } + + if !skipThisKey { + var value = property.value + + // Convert the Any value to a NSObject value + var (unboxedValue, valueType, isObject) = valueForAny(theObject, key: originalKey, anyValue: value, conversionOptions: conversionOptions, isCachable: isCachable, parents: parents) + + if let v = value as? EVCustomReflectable { + unboxedValue = v.toCodableValue() as AnyObject + valueType = "String" + isObject = false + } + + if conversionOptions.contains(.Encoding), let ro = theObject as? EVReflectable { + unboxedValue = ro.encodePropertyValue(value: unboxedValue, key: originalKey) as AnyObject + } + + if conversionOptions.contains(.PropertyConverter) { + // If there is a properyConverter, then use the result of that instead. + if let (_, _, propertyGetter) = (theObject as? EVReflectable)?.propertyConverters().filter({$0.0 == originalKey}).first { + value = propertyGetter() as Any + let (unboxedValue2, _, _) = valueForAny(theObject, key: originalKey, anyValue: value, conversionOptions: conversionOptions, isCachable: isCachable, parents: parents) + unboxedValue = unboxedValue2 + } + } + + if isObject { + if let obj = unboxedValue as? EVReflectable { + if let json = obj.customConverter() { + unboxedValue = json as AnyObject + } else { + // sub objects will be added as a dictionary itself. + let (dict, _) = toDictionary(unboxedValue as? NSObject ?? NSObject(), conversionOptions: conversionOptions, isCachable: isCachable, parents: parents) + unboxedValue = dict + } + } else { + // sub objects will be added as a dictionary itself. + let (dict, _) = toDictionary(unboxedValue as? NSObject ?? NSObject(), conversionOptions: conversionOptions, isCachable: isCachable, parents: parents) + unboxedValue = dict + } + } else if let array = unboxedValue as? [NSObject] { + var item: Any + if array.count > 0 { + item = array[0] + // Workaround for bug https://bugs.swift.org/browse/SR-3083 + if let possibleEnumArray = unboxedValue as? [Any] { + let possibleEnum = possibleEnumArray[0] + if type(of: item) != type(of: possibleEnum) { + item = possibleEnum + var newArray: [AnyObject] = [] + for anEnum in possibleEnumArray { + let (value, _, _) = valueForAny(anyValue: anEnum) + newArray.append(value) + } + unboxedValue = newArray as AnyObject + } + } + } else { + item = array.getArrayTypeInstance(array) + } + + let (_, _, isObject) = valueForAny(anyValue: item, conversionOptions: conversionOptions, isCachable: isCachable, parents: parents) + + if isObject { + // If the items are objects, than add a dictionary of each to the array + var tempValue = [NSDictionary]() + for av in array { + let (dict, _) = toDictionary(av, conversionOptions: conversionOptions, isCachable: isCachable, parents: parents) + tempValue.append(dict) + } + unboxedValue = tempValue as AnyObject + } + } + + if conversionOptions.contains(.SkipPropertyValue) { + if let reflectable = theObject as? EVReflectable { + if !reflectable.skipPropertyValue(unboxedValue, key: mapKey) { + propertiesDictionary.setValue(unboxedValue, forKey: mapKey) + propertiesTypeDictionary[mapKey] = valueType + } + } else { + propertiesDictionary.setValue(unboxedValue, forKey: mapKey) + propertiesTypeDictionary[mapKey] = valueType + } + } else { + propertiesDictionary.setValue(unboxedValue, forKey: mapKey) + propertiesTypeDictionary[mapKey] = valueType + } + } + } + } + return (propertiesDictionary, propertiesTypeDictionary) + } + + + /** + Clean up dictionary so that it can be converted to json + + - parameter dict: The dictionairy that + + - returns: The cleaned up dictionairy + */ + internal class func convertDictionaryForJsonSerialization(_ dict: NSDictionary, theObject: NSObject) -> NSDictionary { + let dict2: NSMutableDictionary = NSMutableDictionary() + for (key, value) in dict { + dict2.setValue(convertValueForJsonSerialization(value as AnyObject, theObject: theObject), forKey: key as? String ?? "") + } + return dict2 + } + + /** + Clean up a value so that it can be converted to json + + - parameter value: The value to be converted + + - returns: The converted value + */ + fileprivate class func convertValueForJsonSerialization(_ value: Any, theObject: NSObject) -> AnyObject { + switch value { + case let stringValue as NSString: + return stringValue + case let numberValue as NSNumber: + return numberValue + case let nullValue as NSNull: + return nullValue + case let arrayValue as NSArray: + let tempArray: NSMutableArray = NSMutableArray() + for value in arrayValue { + tempArray.add(convertValueForJsonSerialization(value as Any, theObject: theObject)) + } + return tempArray + case let date as Date: + return getDateFormatter().string(from: date) as NSString + case let reflectable as EVCustomReflectable: + return convertDictionaryForJsonSerialization(reflectable.toCodableValue() as? NSDictionary ?? NSDictionary(), theObject: theObject) + case let reflectable as EVReflectable: + return convertDictionaryForJsonSerialization(reflectable.toDictionary(), theObject: theObject) + case let ok as NSDictionary: + return convertDictionaryForJsonSerialization(ok, theObject: theObject) + case let d as Data: + return d.base64EncodedString() as AnyObject + default: + (theObject as? EVReflectable)?.addStatusMessage(.InvalidType, message: "Unexpected type while converting value for JsonSerialization: \(value)") + evPrint(.InvalidType, "ERROR: Unexpected type while converting value for JsonSerialization: \(value)") + return "\(value)" as AnyObject + } + } +} + +extension Date { + public init?(fromDateTimeString: String) { + let pattern = "\\\\?/Date\\((\\d+)(([+-]\\d{2})(\\d{2}))?\\)\\\\?/" + let regex = try! NSRegularExpression(pattern: pattern) + let match: NSRange = regex.rangeOfFirstMatch(in: fromDateTimeString, range: NSRange(location: 0, length: fromDateTimeString.utf16.count)) + var dateString: String = "" + if match.location == NSNotFound { + dateString = fromDateTimeString + } else { + dateString = (fromDateTimeString as NSString).substring(with: match) // Extract milliseconds + } + let substrings = dateString.components(separatedBy: CharacterSet.decimalDigits.inverted) + guard let timeStamp = (substrings.compactMap { Double($0) }.first) else { return nil } + self.init(timeIntervalSince1970: timeStamp / 1000.0) // Create Date from timestamp + } +} + + diff --git a/Pods/EVReflection/Source/EVWorkaroundHelpers.swift b/Pods/EVReflection/Source/EVWorkaroundHelpers.swift new file mode 100755 index 0000000..dc58312 --- /dev/null +++ b/Pods/EVReflection/Source/EVWorkaroundHelpers.swift @@ -0,0 +1,106 @@ +// +// EVWorkaroundHelpers.swift +// EVReflection +// +// Created by Edwin Vermeer on 2/7/16. +// Copyright © 2016 evict. All rights reserved. +// + +import Foundation + + +/** + Protocol for the workaround when using generics. See WorkaroundSwiftGenericsTests.swift + */ +public protocol EVGenericsKVC { + /** + Implement this protocol in a class with generic properties so that we can still use a standard mechanism for setting property values. + */ + func setGenericValue(_ value: AnyObject!, forUndefinedKey key: String) + + /** + Add a function so that we can get an instance of T + */ + func getGenericType() -> NSObject +} + +/** + Protocol for the workaround when using an enum with a rawValue of an undefined type + */ +public protocol EVRaw { + /** + For implementing a function that will return the rawValue for a non sepecific enum + */ + var anyRawValue: Any { get } +} + +/** + Default implementation for getting the rawValue for any other type + */ +public extension EVRaw where Self: RawRepresentable { + var anyRawValue: Any { + get { + return rawValue as Any + } + } +} + +/** + Protocol for the workaround when using an array with nullable values + */ +public protocol EVArrayConvertable { + /** + For implementing a function for converting a generic array to a specific array. + */ + func convertArray(_ key: String, array: Any) -> NSArray +} + + +/** + Add a property to an enum to get the associated value + */ +public protocol EVAssociated { +} + +/** + The implrementation of the protocol for getting the associated value + */ +public extension EVAssociated { + /** + Easy access to the associated value of an enum. + + :returns: The label of the enum plus the associated value + */ + public var associated: (label: String, value: Any?) { + get { + let mirror = Mirror(reflecting: self) + if let associated = mirror.children.first { + return (associated.label!, associated.value) + } + evPrint(.EnumWithoutAssociatedValue, "WARNING: Enum option of \(self) does not have an associated value") + return ("\(self)", nil) + } + } +} + + + +/** + Dictionary extension for creating a dictionary from an array of enum values + */ +public extension Dictionary { + /** + Create a dictionairy based on all associated values of an enum array + + - parameter associated: array of dictionairy values which have an associated value + + */ + init(associated: [T]?) { + self.init() + if associated != nil { + for myEnum in associated! { + self[(myEnum.associated.label as? Key)!] = myEnum.associated.value as? Value + } + } + } +} diff --git a/Pods/EVReflection/Source/PrintOptions.swift b/Pods/EVReflection/Source/PrintOptions.swift new file mode 100644 index 0000000..f4494df --- /dev/null +++ b/Pods/EVReflection/Source/PrintOptions.swift @@ -0,0 +1,75 @@ +// +// PrintOptions.swift +// EVReflection +// +// Created by Edwin Vermeer on 9/5/16. +// Copyright © 2015 evict. All rights reserved. +// + + +/** + For specifying what should be printed + */ +public struct PrintOptions: OptionSet, CustomStringConvertible { + /// The numeric representation of the options + public let rawValue: Int + /** + Initialize with a raw value + + - parameter rawValue: the numeric representation + + - returns: The Print options + */ + public init(rawValue: Int) { self.rawValue = rawValue } + + /// No print + public static let None = PrintOptions(rawValue: 0) + /// print array init uknown keypath + public static let UnknownKeypath = PrintOptions(rawValue: 1) + /// print EIncorrectKey + public static let IncorrectKey = PrintOptions(rawValue: 2) + /// print should extend an NSObject + public static let ShouldExtendNSObject = PrintOptions(rawValue: 4) + /// print invalid json + public static let IsInvalidJson = PrintOptions(rawValue: 8) + /// print Missing protocol error + public static let MissingProtocol = PrintOptions(rawValue: 16) + /// print Missing key error + public static let MissingKey = PrintOptions(rawValue: 32) + /// print Invalid type error + public static let InvalidType = PrintOptions(rawValue: 64) + /// print Invalid value error + public static let InvalidValue = PrintOptions(rawValue: 128) + /// print Invalid class error + public static let InvalidClass = PrintOptions(rawValue: 256) + /// print enum without associated value + public static let EnumWithoutAssociatedValue = PrintOptions(rawValue: 512) + /// print enum without associated value + public static let UseWorkaround = PrintOptions(rawValue: 1024) + + + /// All the options + public static var All: PrintOptions = [UnknownKeypath, IncorrectKey, ShouldExtendNSObject, IsInvalidJson, MissingProtocol, MissingKey, InvalidType, InvalidValue, InvalidClass, EnumWithoutAssociatedValue, UseWorkaround] + + /// The active print options + public static var Active: PrintOptions = All + + /// Get a nice description of the PrintOptions + public var description: String { + let strings = ["UnknownKeypath", "IncorrectKey", "ShouldExtendNSObject", "IsInvalidJson", "MissingProtocol", "MissingKey", "InvalidType", "InvalidValue", "InvalidClass", "EnumWithoutAssociatedValue", "UseWorkaround"] + var members = [String]() + for (flag, string) in strings.enumerated() where contains(PrintOptions(rawValue:1<<(flag + 1))) { + members.append(string) + } + if members.count == 0 { + members.append("None") + } + return members.description + } +} + +public func evPrint(_ options: PrintOptions, _ value: String) { + if PrintOptions.Active.contains(options) { + print("🌀 \(value)") + } +} diff --git a/Pods/Manifest.lock b/Pods/Manifest.lock index f5c842b..16acd90 100644 --- a/Pods/Manifest.lock +++ b/Pods/Manifest.lock @@ -1,3 +1,18 @@ -PODFILE CHECKSUM: 44822adf25116fba9612f9a6e4184f5ab4db9a7f +PODS: + - EVReflection (5.6.2): + - EVReflection/Core (= 5.6.2) + - EVReflection/Core (5.6.2) + +DEPENDENCIES: + - EVReflection + +SPEC REPOS: + https://github.com/cocoapods/specs.git: + - EVReflection + +SPEC CHECKSUMS: + EVReflection: 640322f8a3aaf78cbc3c23892476b6adb636ebf0 + +PODFILE CHECKSUM: 37c990d763bcdd56cefd04cd5de41c1753bf9fd2 COCOAPODS: 1.5.2 diff --git a/Pods/Pods.xcodeproj/project.pbxproj b/Pods/Pods.xcodeproj/project.pbxproj index 17561cf..fd2d7c5 100644 --- a/Pods/Pods.xcodeproj/project.pbxproj +++ b/Pods/Pods.xcodeproj/project.pbxproj @@ -7,14 +7,27 @@ objects = { /* Begin PBXBuildFile section */ - 186C5E203BF3608BAB0043993C29EC3F /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5A16F4CFC63FAC439D7A04994F579A03 /* Foundation.framework */; }; - 3806E0641069706628409B43AB679BE1 /* Pods-ProjectX-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 456584BEEF505836D62F0D8D6079D1C1 /* Pods-ProjectX-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 106F53E394D3ABC4099DE1A69DD605B1 /* EVObject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25F397D55CD049AD0C1057047F274F41 /* EVObject.swift */; }; + 11A2606802F2CD8556892D95CCB730AB /* PrintOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 040D4F9EC5EE0A83E5B0792DC2464CA6 /* PrintOptions.swift */; }; + 2B4DBF73B18FBDF203ADBBFF1FEA4543 /* EVCustomReflectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 362437F5A32E040AA07FAA8D70B37C93 /* EVCustomReflectable.swift */; }; + 39C7B7DB3B10CEF04173A3A90A1EB8DD /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5A16F4CFC63FAC439D7A04994F579A03 /* Foundation.framework */; }; 3EE267E487945EE42F4FC893B92E37AC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5A16F4CFC63FAC439D7A04994F579A03 /* Foundation.framework */; }; - 65AC74C5912D6136438160805B7C68F2 /* Pods-ProjectX-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 23AB0DCD45A05D2B56DE773D2FB218F0 /* Pods-ProjectX-dummy.m */; }; + 4149B139A944EED0B567BAB79DC11B11 /* EVReflection-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F5BC3277893161864ABA7EE6BA160AA /* EVReflection-dummy.m */; }; + 46B8F4E1B21BED078515D240556F539F /* Pods-ProjectX-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 23AB0DCD45A05D2B56DE773D2FB218F0 /* Pods-ProjectX-dummy.m */; }; + 56AC36A1233DFE8B92E3ACDEB2865CFA /* EVReflectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = D08C807F1AF55611B3525C7D6894A948 /* EVReflectable.swift */; }; + 609B212E172C917DE6BC45AD18C6F50F /* Pods-ProjectX-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 456584BEEF505836D62F0D8D6079D1C1 /* Pods-ProjectX-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6A3EAA190229B501133298572493C3DA /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5A16F4CFC63FAC439D7A04994F579A03 /* Foundation.framework */; }; 8288207F41ADB3D2C021C7213C94504D /* Pods-ProjectXUITests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F56FD24E7B6B9B9E6DDCB943AB106B13 /* Pods-ProjectXUITests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8F6B9442BBF9A217EC880C8E4F5E91FA /* EVReflection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F93EBA41699B4D27F5D40C2B378B471 /* EVReflection.swift */; }; + B16BCD41FEB0C413C29D022509B7F5C1 /* ConversionOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F80D6DF9FED45651595974E33369C47 /* ConversionOptions.swift */; }; B4E269A07271CD388F59A18EC4EBA4E5 /* Pods-ProjectXUITests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F2C10805549FD99D7CB5349496E41D33 /* Pods-ProjectXUITests-dummy.m */; }; + C68645588E5D3AF68DFB86F3DB3518D1 /* DeserializationStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD9E34AAFD2F397F5CA5A31C2A99C477 /* DeserializationStatus.swift */; }; + E0D50D8790C8FF18ADF380EE9FCB74EE /* EVReflection-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 60608AFF6D1377B72B9EE8839ECF6219 /* EVReflection-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E0EB6A6E80003A0375782FEB80CE214E /* EVWorkaroundHelpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 773AB32C3E8834F0A37D800AA7CCB8B1 /* EVWorkaroundHelpers.swift */; }; E35A36FFEE7685B7B343E05A33654F29 /* Pods-ProjectXTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 31045782C4C78F6AC34EC4FA0704B70E /* Pods-ProjectXTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EEFBED65C004846B53DE5C177818FA2D /* EVArrayExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 299FD3F61E6B452738CEB4805AD93880 /* EVArrayExtension.swift */; }; F1936E60EF226756434024D3F3224C48 /* Pods-ProjectXTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 27E5306AEAE10B2427DF688B80FA7E15 /* Pods-ProjectXTests-dummy.m */; }; + F6D09350B5F2C52A3448B2C10AB7D316 /* EVDictionaryExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10268EF3DA5E9A3D12A71EE2DC188FFD /* EVDictionaryExtension.swift */; }; F6D93BA618F407031E2F5478ACE2457C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5A16F4CFC63FAC439D7A04994F579A03 /* Foundation.framework */; }; /* End PBXBuildFile section */ @@ -23,62 +36,94 @@ isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 90782591CAF58E3FAC57594F0C5B3177; + remoteGlobalIDString = 768F964FE6D39D87DEDD9546C2AAB36B; remoteInfo = "Pods-ProjectX"; }; 9B9945FEE36193EF2B13A4E181CCD20B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 90782591CAF58E3FAC57594F0C5B3177; + remoteGlobalIDString = 768F964FE6D39D87DEDD9546C2AAB36B; remoteInfo = "Pods-ProjectX"; }; + FA922E8AE223D814E1916D80C3B03A3A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 16297A64D8F519B9DFFF85EBEF75A597; + remoteInfo = EVReflection; + }; /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 040D4F9EC5EE0A83E5B0792DC2464CA6 /* PrintOptions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PrintOptions.swift; path = Source/PrintOptions.swift; sourceTree = ""; }; 0A7519B851AFCD7521A01CE8121793A4 /* Pods-ProjectXUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ProjectXUITests.debug.xcconfig"; sourceTree = ""; }; 0B9B81CF083BBFE02712ABE90A4229E5 /* Pods-ProjectXTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-ProjectXTests.modulemap"; sourceTree = ""; }; + 10268EF3DA5E9A3D12A71EE2DC188FFD /* EVDictionaryExtension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVDictionaryExtension.swift; path = Source/EVDictionaryExtension.swift; sourceTree = ""; }; + 1F93EBA41699B4D27F5D40C2B378B471 /* EVReflection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVReflection.swift; path = Source/EVReflection.swift; sourceTree = ""; }; 23AB0DCD45A05D2B56DE773D2FB218F0 /* Pods-ProjectX-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-ProjectX-dummy.m"; sourceTree = ""; }; + 25F397D55CD049AD0C1057047F274F41 /* EVObject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVObject.swift; path = Source/EVObject.swift; sourceTree = ""; }; 27E5306AEAE10B2427DF688B80FA7E15 /* Pods-ProjectXTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-ProjectXTests-dummy.m"; sourceTree = ""; }; + 299FD3F61E6B452738CEB4805AD93880 /* EVArrayExtension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVArrayExtension.swift; path = Source/EVArrayExtension.swift; sourceTree = ""; }; 2D3E61C4EFFADA9D6AFD35546658C3F8 /* Pods-ProjectX-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-ProjectX-acknowledgements.plist"; sourceTree = ""; }; 305A9F31B46411DAB1B031159F218E01 /* Pods-ProjectX.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ProjectX.debug.xcconfig"; sourceTree = ""; }; 31045782C4C78F6AC34EC4FA0704B70E /* Pods-ProjectXTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-ProjectXTests-umbrella.h"; sourceTree = ""; }; + 335E57D30C9727F19AB7A32FB7D62E37 /* EVReflection.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = EVReflection.modulemap; sourceTree = ""; }; + 362437F5A32E040AA07FAA8D70B37C93 /* EVCustomReflectable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVCustomReflectable.swift; path = Source/EVCustomReflectable.swift; sourceTree = ""; }; 3DF6AE867C5A575732F56559B5386169 /* Pods-ProjectX-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-ProjectX-acknowledgements.markdown"; sourceTree = ""; }; 3ED23512DEB1500FD7B88590D2F5C755 /* Pods-ProjectX-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ProjectX-resources.sh"; sourceTree = ""; }; 420A658C87B5C16A7246B50997B0B3BD /* Pods-ProjectX.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-ProjectX.modulemap"; sourceTree = ""; }; 43E12FCAA7246A653DD5464184D0C293 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 456584BEEF505836D62F0D8D6079D1C1 /* Pods-ProjectX-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-ProjectX-umbrella.h"; sourceTree = ""; }; 497677A62BD9A6C58E7B4C660B781C01 /* Pods-ProjectXTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ProjectXTests.debug.xcconfig"; sourceTree = ""; }; - 4ADB415C10931F4F553416263244CA4F /* Pods_ProjectXTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_ProjectXTests.framework; path = "Pods-ProjectXTests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; - 5210E0E2A9BE6457B9D4FD9394B65579 /* Pods_ProjectXUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_ProjectXUITests.framework; path = "Pods-ProjectXUITests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + 4F5BC3277893161864ABA7EE6BA160AA /* EVReflection-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "EVReflection-dummy.m"; sourceTree = ""; }; + 4F80D6DF9FED45651595974E33369C47 /* ConversionOptions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConversionOptions.swift; path = Source/ConversionOptions.swift; sourceTree = ""; }; 5A16F4CFC63FAC439D7A04994F579A03 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS11.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; 5D1E7732F3AF0C4E8E74A8FA2EBFBFAE /* Pods-ProjectXUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ProjectXUITests.release.xcconfig"; sourceTree = ""; }; + 60608AFF6D1377B72B9EE8839ECF6219 /* EVReflection-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "EVReflection-umbrella.h"; sourceTree = ""; }; + 648BD518C079FF03326404E352BAE5DE /* EVReflection-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "EVReflection-prefix.pch"; sourceTree = ""; }; 6582ECDA324E305E3C024639FB5F564D /* Pods-ProjectXTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ProjectXTests-resources.sh"; sourceTree = ""; }; + 6C690E2A9F1189BF962293860A419B0E /* Pods_ProjectXTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_ProjectXTests.framework; path = "Pods-ProjectXTests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + 6DED991DC9DDB3966A93BEB6DF15C315 /* Pods_ProjectXUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_ProjectXUITests.framework; path = "Pods-ProjectXUITests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + 6FA8A74480C0CBE7684F3C66CA463B01 /* Pods_ProjectX.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_ProjectX.framework; path = "Pods-ProjectX.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; 719568D778ECBEAC0743C12D4B4D0FB8 /* Pods-ProjectXUITests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ProjectXUITests-resources.sh"; sourceTree = ""; }; 7465B6D6DC6B76C1BC646E475B90886E /* Pods-ProjectXTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-ProjectXTests-acknowledgements.markdown"; sourceTree = ""; }; + 773AB32C3E8834F0A37D800AA7CCB8B1 /* EVWorkaroundHelpers.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVWorkaroundHelpers.swift; path = Source/EVWorkaroundHelpers.swift; sourceTree = ""; }; 7E0BA159F9BBE27A724C9A25571CDEE7 /* Pods-ProjectXUITests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-ProjectXUITests-acknowledgements.plist"; sourceTree = ""; }; 84402BE490A57FF70CF669DFCFFD1C30 /* Pods-ProjectXTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-ProjectXTests-acknowledgements.plist"; sourceTree = ""; }; 855574B8A989C812505B042C43B00E82 /* Pods-ProjectX.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ProjectX.release.xcconfig"; sourceTree = ""; }; + 8B768B344769B3ED48B03F731575232D /* EVReflection.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = EVReflection.xcconfig; sourceTree = ""; }; 8BC616271F9C0A95561935E0B77D0FEF /* Pods-ProjectXTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ProjectXTests.release.xcconfig"; sourceTree = ""; }; 8BE4C8769E2C82924CF5ECDD07415C2C /* Pods-ProjectXUITests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-ProjectXUITests-acknowledgements.markdown"; sourceTree = ""; }; 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; 96ACCA3094945DF5BBE2D8D224485424 /* Pods-ProjectXUITests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-ProjectXUITests.modulemap"; sourceTree = ""; }; 9E916D5A43140393068ABE4FB3805993 /* Pods-ProjectX-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ProjectX-frameworks.sh"; sourceTree = ""; }; - A1F51742D388FCC3EEA4DC525E0FC4A3 /* Pods_ProjectX.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_ProjectX.framework; path = "Pods-ProjectX.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; AE00356EB2CE5E448251991823BCE830 /* Pods-ProjectXTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ProjectXTests-frameworks.sh"; sourceTree = ""; }; B44D80BE69259915A76261B2B85A0351 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; C60241298B0E74F49459E0856751B985 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + D08C807F1AF55611B3525C7D6894A948 /* EVReflectable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVReflectable.swift; path = Source/EVReflectable.swift; sourceTree = ""; }; + DD9E34AAFD2F397F5CA5A31C2A99C477 /* DeserializationStatus.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DeserializationStatus.swift; path = Source/DeserializationStatus.swift; sourceTree = ""; }; + E3586B7C51148D9443F976B1695E5E5A /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + E949E031ED776DA8BAB844E8D88D5B95 /* EVReflection.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = EVReflection.framework; path = EVReflection.framework; sourceTree = BUILT_PRODUCTS_DIR; }; EB52B1C1E3B9C8FE28F8E4149F406EFF /* Pods-ProjectXUITests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ProjectXUITests-frameworks.sh"; sourceTree = ""; }; F2C10805549FD99D7CB5349496E41D33 /* Pods-ProjectXUITests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-ProjectXUITests-dummy.m"; sourceTree = ""; }; F56FD24E7B6B9B9E6DDCB943AB106B13 /* Pods-ProjectXUITests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-ProjectXUITests-umbrella.h"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ - 3E9A6B14B8D1DF797AE52CB44CDB96FB /* Frameworks */ = { + 3B0CD109FD613DD1279B794DC00F9BA2 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 186C5E203BF3608BAB0043993C29EC3F /* Foundation.framework in Frameworks */, + 39C7B7DB3B10CEF04173A3A90A1EB8DD /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3DF234E730676FAA51C9BE2A2DBE9291 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 6A3EAA190229B501133298572493C3DA /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -101,14 +146,21 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 50B0C74AA74AA589852A3A8959E54CA8 /* Products */ = { + 3D2775AE14F466B11982004A4A13C3BC /* Core */ = { isa = PBXGroup; children = ( - A1F51742D388FCC3EEA4DC525E0FC4A3 /* Pods_ProjectX.framework */, - 4ADB415C10931F4F553416263244CA4F /* Pods_ProjectXTests.framework */, - 5210E0E2A9BE6457B9D4FD9394B65579 /* Pods_ProjectXUITests.framework */, - ); - name = Products; + 4F80D6DF9FED45651595974E33369C47 /* ConversionOptions.swift */, + DD9E34AAFD2F397F5CA5A31C2A99C477 /* DeserializationStatus.swift */, + 299FD3F61E6B452738CEB4805AD93880 /* EVArrayExtension.swift */, + 362437F5A32E040AA07FAA8D70B37C93 /* EVCustomReflectable.swift */, + 10268EF3DA5E9A3D12A71EE2DC188FFD /* EVDictionaryExtension.swift */, + 25F397D55CD049AD0C1057047F274F41 /* EVObject.swift */, + D08C807F1AF55611B3525C7D6894A948 /* EVReflectable.swift */, + 1F93EBA41699B4D27F5D40C2B378B471 /* EVReflection.swift */, + 773AB32C3E8834F0A37D800AA7CCB8B1 /* EVWorkaroundHelpers.swift */, + 040D4F9EC5EE0A83E5B0792DC2464CA6 /* PrintOptions.swift */, + ); + name = Core; sourceTree = ""; }; 5E0D919E635D23B70123790B8308F8EF /* iOS */ = { @@ -137,16 +189,38 @@ path = "Target Support Files/Pods-ProjectXUITests"; sourceTree = ""; }; + 78849575C95BAEEF4B546717CADDD8D8 /* Products */ = { + isa = PBXGroup; + children = ( + E949E031ED776DA8BAB844E8D88D5B95 /* EVReflection.framework */, + 6FA8A74480C0CBE7684F3C66CA463B01 /* Pods_ProjectX.framework */, + 6C690E2A9F1189BF962293860A419B0E /* Pods_ProjectXTests.framework */, + 6DED991DC9DDB3966A93BEB6DF15C315 /* Pods_ProjectXUITests.framework */, + ); + name = Products; + sourceTree = ""; + }; 7DB346D0F39D3F0E887471402A8071AB = { isa = PBXGroup; children = ( 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, BC3CA7F9E30CC8F7E2DD044DD34432FC /* Frameworks */, - 50B0C74AA74AA589852A3A8959E54CA8 /* Products */, + CF251A3E683FF9995A4523384DCA9040 /* Pods */, + 78849575C95BAEEF4B546717CADDD8D8 /* Products */, CF1C85C5C43BD8393C1913E22079FC3C /* Targets Support Files */, ); sourceTree = ""; }; + 88F46CBD5427C433CE22D81DF6D7F14F /* EVReflection */ = { + isa = PBXGroup; + children = ( + 3D2775AE14F466B11982004A4A13C3BC /* Core */, + D7B1A7C328EF10A3D656B76A99AFD2B2 /* Support Files */, + ); + name = EVReflection; + path = EVReflection; + sourceTree = ""; + }; A9D9DEE7D6513E287223CC0F151611E1 /* Pods-ProjectX */ = { isa = PBXGroup; children = ( @@ -201,14 +275,36 @@ name = "Targets Support Files"; sourceTree = ""; }; + CF251A3E683FF9995A4523384DCA9040 /* Pods */ = { + isa = PBXGroup; + children = ( + 88F46CBD5427C433CE22D81DF6D7F14F /* EVReflection */, + ); + name = Pods; + sourceTree = ""; + }; + D7B1A7C328EF10A3D656B76A99AFD2B2 /* Support Files */ = { + isa = PBXGroup; + children = ( + 335E57D30C9727F19AB7A32FB7D62E37 /* EVReflection.modulemap */, + 8B768B344769B3ED48B03F731575232D /* EVReflection.xcconfig */, + 4F5BC3277893161864ABA7EE6BA160AA /* EVReflection-dummy.m */, + 648BD518C079FF03326404E352BAE5DE /* EVReflection-prefix.pch */, + 60608AFF6D1377B72B9EE8839ECF6219 /* EVReflection-umbrella.h */, + E3586B7C51148D9443F976B1695E5E5A /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/EVReflection"; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ - 644167AFD11AFA45B8A8D26342F1A96B /* Headers */ = { + 3B4E64726DCB072C61F2A31ACA34DFAA /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 3806E0641069706628409B43AB679BE1 /* Pods-ProjectX-umbrella.h in Headers */, + E0D50D8790C8FF18ADF380EE9FCB74EE /* EVReflection-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -228,9 +324,34 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + ADF8CC690BCFA366F2318EFA03CC0F15 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 609B212E172C917DE6BC45AD18C6F50F /* Pods-ProjectX-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXHeadersBuildPhase section */ /* Begin PBXNativeTarget section */ + 16297A64D8F519B9DFFF85EBEF75A597 /* EVReflection */ = { + isa = PBXNativeTarget; + buildConfigurationList = 159F432BBF4726F7B46458EA31E9CA43 /* Build configuration list for PBXNativeTarget "EVReflection" */; + buildPhases = ( + 896EA02A9C036F568B2734D92771BE44 /* Sources */, + 3DF234E730676FAA51C9BE2A2DBE9291 /* Frameworks */, + 3B4E64726DCB072C61F2A31ACA34DFAA /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = EVReflection; + productName = EVReflection; + productReference = E949E031ED776DA8BAB844E8D88D5B95 /* EVReflection.framework */; + productType = "com.apple.product-type.framework"; + }; 6234938D11D80B3FC422F04A4C0130CB /* Pods-ProjectXUITests */ = { isa = PBXNativeTarget; buildConfigurationList = E61F6B7F97001CDE567FEE6527F4E8B2 /* Build configuration list for PBXNativeTarget "Pods-ProjectXUITests" */; @@ -246,42 +367,43 @@ ); name = "Pods-ProjectXUITests"; productName = "Pods-ProjectXUITests"; - productReference = 5210E0E2A9BE6457B9D4FD9394B65579 /* Pods_ProjectXUITests.framework */; + productReference = 6DED991DC9DDB3966A93BEB6DF15C315 /* Pods_ProjectXUITests.framework */; productType = "com.apple.product-type.framework"; }; - 8CD9126840F30ADCBC799E2EF885B001 /* Pods-ProjectXTests */ = { + 768F964FE6D39D87DEDD9546C2AAB36B /* Pods-ProjectX */ = { isa = PBXNativeTarget; - buildConfigurationList = FEEFB2C94EFEE4581187C19FF96B597C /* Build configuration list for PBXNativeTarget "Pods-ProjectXTests" */; + buildConfigurationList = F068C03EA322D2C370067F34739F7B95 /* Build configuration list for PBXNativeTarget "Pods-ProjectX" */; buildPhases = ( - 0C654DE0FC38DB8BD4F7BDF09CD728A6 /* Sources */, - ADB89E6C9738A112BC455AB7B404B44A /* Frameworks */, - AC1EFACD9DE6E899316AA41F413015B0 /* Headers */, + 9A39E58BCFA3E61971CD7D4580355BF0 /* Sources */, + 3B0CD109FD613DD1279B794DC00F9BA2 /* Frameworks */, + ADF8CC690BCFA366F2318EFA03CC0F15 /* Headers */, ); buildRules = ( ); dependencies = ( - 3F891F3D150F7E2343E40B01A2AD3658 /* PBXTargetDependency */, + 15DCB334AD5D88D54C2E2929DA0C2A0C /* PBXTargetDependency */, ); - name = "Pods-ProjectXTests"; - productName = "Pods-ProjectXTests"; - productReference = 4ADB415C10931F4F553416263244CA4F /* Pods_ProjectXTests.framework */; + name = "Pods-ProjectX"; + productName = "Pods-ProjectX"; + productReference = 6FA8A74480C0CBE7684F3C66CA463B01 /* Pods_ProjectX.framework */; productType = "com.apple.product-type.framework"; }; - 90782591CAF58E3FAC57594F0C5B3177 /* Pods-ProjectX */ = { + 8CD9126840F30ADCBC799E2EF885B001 /* Pods-ProjectXTests */ = { isa = PBXNativeTarget; - buildConfigurationList = 4E3FDDBF15FF30F3157291EF23996139 /* Build configuration list for PBXNativeTarget "Pods-ProjectX" */; + buildConfigurationList = FEEFB2C94EFEE4581187C19FF96B597C /* Build configuration list for PBXNativeTarget "Pods-ProjectXTests" */; buildPhases = ( - D2879C92891E1C40B06AAD4AA19B8969 /* Sources */, - 3E9A6B14B8D1DF797AE52CB44CDB96FB /* Frameworks */, - 644167AFD11AFA45B8A8D26342F1A96B /* Headers */, + 0C654DE0FC38DB8BD4F7BDF09CD728A6 /* Sources */, + ADB89E6C9738A112BC455AB7B404B44A /* Frameworks */, + AC1EFACD9DE6E899316AA41F413015B0 /* Headers */, ); buildRules = ( ); dependencies = ( + 3F891F3D150F7E2343E40B01A2AD3658 /* PBXTargetDependency */, ); - name = "Pods-ProjectX"; - productName = "Pods-ProjectX"; - productReference = A1F51742D388FCC3EEA4DC525E0FC4A3 /* Pods_ProjectX.framework */; + name = "Pods-ProjectXTests"; + productName = "Pods-ProjectXTests"; + productReference = 6C690E2A9F1189BF962293860A419B0E /* Pods_ProjectXTests.framework */; productType = "com.apple.product-type.framework"; }; /* End PBXNativeTarget section */ @@ -301,11 +423,12 @@ en, ); mainGroup = 7DB346D0F39D3F0E887471402A8071AB; - productRefGroup = 50B0C74AA74AA589852A3A8959E54CA8 /* Products */; + productRefGroup = 78849575C95BAEEF4B546717CADDD8D8 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( - 90782591CAF58E3FAC57594F0C5B3177 /* Pods-ProjectX */, + 16297A64D8F519B9DFFF85EBEF75A597 /* EVReflection */, + 768F964FE6D39D87DEDD9546C2AAB36B /* Pods-ProjectX */, 8CD9126840F30ADCBC799E2EF885B001 /* Pods-ProjectXTests */, 6234938D11D80B3FC422F04A4C0130CB /* Pods-ProjectXUITests */, ); @@ -329,38 +452,60 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - D2879C92891E1C40B06AAD4AA19B8969 /* Sources */ = { + 896EA02A9C036F568B2734D92771BE44 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + B16BCD41FEB0C413C29D022509B7F5C1 /* ConversionOptions.swift in Sources */, + C68645588E5D3AF68DFB86F3DB3518D1 /* DeserializationStatus.swift in Sources */, + EEFBED65C004846B53DE5C177818FA2D /* EVArrayExtension.swift in Sources */, + 2B4DBF73B18FBDF203ADBBFF1FEA4543 /* EVCustomReflectable.swift in Sources */, + F6D09350B5F2C52A3448B2C10AB7D316 /* EVDictionaryExtension.swift in Sources */, + 106F53E394D3ABC4099DE1A69DD605B1 /* EVObject.swift in Sources */, + 56AC36A1233DFE8B92E3ACDEB2865CFA /* EVReflectable.swift in Sources */, + 4149B139A944EED0B567BAB79DC11B11 /* EVReflection-dummy.m in Sources */, + 8F6B9442BBF9A217EC880C8E4F5E91FA /* EVReflection.swift in Sources */, + E0EB6A6E80003A0375782FEB80CE214E /* EVWorkaroundHelpers.swift in Sources */, + 11A2606802F2CD8556892D95CCB730AB /* PrintOptions.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9A39E58BCFA3E61971CD7D4580355BF0 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 65AC74C5912D6136438160805B7C68F2 /* Pods-ProjectX-dummy.m in Sources */, + 46B8F4E1B21BED078515D240556F539F /* Pods-ProjectX-dummy.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ + 15DCB334AD5D88D54C2E2929DA0C2A0C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = EVReflection; + target = 16297A64D8F519B9DFFF85EBEF75A597 /* EVReflection */; + targetProxy = FA922E8AE223D814E1916D80C3B03A3A /* PBXContainerItemProxy */; + }; 3F891F3D150F7E2343E40B01A2AD3658 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = "Pods-ProjectX"; - target = 90782591CAF58E3FAC57594F0C5B3177 /* Pods-ProjectX */; + target = 768F964FE6D39D87DEDD9546C2AAB36B /* Pods-ProjectX */; targetProxy = 3501ED93CE17B04955EB5DED0D489C9D /* PBXContainerItemProxy */; }; 82C8D595986866A369CD0BDCA105BC06 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = "Pods-ProjectX"; - target = 90782591CAF58E3FAC57594F0C5B3177 /* Pods-ProjectX */; + target = 768F964FE6D39D87DEDD9546C2AAB36B /* Pods-ProjectX */; targetProxy = 9B9945FEE36193EF2B13A4E181CCD20B /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ - 0C9707D4EF53831E321A5483231B5D52 /* Debug */ = { + 0F6755768619F57B13D49E6FFB1CC903 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 305A9F31B46411DAB1B031159F218E01 /* Pods-ProjectX.debug.xcconfig */; + baseConfigurationReference = 8B768B344769B3ED48B03F731575232D /* EVReflection.xcconfig */; buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CLANG_ENABLE_OBJC_WEAK = NO; CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; @@ -370,35 +515,34 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-ProjectX/Info.plist"; + GCC_PREFIX_HEADER = "Target Support Files/EVReflection/EVReflection-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/EVReflection/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 11.4; + 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-ProjectX/Pods-ProjectX.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + MODULEMAP_FILE = "Target Support Files/EVReflection/EVReflection.modulemap"; + PRODUCT_MODULE_NAME = EVReflection; + PRODUCT_NAME = EVReflection; SDKROOT = iphoneos; SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 4.0; TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; - name = Debug; + name = Release; }; - 18457805E384C00B13ABF831B37C94E3 /* Release */ = { + 2FA0876FCE3CE5A2DBC955DDA1DB8FB9 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 855574B8A989C812505B042C43B00E82 /* Pods-ProjectX.release.xcconfig */; + baseConfigurationReference = 8B768B344769B3ED48B03F731575232D /* EVReflection.xcconfig */; buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CLANG_ENABLE_OBJC_WEAK = NO; CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; @@ -408,29 +552,28 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-ProjectX/Info.plist"; + GCC_PREFIX_HEADER = "Target Support Files/EVReflection/EVReflection-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/EVReflection/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 11.4; + 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-ProjectX/Pods-ProjectX.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + MODULEMAP_FILE = "Target Support Files/EVReflection/EVReflection.modulemap"; + PRODUCT_MODULE_NAME = EVReflection; + PRODUCT_NAME = EVReflection; SDKROOT = iphoneos; SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 4.0; TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; - name = Release; + name = Debug; }; 5DC0083F57E9AB706B46C5B5D73B38D8 /* Debug */ = { isa = XCBuildConfiguration; @@ -533,6 +676,46 @@ }; name = Debug; }; + 8463FD86DE9B578730B3CE45A29B1067 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 855574B8A989C812505B042C43B00E82 /* Pods-ProjectX.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-ProjectX/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 11.4; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-ProjectX/Pods-ProjectX.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; 8E6AD7F31DBF73846D0C71866067D885 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 8BC616271F9C0A95561935E0B77D0FEF /* Pods-ProjectXTests.release.xcconfig */; @@ -707,23 +890,63 @@ }; name = Debug; }; + E2BD13BA5C72A87935E16BFCA49347AF /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 305A9F31B46411DAB1B031159F218E01 /* Pods-ProjectX.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-ProjectX/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 11.4; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-ProjectX/Pods-ProjectX.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ - 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { + 159F432BBF4726F7B46458EA31E9CA43 /* Build configuration list for PBXNativeTarget "EVReflection" */ = { isa = XCConfigurationList; buildConfigurations = ( - 5DC0083F57E9AB706B46C5B5D73B38D8 /* Debug */, - AEEA80476F98EB645C4DD53EB2BB6D88 /* Release */, + 2FA0876FCE3CE5A2DBC955DDA1DB8FB9 /* Debug */, + 0F6755768619F57B13D49E6FFB1CC903 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 4E3FDDBF15FF30F3157291EF23996139 /* Build configuration list for PBXNativeTarget "Pods-ProjectX" */ = { + 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { isa = XCConfigurationList; buildConfigurations = ( - 0C9707D4EF53831E321A5483231B5D52 /* Debug */, - 18457805E384C00B13ABF831B37C94E3 /* Release */, + 5DC0083F57E9AB706B46C5B5D73B38D8 /* Debug */, + AEEA80476F98EB645C4DD53EB2BB6D88 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -737,6 +960,15 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + F068C03EA322D2C370067F34739F7B95 /* Build configuration list for PBXNativeTarget "Pods-ProjectX" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E2BD13BA5C72A87935E16BFCA49347AF /* Debug */, + 8463FD86DE9B578730B3CE45A29B1067 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; FEEFB2C94EFEE4581187C19FF96B597C /* Build configuration list for PBXNativeTarget "Pods-ProjectXTests" */ = { isa = XCConfigurationList; buildConfigurations = ( diff --git a/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/EVReflection.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/EVReflection.xcscheme new file mode 100644 index 0000000..baec8cb --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/EVReflection.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/Pods-ProjectX.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/Pods-ProjectX.xcscheme index fb8b358..23822aa 100644 --- a/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/Pods-ProjectX.xcscheme +++ b/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/Pods-ProjectX.xcscheme @@ -14,7 +14,7 @@ buildForAnalyzing = "YES"> @@ -45,7 +45,7 @@ diff --git a/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/xcschememanagement.plist b/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/xcschememanagement.plist index 7bfa801..f6db755 100644 --- a/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/xcschememanagement.plist +++ b/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/xcschememanagement.plist @@ -4,27 +4,34 @@ SchemeUserState - Pods-ProjectX.xcscheme + EVReflection.xcscheme isShown orderHint 0 - Pods-ProjectXTests.xcscheme + Pods-ProjectX.xcscheme isShown orderHint 1 - Pods-ProjectXUITests.xcscheme + Pods-ProjectXTests.xcscheme isShown orderHint 2 + Pods-ProjectXUITests.xcscheme + + isShown + + orderHint + 3 + SuppressBuildableAutocreation diff --git a/Pods/Target Support Files/EVReflection/EVReflection-dummy.m b/Pods/Target Support Files/EVReflection/EVReflection-dummy.m new file mode 100644 index 0000000..06d0a9b --- /dev/null +++ b/Pods/Target Support Files/EVReflection/EVReflection-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_EVReflection : NSObject +@end +@implementation PodsDummy_EVReflection +@end diff --git a/Pods/Target Support Files/EVReflection/EVReflection-prefix.pch b/Pods/Target Support Files/EVReflection/EVReflection-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/EVReflection/EVReflection-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/EVReflection/EVReflection-umbrella.h b/Pods/Target Support Files/EVReflection/EVReflection-umbrella.h new file mode 100644 index 0000000..ba57832 --- /dev/null +++ b/Pods/Target Support Files/EVReflection/EVReflection-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double EVReflectionVersionNumber; +FOUNDATION_EXPORT const unsigned char EVReflectionVersionString[]; + diff --git a/Pods/Target Support Files/EVReflection/EVReflection.modulemap b/Pods/Target Support Files/EVReflection/EVReflection.modulemap new file mode 100644 index 0000000..23d6581 --- /dev/null +++ b/Pods/Target Support Files/EVReflection/EVReflection.modulemap @@ -0,0 +1,6 @@ +framework module EVReflection { + umbrella header "EVReflection-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/EVReflection/EVReflection.xcconfig b/Pods/Target Support Files/EVReflection/EVReflection.xcconfig new file mode 100644 index 0000000..5c90a26 --- /dev/null +++ b/Pods/Target Support Files/EVReflection/EVReflection.xcconfig @@ -0,0 +1,11 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/EVReflection +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = -framework "Foundation" +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_TARGET_SRCROOT = ${PODS_ROOT}/EVReflection +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +SWIFT_VERSION = 4.0 diff --git a/Pods/Target Support Files/EVReflection/Info.plist b/Pods/Target Support Files/EVReflection/Info.plist new file mode 100644 index 0000000..643e600 --- /dev/null +++ b/Pods/Target Support Files/EVReflection/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 5.6.2 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-acknowledgements.markdown b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-acknowledgements.markdown index 102af75..91105db 100644 --- a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-acknowledgements.markdown +++ b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-acknowledgements.markdown @@ -1,3 +1,34 @@ # Acknowledgements This application makes use of the following third party libraries: + +## EVReflection + +MIT 3 License + +Copyright (c) 2015, EVICT B.V. +All rights reserved. +http://evict.nl, mailto://edwin@evict.nl + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: +* Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. +* Neither the name of EVICT B.V. nor the +names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + Generated by CocoaPods - https://cocoapods.org diff --git a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-acknowledgements.plist b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-acknowledgements.plist index 7acbad1..a36a999 100644 --- a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-acknowledgements.plist +++ b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-acknowledgements.plist @@ -12,6 +12,43 @@ Type PSGroupSpecifier + + FooterText + MIT 3 License + +Copyright (c) 2015, EVICT B.V. +All rights reserved. +http://evict.nl, mailto://edwin@evict.nl + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: +* Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. +* Neither the name of EVICT B.V. nor the +names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + License + MIT + Title + EVReflection + Type + PSGroupSpecifier + FooterText Generated by CocoaPods - https://cocoapods.org diff --git a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-frameworks.sh b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-frameworks.sh index 08e3eaa..08514d0 100755 --- a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-frameworks.sh +++ b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-frameworks.sh @@ -141,6 +141,13 @@ strip_invalid_archs() { STRIP_BINARY_RETVAL=1 } + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/EVReflection/EVReflection.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/EVReflection/EVReflection.framework" +fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait fi diff --git a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.debug.xcconfig b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.debug.xcconfig index 566aa02..5634160 100644 --- a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.debug.xcconfig +++ b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.debug.xcconfig @@ -1,5 +1,10 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection" 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}/EVReflection/EVReflection.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "EVReflection" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. diff --git a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.release.xcconfig b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.release.xcconfig index 566aa02..5634160 100644 --- a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.release.xcconfig +++ b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.release.xcconfig @@ -1,5 +1,10 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection" 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}/EVReflection/EVReflection.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "EVReflection" +OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. diff --git a/Pods/Target Support Files/Pods-ProjectXTests/Pods-ProjectXTests.debug.xcconfig b/Pods/Target Support Files/Pods-ProjectXTests/Pods-ProjectXTests.debug.xcconfig index 566aa02..612c2bc 100644 --- a/Pods/Target Support Files/Pods-ProjectXTests/Pods-ProjectXTests.debug.xcconfig +++ b/Pods/Target Support Files/Pods-ProjectXTests/Pods-ProjectXTests.debug.xcconfig @@ -1,5 +1,7 @@ +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection" 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}/EVReflection/EVReflection.framework/Headers" PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. diff --git a/Pods/Target Support Files/Pods-ProjectXTests/Pods-ProjectXTests.release.xcconfig b/Pods/Target Support Files/Pods-ProjectXTests/Pods-ProjectXTests.release.xcconfig index 566aa02..612c2bc 100644 --- a/Pods/Target Support Files/Pods-ProjectXTests/Pods-ProjectXTests.release.xcconfig +++ b/Pods/Target Support Files/Pods-ProjectXTests/Pods-ProjectXTests.release.xcconfig @@ -1,5 +1,7 @@ +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection" 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}/EVReflection/EVReflection.framework/Headers" PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. diff --git a/Pods/Target Support Files/Pods-ProjectXUITests/Pods-ProjectXUITests.debug.xcconfig b/Pods/Target Support Files/Pods-ProjectXUITests/Pods-ProjectXUITests.debug.xcconfig index 566aa02..612c2bc 100644 --- a/Pods/Target Support Files/Pods-ProjectXUITests/Pods-ProjectXUITests.debug.xcconfig +++ b/Pods/Target Support Files/Pods-ProjectXUITests/Pods-ProjectXUITests.debug.xcconfig @@ -1,5 +1,7 @@ +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection" 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}/EVReflection/EVReflection.framework/Headers" PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. diff --git a/Pods/Target Support Files/Pods-ProjectXUITests/Pods-ProjectXUITests.release.xcconfig b/Pods/Target Support Files/Pods-ProjectXUITests/Pods-ProjectXUITests.release.xcconfig index 566aa02..612c2bc 100644 --- a/Pods/Target Support Files/Pods-ProjectXUITests/Pods-ProjectXUITests.release.xcconfig +++ b/Pods/Target Support Files/Pods-ProjectXUITests/Pods-ProjectXUITests.release.xcconfig @@ -1,5 +1,7 @@ +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection" 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}/EVReflection/EVReflection.framework/Headers" PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. diff --git a/ProjectX.xcodeproj/project.pbxproj b/ProjectX.xcodeproj/project.pbxproj index 253072f..da90bef 100644 --- a/ProjectX.xcodeproj/project.pbxproj +++ b/ProjectX.xcodeproj/project.pbxproj @@ -176,6 +176,7 @@ E25D0D0420DE4F3A0050A254 /* Sources */, E25D0D0520DE4F3A0050A254 /* Frameworks */, E25D0D0620DE4F3A0050A254 /* Resources */, + FE1BBAD95B16B71D5E370023 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -349,6 +350,24 @@ shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; + FE1BBAD95B16B71D5E370023 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${SRCROOT}/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-frameworks.sh", + "${BUILT_PRODUCTS_DIR}/EVReflection/EVReflection.framework", + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/EVReflection.framework", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ diff --git a/ProjectX.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/xcschememanagement.plist b/ProjectX.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/xcschememanagement.plist index 6356380..c6e979b 100644 --- a/ProjectX.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/xcschememanagement.plist +++ b/ProjectX.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/xcschememanagement.plist @@ -7,7 +7,7 @@ ProjectX.xcscheme orderHint - 3 + 4 diff --git a/ProjectX.xcworkspace/xcuserdata/burcugen.xcuserdatad/UserInterfaceState.xcuserstate b/ProjectX.xcworkspace/xcuserdata/burcugen.xcuserdatad/UserInterfaceState.xcuserstate index 1a63fa4124f5a958f901b8185c20c7ff1d9fcf43..45f5f4b265d7c8d8a9bc7c1606536c5967718d52 100644 GIT binary patch delta 7534 zcmb_g33O9cw?5}wu$gl++?(9Y>A=*HIYDGBlRzo71l!- z3%N$jWM;}Dp=n5i8>2WRK{}*I97;k>P*c-}yM9joOtR#UXk`^SHq>xn7nzSbmk*=fnbL4rlJVag~E67SxLuyGKSw%LGm&rS1FL{@|NA{8Z zB!SIHmbPx2SJMy@lBnFp9SM#8X+i7_)4 z#>&_jJL6zlFv&~`lghMbT#TFP&SWw@nBL4#CZ8F`3}-YWn9)oTQ_P5rm+>(HW_$X`C%m~*I7_JN&q=1K?O2U0}En!9!V99eKLCt@m3c5CggewyLtS50)xE)Z(+F@ z{*w&Aofhkb@KKT!9?j_SzHl{@!&q9i41d5lP5?MN!w6;;kx*sHZ5RHc|Y%f%a3}e2k7z>>NiY(AVf1R$~p;VGehs z0O*g0Vh^su0h;bvcm;kN@5S%o{rFq_7rsT5ge4q_CrLCv*<=(cp_!OT9w&>*YO;k` z-z6WDvoxZA&}d#KH^?n=o52i2qZ-FZ!_DICSP||Wml={s3)raHDUPYT*YCCP(Q6xn&Bu5=kCQ4k79z-3{L#Pw#jJlw%s2l1I8qk6c^uPfR1~7uK9`!&D z)C=`SebB?yWe4gHCK~E_5QcT|B5bFhlR+Fwqury}8}#`bb@hv$@U6IAp#qlg8VGm; zK~H5cwif8;ndGYu)?1N}iXv7FL&MPsG!l(M1!y$#ph7T%1*~8LJ2=1z@sO|{6(ccn zHvRUZF=#BZLn64NXD34$%!FAK0OGLnsQz5PC>F5c-<3}#7O-qinQua-SXf8i%eQ85{{;`27Pm!1t^j8-JtNr4UXriA%%WBcHXel&@RLD4ro=3~6*)PyAt{m2I zP+rsoXhAcXatHoYJ_EHxb!b%qYoUjB^%s?eyyGLs(j&Z;rBRV=kJn#|R-?8JoBnlA z{lRO|IEXf?h#WhZo<8Y2Khv zzx<%LLZpDIsDf6|8c+e7LQ7Tbke;5N7ZCk{^ulU?QFW6>my#Dty;7*;>o`)MGXz1*U_#5w%I>(5Q$C9?LlIdUkuQcN3&l` z34!YSulL^zzBeiSX45NbDw+%JC_3ANi4sesdiSDbHE0@zYep=7`_X}Ll`gpvdLOl= zA6iIbj}M|l;hVZ9Of5PbzOHK~)R)~y=o6G!gFc21HRuRDNcnP;D!ogTu;}B@pkodC z93BEOw?9Qzz0fK2Ez;JZuPCQ|1D&8Vbg4t9DU8lQSBjbvO2!toCxk9UOuGo(B3O%2 z%}?kmN?eOBqbulV^b7hG{f2&r?vM#RpeOW#-q2?)`UCxm{-UUS0o_11;bG_tBPbYK zKp_-?IHD)baHc2d$(>Xs4v!H@4h=9ZapONCAG#a*0#wAikAswwop*&W#ywL0nk^X}@3ITz8!>hGWj$KxcVt;GpA5%OSg zEpCFF!Vnk=`FSPO(ZHzUdcqYeOM_*hXno)mv}`40Xz*LnI=~sY<%q1DOm8%V9{;3T zoPpXV>_M?F_JO~VIc|&F#mF2yFfzuyF`W-mBBgiuLof;o{z0TM-i%OOh>|PLjB?!Q zyBv29o7K}+Dy8!noA>nw(_(q92U%LSSn3H>2O2_k6lYPz1JG1F5N)AUnO5ith{Ne$ zzgSM0X1qx0p%_{nu|zl<=iBE59}Y%zR^f5jj{{H%KB$6mtB{=* z#suV`w|O%7>HRK-OW0|lP&A|UvNQ1`l)&&T2-e_7p&BSgHI&YCs>;35Ga~mQy;>+$ z;>Yp4T09p&0pnpRgz6Q{$BQYM;RSdhUIY_hB222oVdTI|U@|>&3gnNZ>Ke*_M7X=u z9=hvXLYFCyD0b@AEyp$YsjH>xR>3r?ZaU;QxKCx-sBA1P>+yzBSvmcygOPhRdI8qq z^|323%AR;5-W+jt6U+$J(9Vl?TGZF>zRG~FT%^1h6#bF#)*G@Fzlsu9u7tY}cHq|{ z;ydAy8vHsu`kx~8W+YN?;XUveJl+tgy?Fl}*9;AzIzWB<0A^F)=1|^ewPxo>_~?BR zIEL)_ILxJ)e1h)kr#0UV{}=dF#HwiizJezq)~nDim|Acee+TnnQG*3%@rC$b<5xGeaO031V@NIYsmedkV2s{nX zQ1~^KwGTfiYtey7h#DoXAyOhEa-yK!x(c3!rLYX1gXdxS8rr;Th!)w2p7y3MKpm{2 zp0A-lVt9qj5N;-ShPTW758p`@u@MK-)(|_as3A^R86kc(?JEX*%B#gd*FdC&t>2nN zn$mEQCQwsDnn5kSm?N!IcKBtvEkx2t#$7!vVKwB}OSK_w@4*6bkq&ovJ_u_Yc6K72 z@7>vr^q|2Y-AN{_hYhu~ChgP@>PZ31MY`$0fXebo{Y1}LF`S^t$RYhmR((Fn0N8jZ zpJWi8S4VP4F3E#U@G@+@n^Q8BjQD4Q$VlWM1+bas^d$2F)S+M!@ZQYk@eO+Mi$by88Vy9q3>*S$rEHAd6LX0 z3*dFw1#iG^coW`&J@7WXv!0&0n1snwWC?kiJVTx(OR2`a@DUt=Z)RXL1JgkOGXpoG zr!3K54y`6@X?)QQD6Apt;N83BO$l9MoR4%d|X40!zUEaYdCwKFUT3BT}Qqor^r|2 zYw`{GmYgQv!BIE{pTcqY3{Jr3aB>~_o`TFyejw+`1wxq)zM$Yx!k2IgzJjmm=lrcI z-iVzy7)n`n*w8MqCXDRz1p%6l2#k^XQm6&6@G)? z;VKpCd?iK+MaYpvkmCqSL2{-iN*kczpD3jFe;}BVaSW622;qil84D7K1A#JYT29Zb zoLq5YFtxYn89yoPGc8rH-E({TDudn1Jw;=;>dY5(At!AwyW<{oR+ohb(Kc!@9oLMY zle*Eg?J33~yaeyW2l2=F2tJ07<5P6-b{e0-=kR%a5nrO00wrqFoHDYTbRz@EATpec zrUSJA9j5`U^JR33_6jY=1LQC{Mn0ptzd-(A8ZiQ$ggKaaCb1*agh{6%>cDiPBe0%y z1lFI))4#3Xt3RMWu0N^&R)1FitNtp-a1xH?bexe(ImeGS8-b#&&HOMBIIG|lO718&jZ=@9Om5g+cD zF+IeLq>&xP6hzw1$Xjhe(U16Qq-*Q>4?RA?b{e zbe8l{>1^ra(&wcwNLNa0rK_ZCr0b*`q#LE1r7uf&NsmcSOaGEJl9^-=$p*@bW!18| zvQ@ITWN*v%%HEUhmwh8UFS{bUA-Btu<*D*?c}sa~d0TmVc|Uo9yiz_xzFfXSUL&uQ zua>Wse=a{QKPNvgzbL;XzouxckSjt;g<7Fe2#R<`S4B^SsPHR-it&nxifM|+6!R5f z#Y)9S#dgI`#p{YU6c-i0DP>BvGD(@H%vX+5KCY})u2Qa1u2XJMZdGnq?o__6+^f8# z{6%F^C8_$VvQ^_%vs90%=BS=fJ*irt+M#+^wO{qV>X7O~)yJw&Ri{Md}iDnR<+Rg8DJ_9Q9oFJoS9_LiJ+xQ|dbPYV}(6di9Iy zP3o7_Thv?Cd(?;2=hW9(1KXDE$_{3WSU($N$FmdJ$?Q~iIt%Oqb`cw9m$1*UOWEhx z6`otoD*Z)x7v?A5%dIjA|Q`A&02b5?U+^NZ%T zwvkq;RcjNqO|;FlEwm}xG;MorM{Or<7i~A~0PR3+jy6wQs4do(Xv?$}+R56f+UZ)* zzO3D?eNX#|_New#?PuC=v}d&!wZG|PI*rbxv+C?RXGrJL_0VPMvUP)Wxw^r+0-Z-! zq!V?eIlf-5>z~rs=-25t=r`&&>$mB5=wH+C((l$E)Su8_)c>Zx z$%SN`hH?zY88{o~;NrPNt_fuuH`k3D$PML0u8bSQRd7CT9QP=O2Yx312)~GbmS4s{&%eO0=GXG;`4{<3{APX! z|1N)!Kg@r`f5M;OPx4>#U-94Y=lQGrb^a!Q+tA4HfI(uA8El5GhGN4w!*l}}W*Qzb zJZ6|f8P;{f9bV}a3QEH;)H%Z!tavyF3& z^Nb6Oi;Q98v&N;ymyNrPdyMZG-!twvzHdBk{LFa5c+z;zc)|Fi@v`w}THkl7xqZ0-;>+3FCyIFkYA_%n;@XbA@@rd|{!mTv#Qn5!Qu-4Z;>- ztFTSjA-pCW5wIxF*~XZkZG&&J=HIZb~+#n$k_}OfFLgQ%6%L z(?HWOQ>m%kRB5U*RhuT5CYh#~mYa5&4w$|$oicrG`quQF>3h>T(|OZH(%V6v(C($Lq>DDxt}@TTxG5^Z!;e;pE2LIC@gA=#-g|I7NaG}(#+Drl4?n} zw6t`x^tTMK47B7}@+?Cv`Ih09F_v;mrKQT^w*)QYEfX!1Ej5-sma|rwHN%=`oo1bD zU0_{g4O^eJF0(#weZjiP`nq+u^)2f=)_1M@tjDaULe>k`>(-mr+cs=tY>jPkHmOZ+ zv)F7lhb`WgXlr6?W@}+fv8CBuw(hnOwt#JpZMkim?L*rcdy+lH-rC;D-q$|Jo@*a$ zA8IeKd+bGa(Ozm_X5VK2(EgeIwEc|zto;Z31^bWopX}Ei#L>v{fJ5R?J2VcRgL8xo zjxLT$$1+EqV}oO>V~=CM<9)|L$6?1Y$8pCA$4SSRj_)1k9G4u|oY=`Y8$08iDktmI zI`vN8X?Mmu)1B>{E@ua4M`w3u4`(lDA7@`@u5-Avxc#r~e|Hg=+NE*nT%60`5?p3i zGgk{&iYv{P;cDe-Lnko9%Us~v;5z0y<@(FE?^GcAMQ+cN2GWcd|Rx-NF5k zyR*BSyNA1%JKLS(&T|iOk9K?9MecI9&ppl^a6jsv>s}b^mk52ojeIfFV}I*^yBGft DI{5<~ delta 5024 zcmZu!349aP_CDvPm`r9SlSyWh32S%Rn^cyvx25b*ma;E}mIf%47D~$wIqU)=VpwFS zEdrHQL6F7e@lXVLJ{CnlKo$W(#RWG+;oTGp^5>ua(j+ryx%YhEIrH6Z)9~Aoujpay zEw(c_A);!J7F)p3-7@p_!y4E z2{;L70&o$&ftzp#eu4Y&00Av1pcTV00wXaBqcH|!@p-I{H82jn*Z>=15+-9yOu@F; z5mT`nrr|&wgc+ELgE0?B;b_dqF*p_{;}o2VGjT2kaWSsJwOE3sxDDUIy|@n#;fMGU z20q0zcmXftHN1(p7%*gvnOGRBz@B4fW?=%8nUiTuXEj(&R*ThUby!^%$GptP;@JzV z9;?q9utb)`l37dEf%RZLSufU`^0KX{LPfcDm4mr42y6Lv};}R^M?Be z7xb<>e(<=w{1IbDWena~5Y_?1T$3g>+Igr#Qw+!-a4M)!5u%_D#6v^qz+umWv9O>F z%>8f>j>6|~o?~_iuE5uD9lqyyRl#Z;ttf1dJ+U7S;TTNCX*drT;a2=Fp1@Q1Io{^w z6j?=9g+=n>#j_MPfQ{fqnZp+HLagO_W2q>)apQb>ky zNP$++8rncx{=Gf9d09R5JT<0f)S7>9$IIJX@C0XA_SYQ1OWP_dyC5$=Dc_%A2cbM= zZ|DorMbL*T7C}F%#9g-Qo&*>OnZ+;&GN>{|QB1jU77PPN3HV_M45cbmm8z9MHqSkR z!g;<34)eQO-9VS9L~0A6*Gce#55_=2|J1aU?7;=udAS++6N>qj`sE?V!o>eK8WX*3JWqgFOu@}GbWV4G?)SPd!?q8{XE&aEa@zmJ<#raZ22U6 z3C#Lu{ug0BL>I$cm`ByAMlsBT1yqA-@;X@E4ZD}G@>N(4(HkHLi(v^Yg=O#>)uP%| zhw4%sc{jic&ahSdy$05jkMp`de>bEAisd{FRet=ajNB}LR=WcK$T7jQ?y$}ZUb*m(~% zpvdwY`(Xb=)8KNWY6`p$|9Wh9kQzO)`w%{QXjkrd1dfF&auhzHCe*Z;?<$J#Ce*7j zo}>Vr;tf+ynA6mpVo#P)_bgOdW-6QxpT>Ox(q zTPZ}Ln@389WUPdh`ShsDtChy1y7}KADxgA|!ZUQWI)nR#rO|zJGA85|7W@NNtckUG zO|cerFTy(1gBvfj#U-K-UkF`}r=CSvk9tvT_f8qvxsSGt3D}fx85?0^Y(l-M5A`j< zW_%4Ts2|Up&bNHumeCknVVfdsP5o&=xnnzQ{}Azq?KuNG6^9zA3`gu7GVekIX+SW- z=?v6Qm@=i@uRHdE==IoxPsLu?n=&Yq22<90?8}E_e;h!58bKo|mtuQ&^baZMne89f zr(5>WVP)U?b}ZX;r@SoxK)cS_oi-{byX;PiKeKRXXegDZ$-?YV8b2SrL#yC08bU*9 z7-g^LL`=pU4p=?Dz2Rk`9d}NtR)B5RJ=xnhoDeG6c*-e)WNsH59Ia~sJC+9z;52@} zY~0~=%6r6KoW;i-&c-=3it-;bmrwkc|1YVq2ZZAyzITI0hiEwIDH`GuT>gwlPY8tL zDqbvu#+13(|H)ijhec2IAFjs@kC(WS#+EPfjnEP|;}#l66Q3+`JMMfY;V!)xX(j;Ed$($}tU6s_&@GyRiM?l1*_z51v{{#!I9l`?y zG?k{G=1;%l{MHFP$)ACraFf$qk$eI@f|snR$pM;1@U+QUZgd)YgiMHd3~um{Wfwy% zJH}%UDB~br!K(x9&j+j9qRgqBBE|T1@JHDfhS%{%u!}9$RE*yQQ*G4)1MQ)Qd+qT0 z@l$GtPx96CdTWO##Mghq(QonBP}_co-{Wok0e{4w@MpY(ztAk2O>^i)noIL&KD|T> zN_mxj$3O5c{)zYSFZ>&Gc*S0(h4d<|qkqvsI>cEP8sN#CoFhi%W#<+IV=7&Vv@-E2 zz?hBM`DkSdy;8(fTEr{)QI%@#T&x;6HZeCdn1}0xN~|*13RNjci)jfhrDgOQEvFTm z7#~3p#iCd=i(#>x-7EPj>d`7%O>1Z^{~o!sZdCnPx3UBVJrBi5LTsF+GhSX0)F zHK+CT0d40*A6hM^4NHN{*I6spnzdnVSvz{2w$KjRMejUj4C~0cgaUP9sjM??ppCSt zgmq=zSQ?em8?-sJW8O63Rf7rP(<51bHs~4a43^2$Zl!HyY0rln0hY~1K4X^4^4KVP zlis486dRTJkoC~5ad_`?<@Ts4*;qF58ShDKGMhqg({9?sy<7ZP)-zn9hsQ7oKMA!# zWYeK;XVo<)bJWh^5f#w=qMa;cCQo|ZwAQI<-TmVW>LlmoWCiC&E*F)S-CO777KDE9 ztQ&R98K}zTT_Ts=DcFIJyslhw_rN}Ujt$__JA(`DSMhD$3CHkLJkH5}7SH2Fyo6V| zs=k3YxsHzDh{bUIT%R@P8ab6Ko6OwCP+resr!shz2-_OAB6c1Sy^oz^aBSF|6rpS1^im@esx zuIV-O+Io_nruWqQJuC&oho4-|JoVBCkW^mSS?nb)TR7Hp*o&+)o5$vJ#P`xZirPf` z>A(io75j6&`U)T4{W<(2>0NrC{~sA5L1Y;TdL>K^u;skiE7(e|u<90MkMu_+eUMk< z`h(2(>AkYXyzt4|BjDsd{#V+#$P6vLR@$+L$Hiv8^2W>Q) z%8xPA`7vfTuhTsC65GT6;1a!osg-GvDUfX%ZEkCBZ%#9(n}?bU&6CYD%rBXjo41&^ znRl4qGVe0)Hos%uXFgzl&wRps%KW+c3-ej?m*xxRugsUtSIyVV_bsX=$Iun0 zXCYGk{iS>vHQ#>uT#->u&2gQ4p(( z4aIh1PqB~KPYk4sgTzd+K%6E{7iWmG#Mxp{Tq?dMt`t{`YsD?%R&krSLp&^gCVnBF z70-(o#Y^J%;%)H<@h9=VWRfaKW=WE4l3j90HKmSHAF02TE@eoACBKv_6-wiz3DP8K ziZoAJBn71<(lTj{v`#9P)=L|t?b3mO^l#}y>9BM}Ixd}*K9f#MXQa#0ZRuC(cj>Nl zPiAtM{G4o&t#TDPR(?TFkQ>WQ2P<(=}|@*a7w zd`$jSJ}#e>Ka)?(XXJD8dHJGzNxox~Y!z)jTT@#%TcK^PZLuv-WLt0BU@Nt4wr#b2 zZo6W;X1ig#W&6%{+jd6*#jFU5sK|<@xD-RFs8m+kDua~q$~0xBGFy33S)wdemMP1X zVr8SUL)odkt?W@gRlZcdR<0}GD7TdFlwXzKmAlG4Me1wn3U!sbMqQ_t zs=L)a>O1N_^{{$WJ*NIwJ)s6pspr+p>Q(icdPDt1y{G=IK5(GJ;;=d-hs|MkRCGi+ zypD#BMvf+qW{wm`Ye!p0dq+n{x?`wgykmi5qvN3CkmDoA$Bv_ptB&s+cN`C#klhdWJq(pR3Q) z=j#jf75Zv@tzN9J*Ei_9^mp~6`j`3z{VV;lepSDw-_URB-|Bzq_g&y(t}xegE{n_R z3P>)S%Wy@xn!3_l!(3BbOI+Jrhujt1lH2L7>aOLEch_?_a3{E1xRcy1-L2eh+!NhP z+}qrH+y~u<+#k6=b{};gbARgo(tXAKwfnmJ8}|?HpWJuczq)@n!i`j8qA|mmX9SIP z#zv#m*lcVyb{V^kcZ_|;0pmmCaKQMFan87GTs5v4H;miHkH*i&FUD`i0}u0v9>Y`3 z6XA*S#CU3Z>UzAMcuze~Gf#@AQ{0)jb8$D~eu?`n?vJ=XD9e% zug6=-o9Oj>7kc-44|(-a9^Y^+E>Tt h^~L+@`I`Bf`x1TKe7$@F9zBfMqtD$>J&V9M@PDw`dWHZ1 From 140bdb81ef87e4b3d0fae34dec0888071ef33e07 Mon Sep 17 00:00:00 2001 From: Burcu Geneci Date: Thu, 2 Aug 2018 20:40:14 +0300 Subject: [PATCH 2/5] BaseModels added. --- ProjectX.xcodeproj/project.pbxproj | 20 ++++++++++++++++++++ ProjectX/Service/Model/BaseModels.swift | 16 ++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 ProjectX/Service/Model/BaseModels.swift diff --git a/ProjectX.xcodeproj/project.pbxproj b/ProjectX.xcodeproj/project.pbxproj index da90bef..fcf2c7f 100644 --- a/ProjectX.xcodeproj/project.pbxproj +++ b/ProjectX.xcodeproj/project.pbxproj @@ -10,6 +10,7 @@ 8D5E548E9EA1389F79C5E532 /* Pods_ProjectXTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 659C90B821CC3E8DDE1704C4 /* Pods_ProjectXTests.framework */; }; AB8A370CC1BBFFA3F6022451 /* Pods_ProjectXUITests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 24CCC3DFFE3507708E94E347 /* Pods_ProjectXUITests.framework */; }; C97E23EA011DD39C7D2C3F0E /* Pods_ProjectX.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 82D2DA5945F42F2A91D57748 /* Pods_ProjectX.framework */; }; + E2222F43211378A800AB33CC /* BaseModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2222F42211378A800AB33CC /* BaseModels.swift */; }; E25D0D0C20DE4F3A0050A254 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = E25D0D0B20DE4F3A0050A254 /* AppDelegate.swift */; }; E25D0D0E20DE4F3A0050A254 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E25D0D0D20DE4F3A0050A254 /* ViewController.swift */; }; E25D0D1120DE4F3A0050A254 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = E25D0D0F20DE4F3A0050A254 /* Main.storyboard */; }; @@ -46,6 +47,7 @@ A629AD170CAF598D8A5BD8BA /* Pods-ProjectX.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ProjectX.debug.xcconfig"; path = "Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.debug.xcconfig"; sourceTree = ""; }; ACBF95D0EEC860AD39502B82 /* Pods-ProjectX.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ProjectX.release.xcconfig"; path = "Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.release.xcconfig"; sourceTree = ""; }; B70FA1B5BBA6872F2F2C4247 /* Pods-ProjectXUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ProjectXUITests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-ProjectXUITests/Pods-ProjectXUITests.debug.xcconfig"; sourceTree = ""; }; + E2222F42211378A800AB33CC /* BaseModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BaseModels.swift; sourceTree = ""; }; E25D0D0820DE4F3A0050A254 /* ProjectX.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ProjectX.app; sourceTree = BUILT_PRODUCTS_DIR; }; E25D0D0B20DE4F3A0050A254 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; E25D0D0D20DE4F3A0050A254 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; @@ -112,6 +114,22 @@ name = Pods; sourceTree = ""; }; + E2222F402113787200AB33CC /* Service */ = { + isa = PBXGroup; + children = ( + E2222F412113789300AB33CC /* Model */, + ); + path = Service; + sourceTree = ""; + }; + E2222F412113789300AB33CC /* Model */ = { + isa = PBXGroup; + children = ( + E2222F42211378A800AB33CC /* BaseModels.swift */, + ); + path = Model; + sourceTree = ""; + }; E25D0CFF20DE4F3A0050A254 = { isa = PBXGroup; children = ( @@ -137,6 +155,7 @@ E25D0D0A20DE4F3A0050A254 /* ProjectX */ = { isa = PBXGroup; children = ( + E2222F402113787200AB33CC /* Service */, E25D0D0B20DE4F3A0050A254 /* AppDelegate.swift */, E25D0D0D20DE4F3A0050A254 /* ViewController.swift */, E25D0D0F20DE4F3A0050A254 /* Main.storyboard */, @@ -375,6 +394,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + E2222F43211378A800AB33CC /* BaseModels.swift in Sources */, E25D0D0E20DE4F3A0050A254 /* ViewController.swift in Sources */, E25D0D0C20DE4F3A0050A254 /* AppDelegate.swift in Sources */, ); diff --git a/ProjectX/Service/Model/BaseModels.swift b/ProjectX/Service/Model/BaseModels.swift new file mode 100644 index 0000000..8911467 --- /dev/null +++ b/ProjectX/Service/Model/BaseModels.swift @@ -0,0 +1,16 @@ +// +// BaseModel.swift +// ProjectX +// +// Created by Burcu Geneci on 2.08.2018. +// Copyright © 2018 GDG Istanbul. All rights reserved. +// + +import UIKit +import EVReflection + +class BaseModel: EVObject { } + +class BaseRequestModel : BaseModel { } + +class BaseResponseModel : BaseModel { } From 9f8039e259be355a39bedee7f080d2e50c55236e Mon Sep 17 00:00:00 2001 From: Burcu Geneci Date: Thu, 2 Aug 2018 20:44:51 +0300 Subject: [PATCH 3/5] Alamofire pod installed. --- Podfile | 5 +- Podfile.lock | 6 +- Pods/Alamofire/LICENSE | 19 + Pods/Alamofire/README.md | 242 +++++ Pods/Alamofire/Source/AFError.swift | 460 +++++++++ Pods/Alamofire/Source/Alamofire.swift | 465 +++++++++ .../Source/DispatchQueue+Alamofire.swift | 37 + Pods/Alamofire/Source/MultipartFormData.swift | 580 ++++++++++++ .../Source/NetworkReachabilityManager.swift | 233 +++++ Pods/Alamofire/Source/Notifications.swift | 55 ++ Pods/Alamofire/Source/ParameterEncoding.swift | 483 ++++++++++ Pods/Alamofire/Source/Request.swift | 654 +++++++++++++ Pods/Alamofire/Source/Response.swift | 567 +++++++++++ .../Source/ResponseSerialization.swift | 715 ++++++++++++++ Pods/Alamofire/Source/Result.swift | 300 ++++++ Pods/Alamofire/Source/ServerTrustPolicy.swift | 307 ++++++ Pods/Alamofire/Source/SessionDelegate.swift | 725 ++++++++++++++ Pods/Alamofire/Source/SessionManager.swift | 896 ++++++++++++++++++ Pods/Alamofire/Source/TaskDelegate.swift | 466 +++++++++ Pods/Alamofire/Source/Timeline.swift | 136 +++ Pods/Alamofire/Source/Validation.swift | 315 ++++++ Pods/Manifest.lock | 6 +- Pods/Pods.xcodeproj/project.pbxproj | 521 +++++++--- .../xcschemes/Alamofire.xcscheme | 60 ++ .../xcschemes/Pods-ProjectX.xcscheme | 4 +- .../xcschemes/xcschememanagement.plist | 15 +- .../Alamofire/Alamofire-dummy.m | 5 + .../Alamofire/Alamofire-prefix.pch | 12 + .../Alamofire/Alamofire-umbrella.h | 16 + .../Alamofire/Alamofire.modulemap | 6 + .../Alamofire/Alamofire.xcconfig | 9 + .../Target Support Files/Alamofire/Info.plist | 26 + .../Pods-ProjectX-acknowledgements.markdown | 23 + .../Pods-ProjectX-acknowledgements.plist | 29 + .../Pods-ProjectX/Pods-ProjectX-frameworks.sh | 2 + .../Pods-ProjectX.debug.xcconfig | 6 +- .../Pods-ProjectX.release.xcconfig | 6 +- .../Pods-ProjectXTests.debug.xcconfig | 4 +- .../Pods-ProjectXTests.release.xcconfig | 4 +- .../Pods-ProjectXUITests.debug.xcconfig | 4 +- .../Pods-ProjectXUITests.release.xcconfig | 4 +- ProjectX.xcodeproj/project.pbxproj | 2 + .../xcschemes/xcschememanagement.plist | 2 +- .../UserInterfaceState.xcuserstate | Bin 16558 -> 17274 bytes 44 files changed, 8267 insertions(+), 165 deletions(-) create mode 100644 Pods/Alamofire/LICENSE create mode 100644 Pods/Alamofire/README.md create mode 100644 Pods/Alamofire/Source/AFError.swift create mode 100644 Pods/Alamofire/Source/Alamofire.swift create mode 100644 Pods/Alamofire/Source/DispatchQueue+Alamofire.swift create mode 100644 Pods/Alamofire/Source/MultipartFormData.swift create mode 100644 Pods/Alamofire/Source/NetworkReachabilityManager.swift create mode 100644 Pods/Alamofire/Source/Notifications.swift create mode 100644 Pods/Alamofire/Source/ParameterEncoding.swift create mode 100644 Pods/Alamofire/Source/Request.swift create mode 100644 Pods/Alamofire/Source/Response.swift create mode 100644 Pods/Alamofire/Source/ResponseSerialization.swift create mode 100644 Pods/Alamofire/Source/Result.swift create mode 100644 Pods/Alamofire/Source/ServerTrustPolicy.swift create mode 100644 Pods/Alamofire/Source/SessionDelegate.swift create mode 100644 Pods/Alamofire/Source/SessionManager.swift create mode 100644 Pods/Alamofire/Source/TaskDelegate.swift create mode 100644 Pods/Alamofire/Source/Timeline.swift create mode 100644 Pods/Alamofire/Source/Validation.swift create mode 100644 Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/Alamofire.xcscheme create mode 100644 Pods/Target Support Files/Alamofire/Alamofire-dummy.m create mode 100644 Pods/Target Support Files/Alamofire/Alamofire-prefix.pch create mode 100644 Pods/Target Support Files/Alamofire/Alamofire-umbrella.h create mode 100644 Pods/Target Support Files/Alamofire/Alamofire.modulemap create mode 100644 Pods/Target Support Files/Alamofire/Alamofire.xcconfig create mode 100644 Pods/Target Support Files/Alamofire/Info.plist diff --git a/Podfile b/Podfile index 3ff166c..560741f 100644 --- a/Podfile +++ b/Podfile @@ -4,9 +4,10 @@ target 'ProjectX' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! - pod "EVReflection" # Pods for ProjectX - + pod "EVReflection" + pod 'Alamofire', '~> 4.7' + target 'ProjectXTests' do inherit! :search_paths # Pods for testing diff --git a/Podfile.lock b/Podfile.lock index 16acd90..dcf7cec 100644 --- a/Podfile.lock +++ b/Podfile.lock @@ -1,18 +1,22 @@ PODS: + - Alamofire (4.7.3) - EVReflection (5.6.2): - EVReflection/Core (= 5.6.2) - EVReflection/Core (5.6.2) DEPENDENCIES: + - Alamofire (~> 4.7) - EVReflection SPEC REPOS: https://github.com/cocoapods/specs.git: + - Alamofire - EVReflection SPEC CHECKSUMS: + Alamofire: c7287b6e5d7da964a70935e5db17046b7fde6568 EVReflection: 640322f8a3aaf78cbc3c23892476b6adb636ebf0 -PODFILE CHECKSUM: 37c990d763bcdd56cefd04cd5de41c1753bf9fd2 +PODFILE CHECKSUM: 2957bc01138d95002ce3ca76aa00047ba9e7f4ac COCOAPODS: 1.5.2 diff --git a/Pods/Alamofire/LICENSE b/Pods/Alamofire/LICENSE new file mode 100644 index 0000000..2ec3cb1 --- /dev/null +++ b/Pods/Alamofire/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Pods/Alamofire/README.md b/Pods/Alamofire/README.md new file mode 100644 index 0000000..0208252 --- /dev/null +++ b/Pods/Alamofire/README.md @@ -0,0 +1,242 @@ +![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/master/alamofire.png) + +[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg?branch=master)](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)](https://alamofire.github.io/Alamofire) +[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](https://twitter.com/AlamofireSF) +[![Gitter](https://badges.gitter.im/Alamofire/Alamofire.svg)](https://gitter.im/Alamofire/Alamofire?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +Alamofire is an HTTP networking library written in Swift. + +- [Features](#features) +- [Component Libraries](#component-libraries) +- [Requirements](#requirements) +- [Migration Guides](#migration-guides) +- [Communication](#communication) +- [Installation](#installation) +- [Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md) + - **Intro -** [Making a Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#making-a-request), [Response Handling](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-handling), [Response Validation](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-validation), [Response Caching](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-caching) + - **HTTP -** [HTTP Methods](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-methods), [Parameter Encoding](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#parameter-encoding), [HTTP Headers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-headers), [Authentication](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#authentication) + - **Large Data -** [Downloading Data to a File](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#downloading-data-to-a-file), [Uploading Data to a Server](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#uploading-data-to-a-server) + - **Tools -** [Statistical Metrics](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#statistical-metrics), [cURL Command Output](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#curl-command-output) +- [Advanced Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md) + - **URL Session -** [Session Manager](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session-manager), [Session Delegate](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session-delegate), [Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#request) + - **Routing -** [Routing Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#routing-requests), [Adapting and Retrying Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#adapting-and-retrying-requests) + - **Model Objects -** [Custom Response Serialization](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#custom-response-serialization) + - **Connection -** [Security](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#security), [Network Reachability](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#network-reachability) +- [Open Radars](#open-radars) +- [FAQ](#faq) +- [Credits](#credits) +- [Donations](#donations) +- [License](#license) + +## Features + +- [x] Chainable Request / Response Methods +- [x] URL / JSON / plist Parameter Encoding +- [x] Upload File / Data / Stream / MultipartFormData +- [x] Download File using Request or Resume Data +- [x] Authentication with URLCredential +- [x] HTTP Response Validation +- [x] Upload and Download Progress Closures with Progress +- [x] cURL Command Output +- [x] Dynamically Adapt and Retry Requests +- [x] TLS Certificate and Public Key Pinning +- [x] Network Reachability +- [x] Comprehensive Unit and Integration Test Coverage +- [x] [Complete Documentation](https://alamofire.github.io/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 `URLSession` instances not managed by Alamofire. + +## Requirements + +- iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ +- Xcode 8.3+ +- Swift 3.1+ + +## Migration Guides + +- [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md) +- [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](https://stackoverflow.com/questions/tagged/alamofire). (Tag 'alamofire') +- If you'd like to **ask a general question**, use [Stack Overflow](https://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 + +### CocoaPods + +[CocoaPods](https://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +> CocoaPods 1.1+ is required to build Alamofire 4.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, '10.0' +use_frameworks! + +target '' do + pod 'Alamofire', '~> 4.7' +end +``` + +Then, run the following command: + +```bash +$ pod install +``` + +### Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. + +You can install Carthage with [Homebrew](https://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" ~> 4.7 +``` + +Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. + +### Swift Package Manager + +The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. It is in early development, but Alamofire does support its use on supported platforms. + +Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. + +#### Swift 3 + +```swift +dependencies: [ + .Package(url: "https://github.com/Alamofire/Alamofire.git", majorVersion: 4) +] +``` + +#### Swift 4 + +```swift +dependencies: [ + .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.0.0") +] +``` + +### Manually + +If you prefer not to use any 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](https://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`, `Alamofire macOS`, `Alamofire tvOS` or `Alamofire watchOS`. + +- 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. + +## Open Radars + +The following radars have some effect on the current implementation of Alamofire. + +- [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case +- `rdar://26870455` - Background URL Session Configurations do not work in the simulator +- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` +- [`rdar://36082113`](http://openradar.appspot.com/radar?id=4942308441063424) - `URLSessionTaskMetrics` failing to link on watchOS 3.0+ + +## Resolved Radars + +The following radars have been resolved over time after being filed against the Alamofire project. + +- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage (Resolved on 9/1/17 in Xcode 9 beta 6). + +## 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. + +### What logic belongs in a Router vs. a Request Adapter? + +Simple, static data such as paths, parameters and common headers belong in the `Router`. Dynamic data such as an `Authorization` header whose value can changed based on an authentication system belongs in a `RequestAdapter`. + +The reason the dynamic data MUST be placed into the `RequestAdapter` is to support retry operations. When a `Request` is retried, the original request is not rebuilt meaning the `Router` will not be called again. The `RequestAdapter` is called again allowing the dynamic data to be updated on the original request before retrying the `Request`. + +## Credits + +Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. + +### Security Disclosure + +If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## Donations + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially stay registered as a federal non-profit organization. +Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. +Donating to the ASF will enable us to: + +- Pay our yearly legal fees to keep the non-profit in good status +- Pay for our mail servers to help us stay on top of all questions and security issues +- Potentially fund test servers to make it easier for us to test the edge cases +- Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. +We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. +With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. +If you use any of our libraries for work, see if your employers would be interested in donating. +Any amount you can donate today to help us reach our goal would be greatly appreciated. + +[![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W34WPEE74APJQ) + +## License + +Alamofire is released under the MIT license. [See LICENSE](https://github.com/Alamofire/Alamofire/blob/master/LICENSE) for details. diff --git a/Pods/Alamofire/Source/AFError.swift b/Pods/Alamofire/Source/AFError.swift new file mode 100644 index 0000000..8b90d84 --- /dev/null +++ b/Pods/Alamofire/Source/AFError.swift @@ -0,0 +1,460 @@ +// +// AFError.swift +// +// Copyright (c) 2014-2018 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 + +/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with +/// their own associated reasons. +/// +/// - invalidURL: Returned when a `URLConvertible` type fails to create a valid `URL`. +/// - parameterEncodingFailed: Returned when a parameter encoding object throws an error during the encoding process. +/// - multipartEncodingFailed: Returned when some step in the multipart encoding process fails. +/// - responseValidationFailed: Returned when a `validate()` call fails. +/// - responseSerializationFailed: Returned when a response serializer encounters an error in the serialization process. +public enum AFError: Error { + /// The underlying reason the parameter encoding error occurred. + /// + /// - missingURL: The URL request did not have a URL to encode. + /// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the + /// encoding process. + /// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during + /// encoding process. + public enum ParameterEncodingFailureReason { + case missingURL + case jsonEncodingFailed(error: Error) + case propertyListEncodingFailed(error: Error) + } + + /// The underlying reason the multipart encoding error occurred. + /// + /// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a + /// file URL. + /// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty + /// `lastPathComponent` or `pathExtension. + /// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable. + /// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw + /// an error. + /// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory. + /// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by + /// the system. + /// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided + /// threw an error. + /// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`. + /// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the + /// encoded data to disk. + /// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file + /// already exists at the provided `fileURL`. + /// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is + /// not a file URL. + /// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an + /// underlying error. + /// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with + /// underlying system error. + public enum MultipartEncodingFailureReason { + case bodyPartURLInvalid(url: URL) + case bodyPartFilenameInvalid(in: URL) + case bodyPartFileNotReachable(at: URL) + case bodyPartFileNotReachableWithError(atURL: URL, error: Error) + case bodyPartFileIsDirectory(at: URL) + case bodyPartFileSizeNotAvailable(at: URL) + case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) + case bodyPartInputStreamCreationFailed(for: URL) + + case outputStreamCreationFailed(for: URL) + case outputStreamFileAlreadyExists(at: URL) + case outputStreamURLInvalid(url: URL) + case outputStreamWriteFailed(error: Error) + + case inputStreamReadFailed(error: Error) + } + + /// The underlying reason the response validation error occurred. + /// + /// - dataFileNil: The data file containing the server response did not exist. + /// - dataFileReadFailed: The data file containing the server response could not be read. + /// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes` + /// provided did not contain wildcard type. + /// - unacceptableContentType: The response `Content-Type` did not match any type in the provided + /// `acceptableContentTypes`. + /// - unacceptableStatusCode: The response status code was not acceptable. + public enum ResponseValidationFailureReason { + case dataFileNil + case dataFileReadFailed(at: URL) + case missingContentType(acceptableContentTypes: [String]) + case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) + case unacceptableStatusCode(code: Int) + } + + /// The underlying reason the response serialization error occurred. + /// + /// - inputDataNil: The server response contained no data. + /// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length. + /// - inputFileNil: The file containing the server response did not exist. + /// - inputFileReadFailed: The file containing the server response could not be read. + /// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`. + /// - jsonSerializationFailed: JSON serialization failed with an underlying system error. + /// - propertyListSerializationFailed: Property list serialization failed with an underlying system error. + public enum ResponseSerializationFailureReason { + case inputDataNil + case inputDataNilOrZeroLength + case inputFileNil + case inputFileReadFailed(at: URL) + case stringSerializationFailed(encoding: String.Encoding) + case jsonSerializationFailed(error: Error) + case propertyListSerializationFailed(error: Error) + } + + case invalidURL(url: URLConvertible) + case parameterEncodingFailed(reason: ParameterEncodingFailureReason) + case multipartEncodingFailed(reason: MultipartEncodingFailureReason) + case responseValidationFailed(reason: ResponseValidationFailureReason) + case responseSerializationFailed(reason: ResponseSerializationFailureReason) +} + +// MARK: - Adapt Error + +struct AdaptError: Error { + let error: Error +} + +extension Error { + var underlyingAdaptError: Error? { return (self as? AdaptError)?.error } +} + +// MARK: - Error Booleans + +extension AFError { + /// Returns whether the AFError is an invalid URL error. + public var isInvalidURLError: Bool { + if case .invalidURL = self { return true } + return false + } + + /// Returns whether the AFError is a parameter encoding error. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isParameterEncodingError: Bool { + if case .parameterEncodingFailed = self { return true } + return false + } + + /// Returns whether the AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties + /// will contain the associated values. + public var isMultipartEncodingError: Bool { + if case .multipartEncodingFailed = self { return true } + return false + } + + /// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`, + /// `responseContentType`, and `responseCode` properties will contain the associated values. + public var isResponseValidationError: Bool { + if case .responseValidationFailed = self { return true } + return false + } + + /// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and + /// `underlyingError` properties will contain the associated values. + public var isResponseSerializationError: Bool { + if case .responseSerializationFailed = self { return true } + return false + } +} + +// MARK: - Convenience Properties + +extension AFError { + /// The `URLConvertible` associated with the error. + public var urlConvertible: URLConvertible? { + switch self { + case .invalidURL(let url): + return url + default: + return nil + } + } + + /// The `URL` associated with the error. + public var url: URL? { + switch self { + case .multipartEncodingFailed(let reason): + return reason.url + default: + return nil + } + } + + /// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`, + /// `.multipartEncodingFailed` or `.responseSerializationFailed` error. + public var underlyingError: Error? { + switch self { + case .parameterEncodingFailed(let reason): + return reason.underlyingError + case .multipartEncodingFailed(let reason): + return reason.underlyingError + case .responseSerializationFailed(let reason): + return reason.underlyingError + default: + return nil + } + } + + /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. + public var acceptableContentTypes: [String]? { + switch self { + case .responseValidationFailed(let reason): + return reason.acceptableContentTypes + default: + return nil + } + } + + /// The response `Content-Type` of a `.responseValidationFailed` error. + public var responseContentType: String? { + switch self { + case .responseValidationFailed(let reason): + return reason.responseContentType + default: + return nil + } + } + + /// The response code of a `.responseValidationFailed` error. + public var responseCode: Int? { + switch self { + case .responseValidationFailed(let reason): + return reason.responseCode + default: + return nil + } + } + + /// The `String.Encoding` associated with a failed `.stringResponse()` call. + public var failedStringEncoding: String.Encoding? { + switch self { + case .responseSerializationFailed(let reason): + return reason.failedStringEncoding + default: + return nil + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var underlyingError: Error? { + switch self { + case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error): + return error + default: + return nil + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var url: URL? { + switch self { + case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url), + .bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url), + .bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url), + .outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url), + .bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _): + return url + default: + return nil + } + } + + var underlyingError: Error? { + switch self { + case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error), + .outputStreamWriteFailed(let error), .inputStreamReadFailed(let error): + return error + default: + return nil + } + } +} + +extension AFError.ResponseValidationFailureReason { + var acceptableContentTypes: [String]? { + switch self { + case .missingContentType(let types), .unacceptableContentType(let types, _): + return types + default: + return nil + } + } + + var responseContentType: String? { + switch self { + case .unacceptableContentType(_, let responseType): + return responseType + default: + return nil + } + } + + var responseCode: Int? { + switch self { + case .unacceptableStatusCode(let code): + return code + default: + return nil + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var failedStringEncoding: String.Encoding? { + switch self { + case .stringSerializationFailed(let encoding): + return encoding + default: + return nil + } + } + + var underlyingError: Error? { + switch self { + case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error): + return error + default: + return nil + } + } +} + +// MARK: - Error Descriptions + +extension AFError: LocalizedError { + public var errorDescription: String? { + switch self { + case .invalidURL(let url): + return "URL is not valid: \(url)" + case .parameterEncodingFailed(let reason): + return reason.localizedDescription + case .multipartEncodingFailed(let reason): + return reason.localizedDescription + case .responseValidationFailed(let reason): + return reason.localizedDescription + case .responseSerializationFailed(let reason): + return reason.localizedDescription + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var localizedDescription: String { + switch self { + case .missingURL: + return "URL request to encode was missing a URL" + case .jsonEncodingFailed(let error): + return "JSON could not be encoded because of error:\n\(error.localizedDescription)" + case .propertyListEncodingFailed(let error): + return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var localizedDescription: String { + switch self { + case .bodyPartURLInvalid(let url): + return "The URL provided is not a file URL: \(url)" + case .bodyPartFilenameInvalid(let url): + return "The URL provided does not have a valid filename: \(url)" + case .bodyPartFileNotReachable(let url): + return "The URL provided is not reachable: \(url)" + case .bodyPartFileNotReachableWithError(let url, let error): + return ( + "The system returned an error while checking the provided URL for " + + "reachability.\nURL: \(url)\nError: \(error)" + ) + case .bodyPartFileIsDirectory(let url): + return "The URL provided is a directory: \(url)" + case .bodyPartFileSizeNotAvailable(let url): + return "Could not fetch the file size from the provided URL: \(url)" + case .bodyPartFileSizeQueryFailedWithError(let url, let error): + return ( + "The system returned an error while attempting to fetch the file size from the " + + "provided URL.\nURL: \(url)\nError: \(error)" + ) + case .bodyPartInputStreamCreationFailed(let url): + return "Failed to create an InputStream for the provided URL: \(url)" + case .outputStreamCreationFailed(let url): + return "Failed to create an OutputStream for URL: \(url)" + case .outputStreamFileAlreadyExists(let url): + return "A file already exists at the provided URL: \(url)" + case .outputStreamURLInvalid(let url): + return "The provided OutputStream URL is invalid: \(url)" + case .outputStreamWriteFailed(let error): + return "OutputStream write failed with error: \(error)" + case .inputStreamReadFailed(let error): + return "InputStream read failed with error: \(error)" + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var localizedDescription: String { + switch self { + case .inputDataNil: + return "Response could not be serialized, input data was nil." + case .inputDataNilOrZeroLength: + return "Response could not be serialized, input data was nil or zero length." + case .inputFileNil: + return "Response could not be serialized, input file was nil." + case .inputFileReadFailed(let url): + return "Response could not be serialized, input file could not be read: \(url)." + case .stringSerializationFailed(let encoding): + return "String could not be serialized with encoding: \(encoding)." + case .jsonSerializationFailed(let error): + return "JSON could not be serialized because of error:\n\(error.localizedDescription)" + case .propertyListSerializationFailed(let error): + return "PropertyList could not be serialized because of error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.ResponseValidationFailureReason { + var localizedDescription: String { + switch self { + case .dataFileNil: + return "Response could not be validated, data file was nil." + case .dataFileReadFailed(let url): + return "Response could not be validated, data file could not be read: \(url)." + case .missingContentType(let types): + return ( + "Response Content-Type was missing and acceptable content types " + + "(\(types.joined(separator: ","))) do not match \"*/*\"." + ) + case .unacceptableContentType(let acceptableTypes, let responseType): + return ( + "Response Content-Type \"\(responseType)\" does not match any acceptable types: " + + "\(acceptableTypes.joined(separator: ","))." + ) + case .unacceptableStatusCode(let code): + return "Response status code was unacceptable: \(code)." + } + } +} diff --git a/Pods/Alamofire/Source/Alamofire.swift b/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 0000000..2fcc05c --- /dev/null +++ b/Pods/Alamofire/Source/Alamofire.swift @@ -0,0 +1,465 @@ +// +// Alamofire.swift +// +// Copyright (c) 2014-2018 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 + +/// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct +/// URL requests. +public protocol URLConvertible { + /// Returns a URL that conforms to RFC 2396 or throws an `Error`. + /// + /// - throws: An `Error` if the type cannot be converted to a `URL`. + /// + /// - returns: A URL or throws an `Error`. + func asURL() throws -> URL +} + +extension String: URLConvertible { + /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`. + /// + /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string. + /// + /// - returns: A URL or throws an `AFError`. + public func asURL() throws -> URL { + guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } + return url + } +} + +extension URL: URLConvertible { + /// Returns self. + public func asURL() throws -> URL { return self } +} + +extension URLComponents: URLConvertible { + /// Returns a URL if `url` is not nil, otherwise throws an `Error`. + /// + /// - throws: An `AFError.invalidURL` if `url` is `nil`. + /// + /// - returns: A URL or throws an `AFError`. + public func asURL() throws -> URL { + guard let url = url else { throw AFError.invalidURL(url: self) } + return url + } +} + +// MARK: - + +/// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. +public protocol URLRequestConvertible { + /// Returns a URL request or throws if an `Error` was encountered. + /// + /// - throws: An `Error` if the underlying `URLRequest` is `nil`. + /// + /// - returns: A URL request. + func asURLRequest() throws -> URLRequest +} + +extension URLRequestConvertible { + /// The URL request. + public var urlRequest: URLRequest? { return try? asURLRequest() } +} + +extension URLRequest: URLRequestConvertible { + /// Returns a URL request or throws if an `Error` was encountered. + public func asURLRequest() throws -> URLRequest { return self } +} + +// MARK: - + +extension URLRequest { + /// Creates an instance with the specified `method`, `urlString` and `headers`. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The new `URLRequest` instance. + public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { + let url = try url.asURL() + + self.init(url: url) + + httpMethod = method.rawValue + + if let headers = headers { + for (headerField, headerValue) in headers { + setValue(headerValue, forHTTPHeaderField: headerField) + } + } + } + + func adapt(using adapter: RequestAdapter?) throws -> URLRequest { + guard let adapter = adapter else { return self } + return try adapter.adapt(self) + } +} + +// MARK: - Data Request + +/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, +/// `method`, `parameters`, `encoding` and `headers`. +/// +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.get` by default. +/// - parameter parameters: The parameters. `nil` by default. +/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `DataRequest`. +@discardableResult +public func request( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil) + -> DataRequest +{ + return SessionManager.default.request( + url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers + ) +} + +/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the +/// specified `urlRequest`. +/// +/// - parameter urlRequest: The URL request +/// +/// - returns: The created `DataRequest`. +@discardableResult +public func request(_ urlRequest: URLRequestConvertible) -> DataRequest { + return SessionManager.default.request(urlRequest) +} + +// MARK: - Download Request + +// MARK: URL Request + +/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, +/// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.get` by default. +/// - parameter parameters: The parameters. `nil` by default. +/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download( + url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + to: destination + ) +} + +/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the +/// specified `urlRequest` and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// - parameter urlRequest: The URL request. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + _ urlRequest: URLRequestConvertible, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download(urlRequest, to: destination) +} + +// MARK: Resume Data + +/// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a +/// previous request cancellation to retrieve the contents of the original request and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken +/// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the +/// data is written incorrectly and will always fail to resume the download. For more information about the bug and +/// possible workarounds, please refer to the following Stack Overflow post: +/// +/// - http://stackoverflow.com/a/39347461/1342462 +/// +/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` +/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional +/// information. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + resumingWith resumeData: Data, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download(resumingWith: resumeData, to: destination) +} + +// MARK: - Upload Request + +// MARK: File + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `file`. +/// +/// - parameter file: The file to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ fileURL: URL, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers) +} + +/// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `file`. +/// +/// - parameter file: The file to upload. +/// - parameter urlRequest: The URL request. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(fileURL, with: urlRequest) +} + +// MARK: Data + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `data`. +/// +/// - parameter data: The data to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ data: Data, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(data, to: url, method: method, headers: headers) +} + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `data`. +/// +/// - parameter data: The data to upload. +/// - parameter urlRequest: The URL request. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(data, with: urlRequest) +} + +// MARK: InputStream + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `stream`. +/// +/// - parameter stream: The stream to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(stream, to: url, method: method, headers: headers) +} + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `stream`. +/// +/// - parameter urlRequest: The URL request. +/// - parameter stream: The stream to upload. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(stream, with: urlRequest) +} + +// MARK: MultipartFormData + +/// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls +/// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`. +/// +/// 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. +/// +/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. +/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. +/// `multipartFormDataEncodingMemoryThreshold` by default. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +public func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) +{ + return SessionManager.default.upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + to: url, + method: method, + headers: headers, + encodingCompletion: encodingCompletion + ) +} + +/// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and +/// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`. +/// +/// 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. +/// +/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. +/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. +/// `multipartFormDataEncodingMemoryThreshold` by default. +/// - parameter urlRequest: The URL request. +/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +public func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + with urlRequest: URLRequestConvertible, + encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) +{ + return SessionManager.default.upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + with: urlRequest, + encodingCompletion: encodingCompletion + ) +} + +#if !os(watchOS) + +// MARK: - Stream Request + +// MARK: Hostname and Port + +/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname` +/// and `port`. +/// +/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. +/// +/// - parameter hostName: The hostname of the server to connect to. +/// - parameter port: The port of the server to connect to. +/// +/// - returns: The created `StreamRequest`. +@discardableResult +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +public func stream(withHostName hostName: String, port: Int) -> StreamRequest { + return SessionManager.default.stream(withHostName: hostName, port: port) +} + +// MARK: NetService + +/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`. +/// +/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. +/// +/// - parameter netService: The net service used to identify the endpoint. +/// +/// - returns: The created `StreamRequest`. +@discardableResult +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +public func stream(with netService: NetService) -> StreamRequest { + return SessionManager.default.stream(with: netService) +} + +#endif diff --git a/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift b/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift new file mode 100644 index 0000000..dea3ebc --- /dev/null +++ b/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift @@ -0,0 +1,37 @@ +// +// DispatchQueue+Alamofire.swift +// +// Copyright (c) 2014-2018 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 Dispatch +import Foundation + +extension DispatchQueue { + static var userInteractive: DispatchQueue { return DispatchQueue.global(qos: .userInteractive) } + static var userInitiated: DispatchQueue { return DispatchQueue.global(qos: .userInitiated) } + static var utility: DispatchQueue { return DispatchQueue.global(qos: .utility) } + static var background: DispatchQueue { return DispatchQueue.global(qos: .background) } + + func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { + asyncAfter(deadline: .now() + delay, execute: closure) + } +} diff --git a/Pods/Alamofire/Source/MultipartFormData.swift b/Pods/Alamofire/Source/MultipartFormData.swift new file mode 100644 index 0000000..057e68b --- /dev/null +++ b/Pods/Alamofire/Source/MultipartFormData.swift @@ -0,0 +1,580 @@ +// +// MultipartFormData.swift +// +// Copyright (c) 2014-2018 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(macOS) +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 +open 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(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { + 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.data(using: String.Encoding.utf8, allowLossyConversion: false)! + } + } + + class BodyPart { + let headers: HTTPHeaders + let bodyStream: InputStream + let bodyContentLength: UInt64 + var hasInitialBoundary = false + var hasFinalBoundary = false + + init(headers: HTTPHeaders, bodyStream: InputStream, 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`. + open lazy var contentType: String = "multipart/form-data; boundary=\(self.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: AFError? + 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 append(_ data: Data, withName name: String) { + let headers = contentHeaders(withName: name) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: 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 append(_ data: Data, withName name: String, mimeType: String) { + let headers = contentHeaders(withName: name, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: 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 append(_ data: Data, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: 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 append(_ fileURL: URL, withName name: String) { + let fileName = fileURL.lastPathComponent + let pathExtension = fileURL.pathExtension + + if !fileName.isEmpty && !pathExtension.isEmpty { + let mime = mimeType(forPathExtension: pathExtension) + append(fileURL, withName: name, fileName: fileName, mimeType: mime) + } else { + setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) + } + } + + /// 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 append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + + //============================================================ + // Check 1 - is file URL? + //============================================================ + + guard fileURL.isFileURL else { + setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) + return + } + + //============================================================ + // Check 2 - is file URL reachable? + //============================================================ + + do { + let isReachable = try fileURL.checkPromisedItemIsReachable() + guard isReachable else { + setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) + return + } + } catch { + setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 3 - is file URL a directory? + //============================================================ + + var isDirectory: ObjCBool = false + let path = fileURL.path + + guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { + setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) + return + } + + //============================================================ + // Check 4 - can the file size be extracted? + //============================================================ + + let bodyContentLength: UInt64 + + do { + guard let fileSize = try FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber else { + setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) + return + } + + bodyContentLength = fileSize.uint64Value + } + catch { + setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 5 - can a stream be created from file URL? + //============================================================ + + guard let stream = InputStream(url: fileURL) else { + setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) + return + } + + append(stream, withLength: bodyContentLength, 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 append( + _ stream: InputStream, + withLength length: UInt64, + name: String, + fileName: String, + mimeType: String) + { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + append(stream, withLength: 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 append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { + let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) + bodyParts.append(bodyPart) + } + + // MARK: - Data Encoding + + /// Encodes all the appended body parts into a single `Data` value. + /// + /// 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 `AFError` if encoding encounters an error. + /// + /// - returns: The encoded `Data` if encoding is successful. + public func encode() throws -> Data { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + var encoded = Data() + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + let encodedData = try encode(bodyPart) + encoded.append(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 `AFError` if encoding encounters an error. + public func writeEncodedData(to fileURL: URL) throws { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + if FileManager.default.fileExists(atPath: fileURL.path) { + throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) + } else if !fileURL.isFileURL { + throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) + } + + guard let outputStream = OutputStream(url: fileURL, append: false) else { + throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) + } + + outputStream.open() + defer { outputStream.close() } + + self.bodyParts.first?.hasInitialBoundary = true + self.bodyParts.last?.hasFinalBoundary = true + + for bodyPart in self.bodyParts { + try write(bodyPart, to: outputStream) + } + } + + // MARK: - Private - Body Part Encoding + + private func encode(_ bodyPart: BodyPart) throws -> Data { + var encoded = Data() + + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + encoded.append(initialData) + + let headerData = encodeHeaders(for: bodyPart) + encoded.append(headerData) + + let bodyStreamData = try encodeBodyStream(for: bodyPart) + encoded.append(bodyStreamData) + + if bodyPart.hasFinalBoundary { + encoded.append(finalBoundaryData()) + } + + return encoded + } + + private func encodeHeaders(for bodyPart: BodyPart) -> Data { + var headerText = "" + + for (key, value) in bodyPart.headers { + headerText += "\(key): \(value)\(EncodingCharacters.crlf)" + } + headerText += EncodingCharacters.crlf + + return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)! + } + + private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { + let inputStream = bodyPart.bodyStream + inputStream.open() + defer { inputStream.close() } + + var encoded = Data() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let error = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) + } + + if bytesRead > 0 { + encoded.append(buffer, count: bytesRead) + } else { + break + } + } + + return encoded + } + + // MARK: - Private - Writing Body Part to Output Stream + + private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { + try writeInitialBoundaryData(for: bodyPart, to: outputStream) + try writeHeaderData(for: bodyPart, to: outputStream) + try writeBodyStream(for: bodyPart, to: outputStream) + try writeFinalBoundaryData(for: bodyPart, to: outputStream) + } + + private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + return try write(initialData, to: outputStream) + } + + private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let headerData = encodeHeaders(for: bodyPart) + return try write(headerData, to: outputStream) + } + + private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let inputStream = bodyPart.bodyStream + + inputStream.open() + defer { inputStream.close() } + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let streamError = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError)) + } + + if bytesRead > 0 { + if buffer.count != bytesRead { + buffer = Array(buffer[0.. 0, outputStream.hasSpaceAvailable { + let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) + + if let error = outputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error)) + } + + bytesToWrite -= bytesWritten + + if bytesToWrite > 0 { + buffer = Array(buffer[bytesWritten.. String { + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() + { + return contentType as String + } + + return "application/octet-stream" + } + + // MARK: - Private - Content Headers + + private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] { + var disposition = "form-data; name=\"\(name)\"" + if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } + + var headers = ["Content-Disposition": disposition] + if let mimeType = mimeType { headers["Content-Type"] = mimeType } + + return headers + } + + // MARK: - Private - Boundary Encoding + + private func initialBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) + } + + private func encapsulatedBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) + } + + private func finalBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) + } + + // MARK: - Private - Errors + + private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) { + guard bodyPartError == nil else { return } + bodyPartError = AFError.multipartEncodingFailed(reason: reason) + } +} diff --git a/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/Pods/Alamofire/Source/NetworkReachabilityManager.swift new file mode 100644 index 0000000..3ff2e7f --- /dev/null +++ b/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -0,0 +1,233 @@ +// +// NetworkReachabilityManager.swift +// +// Copyright (c) 2014-2018 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. +open class NetworkReachabilityManager { + /// Defines the various states of network reachability. + /// + /// - unknown: It is unknown whether the network is reachable. + /// - notReachable: The network is not reachable. + /// - reachable: The network is reachable. + 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. + open var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } + + /// Whether the network is currently reachable over the WWAN interface. + open var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) } + + /// Whether the network is currently reachable over Ethernet or WiFi interface. + open var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } + + /// The current network reachability status. + open var networkReachabilityStatus: NetworkReachabilityStatus { + guard let flags = self.flags else { return .unknown } + return networkReachabilityStatusForFlags(flags) + } + + /// The dispatch queue to execute the `listener` closure on. + open var listenerQueue: DispatchQueue = DispatchQueue.main + + /// A closure executed when the network reachability status changes. + open var listener: Listener? + + open var flags: SCNetworkReachabilityFlags? { + var flags = SCNetworkReachabilityFlags() + + if SCNetworkReachabilityGetFlags(reachability, &flags) { + return flags + } + + return nil + } + + private let reachability: SCNetworkReachability + open var previousFlags: SCNetworkReachabilityFlags + + // MARK: - Initialization + + /// Creates a `NetworkReachabilityManager` instance with the specified host. + /// + /// - parameter host: The host used to evaluate network reachability. + /// + /// - returns: The new `NetworkReachabilityManager` instance. + public convenience init?(host: String) { + guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } + self.init(reachability: reachability) + } + + /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. + /// + /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing + /// status of the device, both IPv4 and IPv6. + /// + /// - returns: The new `NetworkReachabilityManager` instance. + public convenience init?() { + var address = sockaddr_in() + address.sin_len = UInt8(MemoryLayout.size) + address.sin_family = sa_family_t(AF_INET) + + guard let reachability = withUnsafePointer(to: &address, { pointer in + return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout.size) { + return SCNetworkReachabilityCreateWithAddress(nil, $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. + @discardableResult + open func startListening() -> Bool { + var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) + context.info = Unmanaged.passUnretained(self).toOpaque() + + let callbackEnabled = SCNetworkReachabilitySetCallback( + reachability, + { (_, flags, info) in + let reachability = Unmanaged.fromOpaque(info!).takeUnretainedValue() + reachability.notifyListener(flags) + }, + &context + ) + + let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) + + listenerQueue.async { + self.previousFlags = SCNetworkReachabilityFlags() + self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) + } + + return callbackEnabled && queueEnabled + } + + /// Stops listening for changes in network reachability status. + open 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 isNetworkReachable(with: flags) else { return .notReachable } + + var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) + + #if os(iOS) + if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) } + #endif + + return networkStatus + } + + func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool { + let isReachable = flags.contains(.reachable) + let needsConnection = flags.contains(.connectionRequired) + let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) + let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired) + + return isReachable && (!needsConnection || canConnectWithoutUserInteraction) + } +} + +// MARK: - + +extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} + +/// Returns whether the two network reachability status values are equal. +/// +/// - parameter lhs: The left-hand side value to compare. +/// - parameter rhs: The right-hand side value to compare. +/// +/// - returns: `true` if the two values are equal, `false` otherwise. +public func ==( + lhs: NetworkReachabilityManager.NetworkReachabilityStatus, + rhs: NetworkReachabilityManager.NetworkReachabilityStatus) + -> Bool +{ + switch (lhs, rhs) { + case (.unknown, .unknown): + return true + case (.notReachable, .notReachable): + return true + case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)): + return lhsConnectionType == rhsConnectionType + default: + return false + } +} + +#endif diff --git a/Pods/Alamofire/Source/Notifications.swift b/Pods/Alamofire/Source/Notifications.swift new file mode 100644 index 0000000..e1b6120 --- /dev/null +++ b/Pods/Alamofire/Source/Notifications.swift @@ -0,0 +1,55 @@ +// +// Notifications.swift +// +// Copyright (c) 2014-2018 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 Notification.Name { + /// Used as a namespace for all `URLSessionTask` related notifications. + public struct Task { + /// Posted when a `URLSessionTask` is resumed. The notification `object` contains the resumed `URLSessionTask`. + public static let DidResume = Notification.Name(rawValue: "org.alamofire.notification.name.task.didResume") + + /// Posted when a `URLSessionTask` is suspended. The notification `object` contains the suspended `URLSessionTask`. + public static let DidSuspend = Notification.Name(rawValue: "org.alamofire.notification.name.task.didSuspend") + + /// Posted when a `URLSessionTask` is cancelled. The notification `object` contains the cancelled `URLSessionTask`. + public static let DidCancel = Notification.Name(rawValue: "org.alamofire.notification.name.task.didCancel") + + /// Posted when a `URLSessionTask` is completed. The notification `object` contains the completed `URLSessionTask`. + public static let DidComplete = Notification.Name(rawValue: "org.alamofire.notification.name.task.didComplete") + } +} + +// MARK: - + +extension Notification { + /// Used as a namespace for all `Notification` user info dictionary keys. + public struct Key { + /// User info dictionary key representing the `URLSessionTask` associated with the notification. + public static let Task = "org.alamofire.notification.key.task" + + /// User info dictionary key representing the responseData associated with the notification. + public static let ResponseData = "org.alamofire.notification.key.responseData" + } +} diff --git a/Pods/Alamofire/Source/ParameterEncoding.swift b/Pods/Alamofire/Source/ParameterEncoding.swift new file mode 100644 index 0000000..4a54f2d --- /dev/null +++ b/Pods/Alamofire/Source/ParameterEncoding.swift @@ -0,0 +1,483 @@ +// +// ParameterEncoding.swift +// +// Copyright (c) 2014-2018 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 HTTPMethod: String { + case options = "OPTIONS" + case get = "GET" + case head = "HEAD" + case post = "POST" + case put = "PUT" + case patch = "PATCH" + case delete = "DELETE" + case trace = "TRACE" + case connect = "CONNECT" +} + +// MARK: - + +/// A dictionary of parameters to apply to a `URLRequest`. +public typealias Parameters = [String: Any] + +/// A type used to define how a set of parameters are applied to a `URLRequest`. +public protocol ParameterEncoding { + /// 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. + /// + /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. + /// + /// - returns: The encoded request. + func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest +} + +// MARK: - + +/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP +/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as +/// the HTTP body depends on the destination of the encoding. +/// +/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to +/// `application/x-www-form-urlencoded; charset=utf-8`. +/// +/// There is no published specification for how to encode collection types. By default 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`) is used. Optionally, `ArrayEncoding` can be used to omit the +/// square brackets appended to array keys. +/// +/// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode +/// `true` as 1 and `false` as 0. +public struct URLEncoding: ParameterEncoding { + + // MARK: Helper Types + + /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the + /// resulting URL request. + /// + /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` + /// requests and sets as the HTTP body for requests with any other HTTP method. + /// - queryString: Sets or appends encoded query string result to existing query string. + /// - httpBody: Sets encoded query string result as the HTTP body of the URL request. + public enum Destination { + case methodDependent, queryString, httpBody + } + + /// Configures how `Array` parameters are encoded. + /// + /// - brackets: An empty set of square brackets is appended to the key for every value. + /// This is the default behavior. + /// - noBrackets: No brackets are appended. The key is encoded as is. + public enum ArrayEncoding { + case brackets, noBrackets + + func encode(key: String) -> String { + switch self { + case .brackets: + return "\(key)[]" + case .noBrackets: + return key + } + } + } + + /// Configures how `Bool` parameters are encoded. + /// + /// - numeric: Encode `true` as `1` and `false` as `0`. This is the default behavior. + /// - literal: Encode `true` and `false` as string literals. + public enum BoolEncoding { + case numeric, literal + + func encode(value: Bool) -> String { + switch self { + case .numeric: + return value ? "1" : "0" + case .literal: + return value ? "true" : "false" + } + } + } + + // MARK: Properties + + /// Returns a default `URLEncoding` instance. + public static var `default`: URLEncoding { return URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.methodDependent` destination. + public static var methodDependent: URLEncoding { return URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.queryString` destination. + public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) } + + /// Returns a `URLEncoding` instance with an `.httpBody` destination. + public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) } + + /// The destination defining where the encoded query string is to be applied to the URL request. + public let destination: Destination + + /// The encoding to use for `Array` parameters. + public let arrayEncoding: ArrayEncoding + + /// The encoding to use for `Bool` parameters. + public let boolEncoding: BoolEncoding + + // MARK: Initialization + + /// Creates a `URLEncoding` instance using the specified destination. + /// + /// - parameter destination: The destination defining where the encoded query string is to be applied. + /// - parameter arrayEncoding: The encoding to use for `Array` parameters. + /// - parameter boolEncoding: The encoding to use for `Bool` parameters. + /// + /// - returns: The new `URLEncoding` instance. + public init(destination: Destination = .methodDependent, arrayEncoding: ArrayEncoding = .brackets, boolEncoding: BoolEncoding = .numeric) { + self.destination = destination + self.arrayEncoding = arrayEncoding + self.boolEncoding = boolEncoding + } + + // MARK: Encoding + + /// 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. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) { + guard let url = urlRequest.url else { + throw AFError.parameterEncodingFailed(reason: .missingURL) + } + + if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { + let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) + urlComponents.percentEncodedQuery = percentEncodedQuery + urlRequest.url = urlComponents.url + } + } else { + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) + } + + return urlRequest + } + + /// 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(fromKey key: String, value: Any) -> [(String, String)] { + var components: [(String, String)] = [] + + if let dictionary = value as? [String: Any] { + for (nestedKey, value) in dictionary { + components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) + } + } else if let array = value as? [Any] { + for value in array { + components += queryComponents(fromKey: arrayEncoding.encode(key: key), value: value) + } + } else if let value = value as? NSNumber { + if value.isBool { + components.append((escape(key), escape(boolEncoding.encode(value: value.boolValue)))) + } else { + components.append((escape(key), escape("\(value)"))) + } + } else if let bool = value as? Bool { + components.append((escape(key), escape(boolEncoding.encode(value: bool)))) + } 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 = "!$&'()*+,;=" + + var allowedCharacterSet = CharacterSet.urlQueryAllowed + allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") + + var escaped = "" + + //========================================================================================================== + // + // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few + // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no + // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more + // info, please refer to: + // + // - https://github.com/Alamofire/Alamofire/issues/206 + // + //========================================================================================================== + + if #available(iOS 8.3, *) { + escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string + } else { + let batchSize = 50 + var index = string.startIndex + + while index != string.endIndex { + let startIndex = index + let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex + let range = startIndex.. String { + var components: [(String, String)] = [] + + for key in parameters.keys.sorted(by: <) { + let value = parameters[key]! + components += queryComponents(fromKey: key, value: value) + } + return components.map { "\($0)=\($1)" }.joined(separator: "&") + } + + private func encodesParametersInURL(with method: HTTPMethod) -> Bool { + switch destination { + case .queryString: + return true + case .httpBody: + return false + default: + break + } + + switch method { + case .get, .head, .delete: + return true + default: + return false + } + } +} + +// MARK: - + +/// Uses `JSONSerialization` 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`. +public struct JSONEncoding: ParameterEncoding { + + // MARK: Properties + + /// Returns a `JSONEncoding` instance with default writing options. + public static var `default`: JSONEncoding { return JSONEncoding() } + + /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. + public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) } + + /// The options for writing the parameters as JSON data. + public let options: JSONSerialization.WritingOptions + + // MARK: Initialization + + /// Creates a `JSONEncoding` instance using the specified options. + /// + /// - parameter options: The options for writing the parameters as JSON data. + /// + /// - returns: The new `JSONEncoding` instance. + public init(options: JSONSerialization.WritingOptions = []) { + self.options = options + } + + // MARK: Encoding + + /// 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. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + do { + let data = try JSONSerialization.data(withJSONObject: parameters, options: options) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } + + /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body. + /// + /// - parameter urlRequest: The request to apply the JSON object to. + /// - parameter jsonObject: The JSON object to apply to the request. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let jsonObject = jsonObject else { return urlRequest } + + do { + let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } +} + +// MARK: - + +/// Uses `PropertyListSerialization` 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`. +public struct PropertyListEncoding: ParameterEncoding { + + // MARK: Properties + + /// Returns a default `PropertyListEncoding` instance. + public static var `default`: PropertyListEncoding { return PropertyListEncoding() } + + /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options. + public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) } + + /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options. + public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) } + + /// The property list serialization format. + public let format: PropertyListSerialization.PropertyListFormat + + /// The options for writing the parameters as plist data. + public let options: PropertyListSerialization.WriteOptions + + // MARK: Initialization + + /// Creates a `PropertyListEncoding` instance using the specified format and options. + /// + /// - parameter format: The property list serialization format. + /// - parameter options: The options for writing the parameters as plist data. + /// + /// - returns: The new `PropertyListEncoding` instance. + public init( + format: PropertyListSerialization.PropertyListFormat = .xml, + options: PropertyListSerialization.WriteOptions = 0) + { + self.format = format + self.options = options + } + + // MARK: Encoding + + /// 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. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + do { + let data = try PropertyListSerialization.data( + fromPropertyList: parameters, + format: format, + options: options + ) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error)) + } + + return urlRequest + } +} + +// MARK: - + +extension NSNumber { + fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } +} diff --git a/Pods/Alamofire/Source/Request.swift b/Pods/Alamofire/Source/Request.swift new file mode 100644 index 0000000..ea43411 --- /dev/null +++ b/Pods/Alamofire/Source/Request.swift @@ -0,0 +1,654 @@ +// +// Request.swift +// +// Copyright (c) 2014-2018 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 + +/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. +public protocol RequestAdapter { + /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result. + /// + /// - parameter urlRequest: The URL request to adapt. + /// + /// - throws: An `Error` if the adaptation encounters an error. + /// + /// - returns: The adapted `URLRequest`. + func adapt(_ urlRequest: URLRequest) throws -> URLRequest +} + +// MARK: - + +/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. +public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void + +/// A type that determines whether a request should be retried after being executed by the specified session manager +/// and encountering an error. +public protocol RequestRetrier { + /// Determines whether the `Request` should be retried by calling the `completion` closure. + /// + /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs + /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly + /// cleaned up after. + /// + /// - parameter manager: The session manager the request was executed on. + /// - parameter request: The request that failed due to the encountered error. + /// - parameter error: The error encountered when executing the request. + /// - parameter completion: The completion closure to be executed when retry decision has been determined. + func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) +} + +// MARK: - + +protocol TaskConvertible { + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask +} + +/// A dictionary of headers to apply to a `URLRequest`. +public typealias HTTPHeaders = [String: String] + +// MARK: - + +/// Responsible for sending a request and receiving the response and associated data from the server, as well as +/// managing its underlying `URLSessionTask`. +open class Request { + + // MARK: Helper Types + + /// A closure executed when monitoring upload or download progress of a request. + public typealias ProgressHandler = (Progress) -> Void + + enum RequestTask { + case data(TaskConvertible?, URLSessionTask?) + case download(TaskConvertible?, URLSessionTask?) + case upload(TaskConvertible?, URLSessionTask?) + case stream(TaskConvertible?, URLSessionTask?) + } + + // MARK: Properties + + /// The delegate for the underlying task. + open internal(set) var delegate: TaskDelegate { + get { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + return taskDelegate + } + set { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + taskDelegate = newValue + } + } + + /// The underlying task. + open var task: URLSessionTask? { return delegate.task } + + /// The session belonging to the underlying task. + public let session: URLSession + + /// The request sent or to be sent to the server. + open var request: URLRequest? { return task?.originalRequest } + + /// The response received from the server, if any. + open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } + + /// The number of times the request has been retried. + open internal(set) var retryCount: UInt = 0 + + let originalTask: TaskConvertible? + + var startTime: CFAbsoluteTime? + var endTime: CFAbsoluteTime? + + var validations: [() -> Void] = [] + + private var taskDelegate: TaskDelegate + private var taskDelegateLock = NSLock() + + // MARK: Lifecycle + + init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { + self.session = session + + switch requestTask { + case .data(let originalTask, let task): + taskDelegate = DataTaskDelegate(task: task) + self.originalTask = originalTask + case .download(let originalTask, let task): + taskDelegate = DownloadTaskDelegate(task: task) + self.originalTask = originalTask + case .upload(let originalTask, let task): + taskDelegate = UploadTaskDelegate(task: task) + self.originalTask = originalTask + case .stream(let originalTask, let task): + taskDelegate = TaskDelegate(task: task) + self.originalTask = originalTask + } + + delegate.error = error + delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } + } + + // MARK: Authentication + + /// Associates an HTTP Basic credential with the request. + /// + /// - parameter user: The user. + /// - parameter password: The password. + /// - parameter persistence: The URL credential persistence. `.ForSession` by default. + /// + /// - returns: The request. + @discardableResult + open func authenticate( + user: String, + password: String, + persistence: URLCredential.Persistence = .forSession) + -> Self + { + let credential = URLCredential(user: user, password: password, persistence: persistence) + return authenticate(usingCredential: credential) + } + + /// Associates a specified credential with the request. + /// + /// - parameter credential: The credential. + /// + /// - returns: The request. + @discardableResult + open func authenticate(usingCredential credential: URLCredential) -> Self { + delegate.credential = credential + return self + } + + /// Returns a base64 encoded basic authentication credential as an authorization header tuple. + /// + /// - parameter user: The user. + /// - parameter password: The password. + /// + /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. + open class func authorizationHeader(user: String, password: String) -> (key: String, value: String)? { + guard let data = "\(user):\(password)".data(using: .utf8) else { return nil } + + let credential = data.base64EncodedString(options: []) + + return (key: "Authorization", value: "Basic \(credential)") + } + + // MARK: State + + /// Resumes the request. + open func resume() { + guard let task = task else { delegate.queue.isSuspended = false ; return } + + if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } + + task.resume() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidResume, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } + + /// Suspends the request. + open func suspend() { + guard let task = task else { return } + + task.suspend() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidSuspend, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } + + /// Cancels the request. + open func cancel() { + guard let task = task else { return } + + task.cancel() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidCancel, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } +} + +// 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. + open 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.joined(separator: " ") + } +} + +// MARK: - CustomDebugStringConvertible + +extension Request: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, in the form of a cURL command. + open var debugDescription: String { + return cURLRepresentation() + } + + func cURLRepresentation() -> String { + var components = ["$ curl -v"] + + guard let request = self.request, + let url = request.url, + let host = url.host + else { + return "$ curl command could not be created" + } + + if let httpMethod = request.httpMethod, httpMethod != "GET" { + components.append("-X \(httpMethod)") + } + + if let credentialStorage = self.session.configuration.urlCredentialStorage { + let protectionSpace = URLProtectionSpace( + host: host, + port: url.port ?? 0, + protocol: url.scheme, + realm: host, + authenticationMethod: NSURLAuthenticationMethodHTTPBasic + ) + + if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { + for credential in credentials { + guard let user = credential.user, let password = credential.password else { continue } + components.append("-u \(user):\(password)") + } + } else { + if let credential = delegate.credential, let user = credential.user, let password = credential.password { + components.append("-u \(user):\(password)") + } + } + } + + if session.configuration.httpShouldSetCookies { + if + let cookieStorage = session.configuration.httpCookieStorage, + let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty + { + let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } + + #if swift(>=3.2) + components.append("-b \"\(string[.. URLSessionTask { + do { + let urlRequest = try self.urlRequest.adapt(using: adapter) + return queue.sync { session.dataTask(with: urlRequest) } + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + if let requestable = originalTask as? Requestable { return requestable.urlRequest } + + return nil + } + + /// The progress of fetching the response data from the server for the request. + open var progress: Progress { return dataDelegate.progress } + + var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } + + // MARK: Stream + + /// 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 server data in any `Response` object will be `nil`. + /// + /// - parameter closure: The code to be executed periodically during the lifecycle of the request. + /// + /// - returns: The request. + @discardableResult + open func stream(closure: ((Data) -> Void)? = nil) -> Self { + dataDelegate.dataStream = closure + return self + } + + // MARK: Progress + + /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is read from the server. + /// + /// - returns: The request. + @discardableResult + open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + dataDelegate.progressHandler = (closure, queue) + return self + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. +open class DownloadRequest: Request { + + // MARK: Helper Types + + /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the + /// destination URL. + public struct DownloadOptions: OptionSet { + /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. + public let rawValue: UInt + + /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. + public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) + + /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. + public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) + + /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value. + /// + /// - parameter rawValue: The raw bitmask value for the option. + /// + /// - returns: A new log level instance. + public init(rawValue: UInt) { + self.rawValue = rawValue + } + } + + /// A closure executed once a download 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 two arguments: the file URL where the temporary file should be moved and + /// the options defining how the file should be moved. + public typealias DownloadFileDestination = ( + _ temporaryURL: URL, + _ response: HTTPURLResponse) + -> (destinationURL: URL, options: DownloadOptions) + + enum Downloadable: TaskConvertible { + case request(URLRequest) + case resumeData(Data) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let task: URLSessionTask + + switch self { + case let .request(urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.downloadTask(with: urlRequest) } + case let .resumeData(resumeData): + task = queue.sync { session.downloadTask(withResumeData: resumeData) } + } + + return task + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + + if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable { + return urlRequest + } + + return nil + } + + /// The resume data of the underlying download task if available after a failure. + open var resumeData: Data? { return downloadDelegate.resumeData } + + /// The progress of downloading the response data from the server for the request. + open var progress: Progress { return downloadDelegate.progress } + + var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } + + // MARK: State + + /// Cancels the request. + open override func cancel() { + downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } + + NotificationCenter.default.post( + name: Notification.Name.Task.DidCancel, + object: self, + userInfo: [Notification.Key.Task: task as Any] + ) + } + + // MARK: Progress + + /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is read from the server. + /// + /// - returns: The request. + @discardableResult + open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + downloadDelegate.progressHandler = (closure, queue) + return self + } + + // MARK: Destination + + /// 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. + open class func suggestedDownloadDestination( + for directory: FileManager.SearchPathDirectory = .documentDirectory, + in domain: FileManager.SearchPathDomainMask = .userDomainMask) + -> DownloadFileDestination + { + return { temporaryURL, response in + let directoryURLs = FileManager.default.urls(for: directory, in: domain) + + if !directoryURLs.isEmpty { + return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) + } + + return (temporaryURL, []) + } + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. +open class UploadRequest: DataRequest { + + // MARK: Helper Types + + enum Uploadable: TaskConvertible { + case data(Data, URLRequest) + case file(URL, URLRequest) + case stream(InputStream, URLRequest) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let task: URLSessionTask + + switch self { + case let .data(data, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(with: urlRequest, from: data) } + case let .file(url, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) } + case let .stream(_, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) } + } + + return task + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + + guard let uploadable = originalTask as? Uploadable else { return nil } + + switch uploadable { + case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest): + return urlRequest + } + } + + /// The progress of uploading the payload to the server for the upload request. + open var uploadProgress: Progress { return uploadDelegate.uploadProgress } + + var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } + + // MARK: Upload Progress + + /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to + /// the server. + /// + /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress + /// of data being read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is sent to the server. + /// + /// - returns: The request. + @discardableResult + open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + uploadDelegate.uploadProgressHandler = (closure, queue) + return self + } +} + +// MARK: - + +#if !os(watchOS) + +/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +open class StreamRequest: Request { + enum Streamable: TaskConvertible { + case stream(hostName: String, port: Int) + case netService(NetService) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + let task: URLSessionTask + + switch self { + case let .stream(hostName, port): + task = queue.sync { session.streamTask(withHostName: hostName, port: port) } + case let .netService(netService): + task = queue.sync { session.streamTask(with: netService) } + } + + return task + } + } +} + +#endif diff --git a/Pods/Alamofire/Source/Response.swift b/Pods/Alamofire/Source/Response.swift new file mode 100644 index 0000000..74b1ef5 --- /dev/null +++ b/Pods/Alamofire/Source/Response.swift @@ -0,0 +1,567 @@ +// +// Response.swift +// +// Copyright (c) 2014-2018 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 data associated with an non-serialized response of a data or upload request. +public struct DefaultDataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The error encountered while executing or validating the request. + public let error: Error? + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + var _metrics: AnyObject? + + /// Creates a `DefaultDataResponse` instance from the specified parameters. + /// + /// - Parameters: + /// - request: The URL request sent to the server. + /// - response: The server's response to the URL request. + /// - data: The data returned by the server. + /// - error: The error encountered while executing or validating the request. + /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. + /// - metrics: The task metrics containing the request / response statistics. `nil` by default. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + error: Error?, + timeline: Timeline = Timeline(), + metrics: AnyObject? = nil) + { + self.request = request + self.response = response + self.data = data + self.error = error + self.timeline = timeline + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a data or upload request. +public struct DataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Value? { return result.value } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Error? { return result.error } + + var _metrics: AnyObject? + + /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. + /// + /// - 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 `DataResponse` instance. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + result: Result, + timeline: Timeline = Timeline()) + { + self.request = request + self.response = response + self.data = data + self.result = result + self.timeline = timeline + } +} + +// MARK: - + +extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// 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 + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the server data, the response serialization result and the timeline. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[Data]: \(data?.count ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") + + return output.joined(separator: "\n") + } +} + +// MARK: - + +extension DataResponse { + /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Value) -> T) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.map(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result + /// value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's + /// result is a failure, returns the same failure. + public func flatMap(_ transform: (Value) throws -> T) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.flatMap(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let withMyError = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// - Returns: A `DataResponse` instance containing the result of the transform. + public func mapError(_ transform: (Error) -> E) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.mapError(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `flatMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.flatMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `DataResponse` instance containing the result of the transform. + public func flatMapError(_ transform: (Error) throws -> E) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.flatMapError(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } +} + +// MARK: - + +/// Used to store all data associated with an non-serialized response of a download request. +public struct DefaultDownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The temporary destination URL of the data returned from the server. + public let temporaryURL: URL? + + /// The final destination URL of the data returned from the server if it was moved. + public let destinationURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The error encountered while executing or validating the request. + public let error: Error? + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + var _metrics: AnyObject? + + /// Creates a `DefaultDownloadResponse` instance from the specified parameters. + /// + /// - Parameters: + /// - request: The URL request sent to the server. + /// - response: The server's response to the URL request. + /// - temporaryURL: The temporary destination URL of the data returned from the server. + /// - destinationURL: The final destination URL of the data returned from the server if it was moved. + /// - resumeData: The resume data generated if the request was cancelled. + /// - error: The error encountered while executing or validating the request. + /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. + /// - metrics: The task metrics containing the request / response statistics. `nil` by default. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + temporaryURL: URL?, + destinationURL: URL?, + resumeData: Data?, + error: Error?, + timeline: Timeline = Timeline(), + metrics: AnyObject? = nil) + { + self.request = request + self.response = response + self.temporaryURL = temporaryURL + self.destinationURL = destinationURL + self.resumeData = resumeData + self.error = error + self.timeline = timeline + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a download request. +public struct DownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The temporary destination URL of the data returned from the server. + public let temporaryURL: URL? + + /// The final destination URL of the data returned from the server if it was moved. + public let destinationURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Value? { return result.value } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Error? { return result.error } + + var _metrics: AnyObject? + + /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. + /// + /// - parameter request: The URL request sent to the server. + /// - parameter response: The server's response to the URL request. + /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. + /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. + /// - parameter resumeData: The resume data generated if the request was cancelled. + /// - parameter result: The result of response serialization. + /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + /// + /// - returns: The new `DownloadResponse` instance. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + temporaryURL: URL?, + destinationURL: URL?, + resumeData: Data?, + result: Result, + timeline: Timeline = Timeline()) + { + self.request = request + self.response = response + self.temporaryURL = temporaryURL + self.destinationURL = destinationURL + self.resumeData = resumeData + self.result = result + self.timeline = timeline + } +} + +// MARK: - + +extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// 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 + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the temporary and destination URLs, the resume data, the response serialization result and the + /// timeline. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") + output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") + output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") + + return output.joined(separator: "\n") + } +} + +// MARK: - + +extension DownloadResponse { + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Value) -> T) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.map(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this + /// instance's result is a failure, returns the same failure. + public func flatMap(_ transform: (Value) throws -> T) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.flatMap(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let withMyError = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// - Returns: A `DownloadResponse` instance containing the result of the transform. + public func mapError(_ transform: (Error) -> E) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.mapError(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `flatMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.flatMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `DownloadResponse` instance containing the result of the transform. + public func flatMapError(_ transform: (Error) throws -> E) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.flatMapError(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } +} + +// MARK: - + +protocol Response { + /// The task metrics containing the request / response statistics. + var _metrics: AnyObject? { get set } + mutating func add(_ metrics: AnyObject?) +} + +extension Response { + mutating func add(_ metrics: AnyObject?) { + #if !os(watchOS) + guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } + guard let metrics = metrics as? URLSessionTaskMetrics else { return } + + _metrics = metrics + #endif + } +} + +// MARK: - + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DefaultDataResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DataResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DefaultDownloadResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DownloadResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} diff --git a/Pods/Alamofire/Source/ResponseSerialization.swift b/Pods/Alamofire/Source/ResponseSerialization.swift new file mode 100644 index 0000000..3333726 --- /dev/null +++ b/Pods/Alamofire/Source/ResponseSerialization.swift @@ -0,0 +1,715 @@ +// +// ResponseSerialization.swift +// +// Copyright (c) 2014-2018 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 type in which all data response serializers must conform to in order to serialize a response. +public protocol DataResponseSerializerProtocol { + /// The type of serialized object to be created by this `DataResponseSerializerType`. + associatedtype SerializedObject + + /// A closure used by response handlers that takes a request, response, data and error and returns a result. + var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result { get } +} + +// MARK: - + +/// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object. +public struct DataResponseSerializer: DataResponseSerializerProtocol { + /// The type of serialized object to be created by this `DataResponseSerializer`. + public typealias SerializedObject = Value + + /// A closure used by response handlers that takes a request, response, data and error and returns a result. + public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> 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: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - + +/// The type in which all download response serializers must conform to in order to serialize a response. +public protocol DownloadResponseSerializerProtocol { + /// The type of serialized object to be created by this `DownloadResponseSerializerType`. + associatedtype SerializedObject + + /// A closure used by response handlers that takes a request, response, url and error and returns a result. + var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result { get } +} + +// MARK: - + +/// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object. +public struct DownloadResponseSerializer: DownloadResponseSerializerProtocol { + /// The type of serialized object to be created by this `DownloadResponseSerializer`. + public typealias SerializedObject = Value + + /// A closure used by response handlers that takes a request, response, url and error and returns a result. + public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> 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: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - Timeline + +extension Request { + var timeline: Timeline { + let requestStartTime = self.startTime ?? CFAbsoluteTimeGetCurrent() + let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() + let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime + + return Timeline( + requestStartTime: requestStartTime, + initialResponseTime: initialResponseTime, + requestCompletedTime: requestCompletedTime, + serializationCompletedTime: CFAbsoluteTimeGetCurrent() + ) + } +} + +// MARK: - Default + +extension DataRequest { + /// 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. + @discardableResult + public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self { + delegate.queue.addOperation { + (queue ?? DispatchQueue.main).async { + var dataResponse = DefaultDataResponse( + request: self.request, + response: self.response, + data: self.delegate.data, + error: self.delegate.error, + timeline: self.timeline + ) + + dataResponse.add(self.delegate.metrics) + + completionHandler(dataResponse) + } + } + + 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. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + responseSerializer: T, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.delegate.data, + self.delegate.error + ) + + var dataResponse = DataResponse( + request: self.request, + response: self.response, + data: self.delegate.data, + result: result, + timeline: self.timeline + ) + + dataResponse.add(self.delegate.metrics) + + (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) } + } + + return self + } +} + +extension DownloadRequest { + /// 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. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DefaultDownloadResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + (queue ?? DispatchQueue.main).async { + var downloadResponse = DefaultDownloadResponse( + request: self.request, + response: self.response, + temporaryURL: self.downloadDelegate.temporaryURL, + destinationURL: self.downloadDelegate.destinationURL, + resumeData: self.downloadDelegate.resumeData, + error: self.downloadDelegate.error, + timeline: self.timeline + ) + + downloadResponse.add(self.delegate.metrics) + + completionHandler(downloadResponse) + } + } + + 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 contained in the destination url. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + responseSerializer: T, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.downloadDelegate.fileURL, + self.downloadDelegate.error + ) + + var downloadResponse = DownloadResponse( + request: self.request, + response: self.response, + temporaryURL: self.downloadDelegate.temporaryURL, + destinationURL: self.downloadDelegate.destinationURL, + resumeData: self.downloadDelegate.resumeData, + result: result, + timeline: self.timeline + ) + + downloadResponse.add(self.delegate.metrics) + + (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) } + } + + return self + } +} + +// MARK: - Data + +extension Request { + /// Returns a result data type that contains the response data as-is. + /// + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) } + + guard let validData = data else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) + } + + return .success(validData) + } +} + +extension DataRequest { + /// Creates a response serializer that returns the associated data as-is. + /// + /// - returns: A data response serializer. + public static func dataResponseSerializer() -> DataResponseSerializer { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseData(response: response, data: data, error: error) + } + } + + /// 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. + @discardableResult + public func responseData( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.dataResponseSerializer(), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns the associated data as-is. + /// + /// - returns: A data response serializer. + public static func dataResponseSerializer() -> DownloadResponseSerializer { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseData(response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// 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. + @discardableResult + public func responseData( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.dataResponseSerializer(), + completionHandler: completionHandler + ) + } +} + +// MARK: - String + +extension Request { + /// Returns a result string type 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. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseString( + encoding: String.Encoding?, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") } + + guard let validData = data else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) + } + + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName as CFString?, convertedEncoding == nil { + convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding( + CFStringConvertIANACharSetNameToEncoding(encodingName)) + ) + } + + let actualEncoding = convertedEncoding ?? .isoLatin1 + + if let string = String(data: validData, encoding: actualEncoding) { + return .success(string) + } else { + return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns a result string type 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: String.Encoding? = nil) -> DataResponseSerializer { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: 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. + @discardableResult + public func responseString( + queue: DispatchQueue? = nil, + encoding: String.Encoding? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns a result string type 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: String.Encoding? = nil) -> DownloadResponseSerializer { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// 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. + @discardableResult + public func responseString( + queue: DispatchQueue? = nil, + encoding: String.Encoding? = nil, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +// MARK: - JSON + +extension Request { + /// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization` + /// with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseJSON( + options: JSONSerialization.ReadingOptions, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } + + guard let validData = data, validData.count > 0 else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) + } + + do { + let json = try JSONSerialization.jsonObject(with: validData, options: options) + return .success(json) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns a JSON object result type constructed from the response data using + /// `JSONSerialization` with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// + /// - returns: A JSON object response serializer. + public static func jsonResponseSerializer( + options: JSONSerialization.ReadingOptions = .allowFragments) + -> DataResponseSerializer + { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseJSON( + queue: DispatchQueue? = nil, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.jsonResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns a JSON object result type constructed from the response data using + /// `JSONSerialization` with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// + /// - returns: A JSON object response serializer. + public static func jsonResponseSerializer( + options: JSONSerialization.ReadingOptions = .allowFragments) + -> DownloadResponseSerializer + { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseJSON( + queue: DispatchQueue? = nil, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.jsonResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +// MARK: - Property List + +extension Request { + /// Returns a plist object contained in a result type constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponsePropertyList( + options: PropertyListSerialization.ReadOptions, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } + + guard let validData = data, validData.count > 0 else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) + } + + do { + let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil) + return .success(plist) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns an object constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// + /// - returns: A property list object response serializer. + public static func propertyListResponseSerializer( + options: PropertyListSerialization.ReadOptions = []) + -> DataResponseSerializer + { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responsePropertyList( + queue: DispatchQueue? = nil, + options: PropertyListSerialization.ReadOptions = [], + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns an object constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// + /// - returns: A property list object response serializer. + public static func propertyListResponseSerializer( + options: PropertyListSerialization.ReadOptions = []) + -> DownloadResponseSerializer + { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responsePropertyList( + queue: DispatchQueue? = nil, + options: PropertyListSerialization.ReadOptions = [], + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +/// A set of HTTP response status code that do not contain response data. +private let emptyDataStatusCodes: Set = [204, 205] diff --git a/Pods/Alamofire/Source/Result.swift b/Pods/Alamofire/Source/Result.swift new file mode 100644 index 0000000..df62e12 --- /dev/null +++ b/Pods/Alamofire/Source/Result.swift @@ -0,0 +1,300 @@ +// +// Result.swift +// +// Copyright (c) 2014-2018 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)" + } + } +} + +// MARK: - Functional APIs + +extension Result { + /// Creates a `Result` instance from the result of a closure. + /// + /// A failure result is created when the closure throws, and a success result is created when the closure + /// succeeds without throwing an error. + /// + /// func someString() throws -> String { ... } + /// + /// let result = Result(value: { + /// return try someString() + /// }) + /// + /// // The type of result is Result + /// + /// The trailing closure syntax is also supported: + /// + /// let result = Result { try someString() } + /// + /// - parameter value: The closure to execute and create the result for. + public init(value: () throws -> Value) { + do { + self = try .success(value()) + } catch { + self = .failure(error) + } + } + + /// Returns the success value, or throws the failure error. + /// + /// let possibleString: Result = .success("success") + /// try print(possibleString.unwrap()) + /// // Prints "success" + /// + /// let noString: Result = .failure(error) + /// try print(noString.unwrap()) + /// // Throws error + public func unwrap() throws -> Value { + switch self { + case .success(let value): + return value + case .failure(let error): + throw error + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: Result = .success(Data()) + /// let possibleInt = possibleData.map { $0.count } + /// try print(possibleInt.unwrap()) + /// // Prints "0" + /// + /// let noData: Result = .failure(error) + /// let noInt = noData.map { $0.count } + /// try print(noInt.unwrap()) + /// // Throws error + /// + /// - parameter transform: A closure that takes the success value of the `Result` instance. + /// + /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the + /// same failure. + public func map(_ transform: (Value) -> T) -> Result { + switch self { + case .success(let value): + return .success(transform(value)) + case .failure(let error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance. + /// + /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the + /// same failure. + public func flatMap(_ transform: (Value) throws -> T) -> Result { + switch self { + case .success(let value): + do { + return try .success(transform(value)) + } catch { + return .failure(error) + } + case .failure(let error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: Result = .failure(someError) + /// let withMyError: Result = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns + /// the same instance. + public func mapError(_ transform: (Error) -> T) -> Result { + switch self { + case .failure(let error): + return .failure(transform(error)) + case .success: + return self + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `flatMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.flatMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns + /// the same instance. + public func flatMapError(_ transform: (Error) throws -> T) -> Result { + switch self { + case .failure(let error): + do { + return try .failure(transform(error)) + } catch { + return .failure(error) + } + case .success: + return self + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `withValue` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A closure that takes the success value of this instance. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func withValue(_ closure: (Value) -> Void) -> Result { + if case let .success(value) = self { closure(value) } + + return self + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `withError` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A closure that takes the success value of this instance. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func withError(_ closure: (Error) -> Void) -> Result { + if case let .failure(error) = self { closure(error) } + + return self + } + + /// Evaluates the specified closure when the `Result` is a success. + /// + /// Use the `ifSuccess` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A `Void` closure. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func ifSuccess(_ closure: () -> Void) -> Result { + if isSuccess { closure() } + + return self + } + + /// Evaluates the specified closure when the `Result` is a failure. + /// + /// Use the `ifFailure` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A `Void` closure. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func ifFailure(_ closure: () -> Void) -> Result { + if isFailure { closure() } + + return self + } +} diff --git a/Pods/Alamofire/Source/ServerTrustPolicy.swift b/Pods/Alamofire/Source/ServerTrustPolicy.swift new file mode 100644 index 0000000..7f44c8d --- /dev/null +++ b/Pods/Alamofire/Source/ServerTrustPolicy.swift @@ -0,0 +1,307 @@ +// +// ServerTrustPolicy.swift +// +// Copyright (c) 2014-2018 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. +open 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. + open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { + return policies[host] + } +} + +// MARK: - + +extension URLSession { + private struct AssociatedKeys { + static var managerKey = "URLSession.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. +/// +/// - performRevokedEvaluation: Uses the default and revoked server trust evaluations allowing you to control whether to +/// validate the host provided by the challenge as well as specify the revocation flags for +/// testing for revoked certificates. Apple platforms did not start testing for revoked +/// certificates automatically until iOS 10.1, macOS 10.12 and tvOS 10.1 which is +/// demonstrated in our TLS tests. 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 performRevokedEvaluation(validateHost: Bool, revocationFlags: CFOptionFlags) + 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 certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] { + var certificates: [SecCertificate] = [] + + let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in + bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil) + }.joined()) + + for path in paths { + if + let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, + let 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 publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for certificate in certificates(in: bundle) { + if let publicKey = publicKey(for: 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 evaluate(_ serverTrust: SecTrust, forHost 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 .performRevokedEvaluation(validateHost, revocationFlags): + let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + let revokedPolicy = SecPolicyCreateRevocation(revocationFlags) + SecTrustSetPolicies(serverTrust, [defaultPolicy, revokedPolicy] as CFTypeRef) + + 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 as CFArray) + SecTrustSetAnchorCertificatesOnly(serverTrust, true) + + serverTrustIsValid = trustIsValid(serverTrust) + } else { + let serverCertificatesDataArray = certificateData(for: serverTrust) + let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates) + + outerLoop: for serverCertificateData in serverCertificatesDataArray { + for pinnedCertificateData in pinnedCertificatesDataArray { + if serverCertificateData == 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.publicKeys(for: 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, host) + } + + return serverTrustIsValid + } + + // MARK: - Private - Trust Validation + + private func trustIsValid(_ trust: SecTrust) -> Bool { + var isValid = false + + var result = SecTrustResultType.invalid + let status = SecTrustEvaluate(trust, &result) + + if status == errSecSuccess { + let unspecified = SecTrustResultType.unspecified + let proceed = SecTrustResultType.proceed + + + isValid = result == unspecified || result == proceed + } + + return isValid + } + + // MARK: - Private - Certificate Data + + private func certificateData(for trust: SecTrust) -> [Data] { + var certificates: [SecCertificate] = [] + + for index in 0.. [Data] { + return certificates.map { SecCertificateCopyData($0) as Data } + } + + // MARK: - Private - Public Key Extraction + + private static func publicKeys(for 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, trustCreationStatus == errSecSuccess { + publicKey = SecTrustCopyPublicKey(trust) + } + + return publicKey + } +} diff --git a/Pods/Alamofire/Source/SessionDelegate.swift b/Pods/Alamofire/Source/SessionDelegate.swift new file mode 100644 index 0000000..03bcb7c --- /dev/null +++ b/Pods/Alamofire/Source/SessionDelegate.swift @@ -0,0 +1,725 @@ +// +// SessionDelegate.swift +// +// Copyright (c) 2014-2018 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 handling all delegate callbacks for the underlying session. +open class SessionDelegate: NSObject { + + // MARK: URLSessionDelegate Overrides + + /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`. + open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? + + /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. + open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`. + open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. + open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? + + // MARK: URLSessionTaskDelegate Overrides + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. + open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and + /// requires the caller to call the `completionHandler`. + open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`. + open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and + /// requires the caller to call the `completionHandler`. + open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`. + open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and + /// requires the caller to call the `completionHandler`. + open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, @escaping (InputStream?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`. + open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`. + open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? + + // MARK: URLSessionDataDelegate Overrides + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`. + open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? + + /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and + /// requires caller to call the `completionHandler`. + open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, @escaping (URLSession.ResponseDisposition) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`. + open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`. + open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. + open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? + + /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and + /// requires caller to call the `completionHandler`. + open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, @escaping (CachedURLResponse?) -> Void) -> Void)? + + // MARK: URLSessionDownloadDelegate Overrides + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`. + open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`. + open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`. + open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: URLSessionStreamDelegate Overrides + +#if !os(watchOS) + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskReadClosed as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskReadClosed = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskWriteClosed as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskWriteClosed = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskBetterRouteDiscovered as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskBetterRouteDiscovered = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? { + get { + return _streamTaskDidBecomeInputStream as? (URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void + } + set { + _streamTaskDidBecomeInputStream = newValue + } + } + + var _streamTaskReadClosed: Any? + var _streamTaskWriteClosed: Any? + var _streamTaskBetterRouteDiscovered: Any? + var _streamTaskDidBecomeInputStream: Any? + +#endif + + // MARK: Properties + + var retrier: RequestRetrier? + weak var sessionManager: SessionManager? + + var requests: [Int: Request] = [:] + private let lock = NSLock() + + /// Access the task delegate for the specified task in a thread-safe manner. + open subscript(task: URLSessionTask) -> Request? { + get { + lock.lock() ; defer { lock.unlock() } + return requests[task.taskIdentifier] + } + set { + lock.lock() ; defer { lock.unlock() } + requests[task.taskIdentifier] = newValue + } + } + + // MARK: Lifecycle + + /// Initializes the `SessionDelegate` instance. + /// + /// - returns: The new `SessionDelegate` instance. + public override init() { + super.init() + } + + // MARK: NSObject Overrides + + /// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond + /// to a specified message. + /// + /// - parameter selector: A selector that identifies a message. + /// + /// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`. + open override func responds(to selector: Selector) -> Bool { + #if !os(macOS) + if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) { + return sessionDidFinishEventsForBackgroundURLSession != nil + } + #endif + + #if !os(watchOS) + if #available(iOS 9.0, macOS 10.11, tvOS 9.0, *) { + switch selector { + case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)): + return streamTaskReadClosed != nil + case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)): + return streamTaskWriteClosed != nil + case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)): + return streamTaskBetterRouteDiscovered != nil + case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)): + return streamTaskDidBecomeInputAndOutputStreams != nil + default: + break + } + } + #endif + + switch selector { + case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)): + return sessionDidBecomeInvalidWithError != nil + case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)): + return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) + case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): + return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) + case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)): + return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) + default: + return type(of: self).instancesRespond(to: selector) + } + } +} + +// MARK: - URLSessionDelegate + +extension SessionDelegate: URLSessionDelegate { + /// 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. + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + 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. + open func urlSession( + _ session: URLSession, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + guard sessionDidReceiveChallengeWithCompletion == nil else { + sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) + return + } + + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + var credential: URLCredential? + + 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?.serverTrustPolicy(forHost: host), + let serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluate(serverTrust, forHost: host) { + disposition = .useCredential + credential = URLCredential(trust: serverTrust) + } else { + disposition = .cancelAuthenticationChallenge + } + } + } + + completionHandler(disposition, credential) + } + +#if !os(macOS) + + /// Tells the delegate that all messages enqueued for a session have been delivered. + /// + /// - parameter session: The session that no longer has any outstanding requests. + open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { + sessionDidFinishEventsForBackgroundURLSession?(session) + } + +#endif +} + +// MARK: - URLSessionTaskDelegate + +extension SessionDelegate: URLSessionTaskDelegate { + /// 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. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + guard taskWillPerformHTTPRedirectionWithCompletion == nil else { + taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) + return + } + + var redirectRequest: URLRequest? = 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. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> 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 { + delegate.urlSession( + session, + task: task, + didReceive: challenge, + completionHandler: completionHandler + ) + } else { + urlSession(session, didReceive: 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. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> 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 { + 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. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else if let delegate = self[task]?.delegate as? UploadTaskDelegate { + delegate.URLSession( + session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend + ) + } + } + +#if !os(watchOS) + + /// Tells the delegate that the session finished collecting metrics for the task. + /// + /// - parameter session: The session collecting the metrics. + /// - parameter task: The task whose metrics have been collected. + /// - parameter metrics: The collected metrics. + @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) + @objc(URLSession:task:didFinishCollectingMetrics:) + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + self[task]?.delegate.metrics = metrics + } + +#endif + + /// 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. + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + /// Executed after it is determined that the request is not going to be retried + let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in + guard let strongSelf = self else { return } + + strongSelf.taskDidComplete?(session, task, error) + + strongSelf[task]?.delegate.urlSession(session, task: task, didCompleteWithError: error) + + var userInfo: [String: Any] = [Notification.Key.Task: task] + + if let data = (strongSelf[task]?.delegate as? DataTaskDelegate)?.data { + userInfo[Notification.Key.ResponseData] = data + } + + NotificationCenter.default.post( + name: Notification.Name.Task.DidComplete, + object: strongSelf, + userInfo: userInfo + ) + + strongSelf[task] = nil + } + + guard let request = self[task], let sessionManager = sessionManager else { + completeTask(session, task, error) + return + } + + // Run all validations on the request before checking if an error occurred + request.validations.forEach { $0() } + + // Determine whether an error has occurred + var error: Error? = error + + if request.delegate.error != nil { + error = request.delegate.error + } + + /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request + /// should be retried. Otherwise, complete the task by notifying the task delegate. + if let retrier = retrier, let error = error { + retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, timeDelay in + guard shouldRetry else { completeTask(session, task, error) ; return } + + DispatchQueue.utility.after(timeDelay) { [weak self] in + guard let strongSelf = self else { return } + + let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false + + if retrySucceeded, let task = request.task { + strongSelf[task] = request + return + } else { + completeTask(session, task, error) + } + } + } + } else { + completeTask(session, task, error) + } + } +} + +// MARK: - URLSessionDataDelegate + +extension SessionDelegate: URLSessionDataDelegate { + /// 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. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) + { + guard dataTaskDidReceiveResponseWithCompletion == nil else { + dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) + return + } + + var disposition: URLSession.ResponseDisposition = .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. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didBecome downloadTask: URLSessionDownloadTask) + { + if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { + dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) + } else { + self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask) + } + } + + /// 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. + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { + delegate.urlSession(session, dataTask: dataTask, didReceive: 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. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> 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]?.delegate as? DataTaskDelegate { + delegate.urlSession( + session, + dataTask: dataTask, + willCacheResponse: proposedResponse, + completionHandler: completionHandler + ) + } else { + completionHandler(proposedResponse) + } + } +} + +// MARK: - URLSessionDownloadDelegate + +extension SessionDelegate: URLSessionDownloadDelegate { + /// 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. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) + { + if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { + downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: 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`. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } else if let delegate = self[downloadTask]?.delegate as? 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. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession( + session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes + ) + } + } +} + +// MARK: - URLSessionStreamDelegate + +#if !os(watchOS) + +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +extension SessionDelegate: URLSessionStreamDelegate { + /// Tells the delegate that the read side of the connection has been closed. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) { + 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. + open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) { + 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. + open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) { + 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. + open func urlSession( + _ session: URLSession, + streamTask: URLSessionStreamTask, + didBecome inputStream: InputStream, + outputStream: OutputStream) + { + streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream) + } +} + +#endif diff --git a/Pods/Alamofire/Source/SessionManager.swift b/Pods/Alamofire/Source/SessionManager.swift new file mode 100644 index 0000000..8779efd --- /dev/null +++ b/Pods/Alamofire/Source/SessionManager.swift @@ -0,0 +1,896 @@ +// +// SessionManager.swift +// +// Copyright (c) 2014-2018 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`. +open class SessionManager { + + // MARK: - Helper Types + + /// 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 `UploadRequest` 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: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?) + case failure(Error) + } + + // MARK: - Properties + + /// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use + /// directly for any ad hoc requests. + public static let `default`: SessionManager = { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders + + return SessionManager(configuration: configuration) + }() + + /// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. + public static let defaultHTTPHeaders: HTTPHeaders = { + // 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 = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in + let quality = 1.0 - (Double(index) * 0.1) + return "\(languageCode);q=\(quality)" + }.joined(separator: ", ") + + // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 + // Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0` + let userAgent: String = { + if let info = Bundle.main.infoDictionary { + let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" + let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" + let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" + let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" + + let osNameVersion: String = { + let version = ProcessInfo.processInfo.operatingSystemVersion + let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + + let osName: String = { + #if os(iOS) + return "iOS" + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(macOS) + return "OS X" + #elseif os(Linux) + return "Linux" + #else + return "Unknown" + #endif + }() + + return "\(osName) \(versionString)" + }() + + let alamofireVersion: String = { + guard + let afInfo = Bundle(for: SessionManager.self).infoDictionary, + let build = afInfo["CFBundleShortVersionString"] + else { return "Unknown" } + + return "Alamofire/\(build)" + }() + + return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" + } + + return "Alamofire" + }() + + return [ + "Accept-Encoding": acceptEncoding, + "Accept-Language": acceptLanguage, + "User-Agent": userAgent + ] + }() + + /// Default memory threshold used when encoding `MultipartFormData` in bytes. + public static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000 + + /// The underlying session. + public let session: URLSession + + /// 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. + open var startRequestsImmediately: Bool = true + + /// The request adapter called each time a new request is created. + open var adapter: RequestAdapter? + + /// The request retrier called each time a request encounters an error to determine whether to retry the request. + open var retrier: RequestRetrier? { + get { return delegate.retrier } + set { delegate.retrier = newValue } + } + + /// 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. + open var backgroundCompletionHandler: (() -> Void)? + + let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString) + + // MARK: - Lifecycle + + /// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`. + /// + /// - parameter configuration: The configuration used to construct the managed session. + /// `URLSessionConfiguration.default` 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 `SessionManager` instance. + public init( + configuration: URLSessionConfiguration = URLSessionConfiguration.default, + delegate: SessionDelegate = SessionDelegate(), + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + self.delegate = delegate + self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + /// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`. + /// + /// - 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 `SessionManager` instance if the URL session's delegate matches; `nil` otherwise. + public init?( + session: URLSession, + 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?) { + session.serverTrustPolicyManager = serverTrustPolicyManager + + delegate.sessionManager = self + + delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in + guard let strongSelf = self else { return } + DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() } + } + } + + deinit { + session.invalidateAndCancel() + } + + // MARK: - Data Request + + /// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding` + /// and `headers`. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.get` by default. + /// - parameter parameters: The parameters. `nil` by default. + /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `DataRequest`. + @discardableResult + open func request( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil) + -> DataRequest + { + var originalRequest: URLRequest? + + do { + originalRequest = try URLRequest(url: url, method: method, headers: headers) + let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters) + return request(encodedURLRequest) + } catch { + return request(originalRequest, failedWith: error) + } + } + + /// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `DataRequest`. + @discardableResult + open func request(_ urlRequest: URLRequestConvertible) -> DataRequest { + var originalRequest: URLRequest? + + do { + originalRequest = try urlRequest.asURLRequest() + let originalTask = DataRequest.Requestable(urlRequest: originalRequest!) + + let task = try originalTask.task(session: session, adapter: adapter, queue: queue) + let request = DataRequest(session: session, requestTask: .data(originalTask, task)) + + delegate[task] = request + + if startRequestsImmediately { request.resume() } + + return request + } catch { + return request(originalRequest, failedWith: error) + } + } + + // MARK: Private - Request Implementation + + private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest { + var requestTask: Request.RequestTask = .data(nil, nil) + + if let urlRequest = urlRequest { + let originalTask = DataRequest.Requestable(urlRequest: urlRequest) + requestTask = .data(originalTask, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError) + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: request, with: underlyingError) + } else { + if startRequestsImmediately { request.resume() } + } + + return request + } + + // MARK: - Download Request + + // MARK: URL Request + + /// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`, + /// `headers` and save them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.get` by default. + /// - parameter parameters: The parameters. `nil` by default. + /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) + return download(encodedURLRequest, to: destination) + } catch { + return download(nil, to: destination, failedWith: error) + } + } + + /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save + /// them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// 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. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + _ urlRequest: URLRequestConvertible, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + do { + let urlRequest = try urlRequest.asURLRequest() + return download(.request(urlRequest), to: destination) + } catch { + return download(nil, to: destination, failedWith: error) + } + } + + // MARK: Resume Data + + /// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve + /// the contents of the original request and save them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken + /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the + /// data is written incorrectly and will always fail to resume the download. For more information about the bug and + /// possible workarounds, please refer to the following Stack Overflow post: + /// + /// - http://stackoverflow.com/a/39347461/1342462 + /// + /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` + /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for + /// additional information. + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + resumingWith resumeData: Data, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + return download(.resumeData(resumeData), to: destination) + } + + // MARK: Private - Download Implementation + + private func download( + _ downloadable: DownloadRequest.Downloadable, + to destination: DownloadRequest.DownloadFileDestination?) + -> DownloadRequest + { + do { + let task = try downloadable.task(session: session, adapter: adapter, queue: queue) + let download = DownloadRequest(session: session, requestTask: .download(downloadable, task)) + + download.downloadDelegate.destination = destination + + delegate[task] = download + + if startRequestsImmediately { download.resume() } + + return download + } catch { + return download(downloadable, to: destination, failedWith: error) + } + } + + private func download( + _ downloadable: DownloadRequest.Downloadable?, + to destination: DownloadRequest.DownloadFileDestination?, + failedWith error: Error) + -> DownloadRequest + { + var downloadTask: Request.RequestTask = .download(nil, nil) + + if let downloadable = downloadable { + downloadTask = .download(downloadable, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + + let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError) + download.downloadDelegate.destination = destination + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: download, with: underlyingError) + } else { + if startRequestsImmediately { download.resume() } + } + + return download + } + + // MARK: - Upload Request + + // MARK: File + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter file: The file to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ fileURL: URL, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(fileURL, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter file: The file to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.file(fileURL, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: Data + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter data: The data to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ data: Data, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(data, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter data: The data to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.data(data, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: InputStream + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter stream: The stream to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(stream, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter stream: The stream to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.stream(stream, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: MultipartFormData + + /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new + /// `UploadRequest` using the `url`, `method` and `headers`. + /// + /// 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 multipartFormData: The closure used to append body parts to the `MultipartFormData`. + /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + /// `multipartFormDataEncodingMemoryThreshold` by default. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + open func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + + return upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + with: urlRequest, + encodingCompletion: encodingCompletion + ) + } catch { + DispatchQueue.main.async { encodingCompletion?(.failure(error)) } + } + } + + /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new + /// `UploadRequest` using the `urlRequest`. + /// + /// 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 multipartFormData: The closure used to append body parts to the `MultipartFormData`. + /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + /// `multipartFormDataEncodingMemoryThreshold` by default. + /// - parameter urlRequest: The URL request. + /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + open func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + with urlRequest: URLRequestConvertible, + encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) + { + DispatchQueue.global(qos: .utility).async { + let formData = MultipartFormData() + multipartFormData(formData) + + var tempFileURL: URL? + + do { + var urlRequestWithContentType = try urlRequest.asURLRequest() + urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") + + let isBackgroundSession = self.session.configuration.identifier != nil + + if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { + let data = try formData.encode() + + let encodingResult = MultipartFormDataEncodingResult.success( + request: self.upload(data, with: urlRequestWithContentType), + streamingFromDisk: false, + streamFileURL: nil + ) + + DispatchQueue.main.async { encodingCompletion?(encodingResult) } + } else { + let fileManager = FileManager.default + let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) + let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") + let fileName = UUID().uuidString + let fileURL = directoryURL.appendingPathComponent(fileName) + + tempFileURL = fileURL + + var directoryError: Error? + + // Create directory inside serial queue to ensure two threads don't do this in parallel + self.queue.sync { + do { + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) + } catch { + directoryError = error + } + } + + if let directoryError = directoryError { throw directoryError } + + try formData.writeEncodedData(to: fileURL) + + let upload = self.upload(fileURL, with: urlRequestWithContentType) + + // Cleanup the temp file once the upload is complete + upload.delegate.queue.addOperation { + do { + try FileManager.default.removeItem(at: fileURL) + } catch { + // No-op + } + } + + DispatchQueue.main.async { + let encodingResult = MultipartFormDataEncodingResult.success( + request: upload, + streamingFromDisk: true, + streamFileURL: fileURL + ) + + encodingCompletion?(encodingResult) + } + } + } catch { + // Cleanup the temp file in the event that the multipart form data encoding failed + if let tempFileURL = tempFileURL { + do { + try FileManager.default.removeItem(at: tempFileURL) + } catch { + // No-op + } + } + + DispatchQueue.main.async { encodingCompletion?(.failure(error)) } + } + } + } + + // MARK: Private - Upload Implementation + + private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest { + do { + let task = try uploadable.task(session: session, adapter: adapter, queue: queue) + let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task)) + + if case let .stream(inputStream, _) = uploadable { + upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream } + } + + delegate[task] = upload + + if startRequestsImmediately { upload.resume() } + + return upload + } catch { + return upload(uploadable, failedWith: error) + } + } + + private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest { + var uploadTask: Request.RequestTask = .upload(nil, nil) + + if let uploadable = uploadable { + uploadTask = .upload(uploadable, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError) + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: upload, with: underlyingError) + } else { + if startRequestsImmediately { upload.resume() } + } + + return upload + } + +#if !os(watchOS) + + // MARK: - Stream Request + + // MARK: Hostname and Port + + /// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter hostName: The hostname of the server to connect to. + /// - parameter port: The port of the server to connect to. + /// + /// - returns: The created `StreamRequest`. + @discardableResult + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open func stream(withHostName hostName: String, port: Int) -> StreamRequest { + return stream(.stream(hostName: hostName, port: port)) + } + + // MARK: NetService + + /// Creates a `StreamRequest` for bidirectional streaming using the `netService`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter netService: The net service used to identify the endpoint. + /// + /// - returns: The created `StreamRequest`. + @discardableResult + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open func stream(with netService: NetService) -> StreamRequest { + return stream(.netService(netService)) + } + + // MARK: Private - Stream Implementation + + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest { + do { + let task = try streamable.task(session: session, adapter: adapter, queue: queue) + let request = StreamRequest(session: session, requestTask: .stream(streamable, task)) + + delegate[task] = request + + if startRequestsImmediately { request.resume() } + + return request + } catch { + return stream(failedWith: error) + } + } + + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + private func stream(failedWith error: Error) -> StreamRequest { + let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error) + if startRequestsImmediately { stream.resume() } + return stream + } + +#endif + + // MARK: - Internal - Retry Request + + func retry(_ request: Request) -> Bool { + guard let originalTask = request.originalTask else { return false } + + do { + let task = try originalTask.task(session: session, adapter: adapter, queue: queue) + + if let originalTask = request.task { + delegate[originalTask] = nil // removes the old request to avoid endless growth + } + + request.delegate.task = task // resets all task delegate data + + request.retryCount += 1 + request.startTime = CFAbsoluteTimeGetCurrent() + request.endTime = nil + + task.resume() + + return true + } catch { + request.delegate.error = error.underlyingAdaptError ?? error + return false + } + } + + private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) { + DispatchQueue.utility.async { [weak self] in + guard let strongSelf = self else { return } + + retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in + guard let strongSelf = self else { return } + + guard shouldRetry else { + if strongSelf.startRequestsImmediately { request.resume() } + return + } + + DispatchQueue.utility.after(timeDelay) { + guard let strongSelf = self else { return } + + let retrySucceeded = strongSelf.retry(request) + + if retrySucceeded, let task = request.task { + strongSelf.delegate[task] = request + } else { + if strongSelf.startRequestsImmediately { request.resume() } + } + } + } + } + } +} diff --git a/Pods/Alamofire/Source/TaskDelegate.swift b/Pods/Alamofire/Source/TaskDelegate.swift new file mode 100644 index 0000000..8e19888 --- /dev/null +++ b/Pods/Alamofire/Source/TaskDelegate.swift @@ -0,0 +1,466 @@ +// +// TaskDelegate.swift +// +// Copyright (c) 2014-2018 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 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. +open class TaskDelegate: NSObject { + + // MARK: Properties + + /// The serial operation queue used to execute all operations after the task completes. + public let queue: OperationQueue + + /// The data returned by the server. + public var data: Data? { return nil } + + /// The error generated throughout the lifecyle of the task. + public var error: Error? + + var task: URLSessionTask? { + set { + taskLock.lock(); defer { taskLock.unlock() } + _task = newValue + } + get { + taskLock.lock(); defer { taskLock.unlock() } + return _task + } + } + + var initialResponseTime: CFAbsoluteTime? + var credential: URLCredential? + var metrics: AnyObject? // URLSessionTaskMetrics + + private var _task: URLSessionTask? { + didSet { reset() } + } + + private let taskLock = NSLock() + + // MARK: Lifecycle + + init(task: URLSessionTask?) { + _task = task + + self.queue = { + let operationQueue = OperationQueue() + + operationQueue.maxConcurrentOperationCount = 1 + operationQueue.isSuspended = true + operationQueue.qualityOfService = .utility + + return operationQueue + }() + } + + func reset() { + error = nil + initialResponseTime = nil + } + + // MARK: URLSessionTaskDelegate + + var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? + var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)? + + @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + var redirectRequest: URLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + @objc(URLSession:task:didReceiveChallenge:completionHandler:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + var credential: URLCredential? + + 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?.serverTrustPolicy(forHost: host), + let serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluate(serverTrust, forHost: host) { + disposition = .useCredential + credential = URLCredential(trust: serverTrust) + } else { + disposition = .cancelAuthenticationChallenge + } + } + } else { + if challenge.previousFailureCount > 0 { + disposition = .rejectProtectionSpace + } else { + credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) + + if credential != nil { + disposition = .useCredential + } + } + } + + completionHandler(disposition, credential) + } + + @objc(URLSession:task:needNewBodyStream:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) + { + var bodyStream: InputStream? + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + bodyStream = taskNeedNewBodyStream(session, task) + } + + completionHandler(bodyStream) + } + + @objc(URLSession:task:didCompleteWithError:) + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + if let taskDidCompleteWithError = taskDidCompleteWithError { + taskDidCompleteWithError(session, task, error) + } else { + if let error = error { + if self.error == nil { self.error = error } + + if + let downloadDelegate = self as? DownloadTaskDelegate, + let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data + { + downloadDelegate.resumeData = resumeData + } + } + + queue.isSuspended = false + } + } +} + +// MARK: - + +class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate { + + // MARK: Properties + + var dataTask: URLSessionDataTask { return task as! URLSessionDataTask } + + override var data: Data? { + if dataStream != nil { + return nil + } else { + return mutableData + } + } + + var progress: Progress + var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + var dataStream: ((_ data: Data) -> Void)? + + private var totalBytesReceived: Int64 = 0 + private var mutableData: Data + + private var expectedContentLength: Int64? + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + mutableData = Data() + progress = Progress(totalUnitCount: 0) + + super.init(task: task) + } + + override func reset() { + super.reset() + + progress = Progress(totalUnitCount: 0) + totalBytesReceived = 0 + mutableData = Data() + expectedContentLength = nil + } + + // MARK: URLSessionDataDelegate + + var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? + var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? + var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) + { + var disposition: URLSession.ResponseDisposition = .allow + + expectedContentLength = response.expectedContentLength + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didBecome downloadTask: URLSessionDownloadTask) + { + dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else { + if let dataStream = dataStream { + dataStream(data) + } else { + mutableData.append(data) + } + + let bytesReceived = Int64(data.count) + totalBytesReceived += bytesReceived + let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown + + progress.totalUnitCount = totalBytesExpected + progress.completedUnitCount = totalBytesReceived + + if let progressHandler = progressHandler { + progressHandler.queue.async { progressHandler.closure(self.progress) } + } + } + } + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) + { + var cachedResponse: CachedURLResponse? = proposedResponse + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) + } + + completionHandler(cachedResponse) + } +} + +// MARK: - + +class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate { + + // MARK: Properties + + var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask } + + var progress: Progress + var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + var resumeData: Data? + override var data: Data? { return resumeData } + + var destination: DownloadRequest.DownloadFileDestination? + + var temporaryURL: URL? + var destinationURL: URL? + + var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL } + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + progress = Progress(totalUnitCount: 0) + super.init(task: task) + } + + override func reset() { + super.reset() + + progress = Progress(totalUnitCount: 0) + resumeData = nil + } + + // MARK: URLSessionDownloadDelegate + + var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)? + var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) + { + temporaryURL = location + + guard + let destination = destination, + let response = downloadTask.response as? HTTPURLResponse + else { return } + + let result = destination(location, response) + let destinationURL = result.destinationURL + let options = result.options + + self.destinationURL = destinationURL + + do { + if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) { + try FileManager.default.removeItem(at: destinationURL) + } + + if options.contains(.createIntermediateDirectories) { + let directory = destinationURL.deletingLastPathComponent() + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + + try FileManager.default.moveItem(at: location, to: destinationURL) + } catch { + self.error = error + } + } + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + 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 + + if let progressHandler = progressHandler { + progressHandler.queue.async { progressHandler.closure(self.progress) } + } + } + } + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else { + progress.totalUnitCount = expectedTotalBytes + progress.completedUnitCount = fileOffset + } + } +} + +// MARK: - + +class UploadTaskDelegate: DataTaskDelegate { + + // MARK: Properties + + var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask } + + var uploadProgress: Progress + var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + uploadProgress = Progress(totalUnitCount: 0) + super.init(task: task) + } + + override func reset() { + super.reset() + uploadProgress = Progress(totalUnitCount: 0) + } + + // MARK: URLSessionTaskDelegate + + var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + func URLSession( + _ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else { + uploadProgress.totalUnitCount = totalBytesExpectedToSend + uploadProgress.completedUnitCount = totalBytesSent + + if let uploadProgressHandler = uploadProgressHandler { + uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) } + } + } + } +} diff --git a/Pods/Alamofire/Source/Timeline.swift b/Pods/Alamofire/Source/Timeline.swift new file mode 100644 index 0000000..181c988 --- /dev/null +++ b/Pods/Alamofire/Source/Timeline.swift @@ -0,0 +1,136 @@ +// +// Timeline.swift +// +// Copyright (c) 2014-2018 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: TimeInterval + + /// The time interval in seconds from the time the request started to the time the request completed. + public let requestDuration: TimeInterval + + /// The time interval in seconds from the time the request completed to the time response serialization completed. + public let serializationDuration: TimeInterval + + /// The time interval in seconds from the time the request started to the time response serialization completed. + public let totalDuration: TimeInterval + + /// Creates a new `Timeline` instance with the specified request times. + /// + /// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. + /// - parameter initialResponseTime: The time the first bytes were received from or sent to the server. + /// Defaults to `0.0`. + /// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. + /// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults + /// to `0.0`. + /// + /// - returns: The new `Timeline` instance. + public init( + requestStartTime: CFAbsoluteTime = 0.0, + initialResponseTime: CFAbsoluteTime = 0.0, + requestCompletedTime: CFAbsoluteTime = 0.0, + serializationCompletedTime: CFAbsoluteTime = 0.0) + { + self.requestStartTime = requestStartTime + self.initialResponseTime = initialResponseTime + self.requestCompletedTime = requestCompletedTime + self.serializationCompletedTime = serializationCompletedTime + + self.latency = initialResponseTime - requestStartTime + self.requestDuration = requestCompletedTime - requestStartTime + self.serializationDuration = serializationCompletedTime - requestCompletedTime + self.totalDuration = serializationCompletedTime - requestStartTime + } +} + +// MARK: - CustomStringConvertible + +extension Timeline: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes the latency, the request + /// duration and the total duration. + public var description: String { + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joined(separator: ", ") + " }" + } +} + +// MARK: - CustomDebugStringConvertible + +extension Timeline: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes the request start time, the + /// initial response time, the request completed time, the serialization completed time, the latency, the request + /// duration and the total duration. + public var debugDescription: String { + let requestStartTime = String(format: "%.3f", self.requestStartTime) + let initialResponseTime = String(format: "%.3f", self.initialResponseTime) + let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) + let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Request Start Time\": " + requestStartTime, + "\"Initial Response Time\": " + initialResponseTime, + "\"Request Completed Time\": " + requestCompletedTime, + "\"Serialization Completed Time\": " + serializationCompletedTime, + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joined(separator: ", ") + " }" + } +} diff --git a/Pods/Alamofire/Source/Validation.swift b/Pods/Alamofire/Source/Validation.swift new file mode 100644 index 0000000..ec2c5c3 --- /dev/null +++ b/Pods/Alamofire/Source/Validation.swift @@ -0,0 +1,315 @@ +// +// Validation.swift +// +// Copyright (c) 2014-2018 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 { + + // MARK: Helper Types + + fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason + + /// 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(Error) + } + + fileprivate struct MIMEType { + let type: String + let subtype: String + + var isWildcard: Bool { return type == "*" && subtype == "*" } + + init?(_ string: String) { + let components: [String] = { + let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) + + #if swift(>=3.2) + let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)] + #else + let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex) + #endif + + return split.components(separatedBy: "/") + }() + + if let type = components.first, let 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 + } + } + } + + // MARK: Properties + + fileprivate var acceptableStatusCodes: [Int] { return Array(200..<300) } + + fileprivate var acceptableContentTypes: [String] { + if let accept = request?.value(forHTTPHeaderField: "Accept") { + return accept.components(separatedBy: ",") + } + + return ["*/*"] + } + + // MARK: Status Code + + fileprivate func validate( + statusCode acceptableStatusCodes: S, + response: HTTPURLResponse) + -> ValidationResult + where S.Iterator.Element == Int + { + if acceptableStatusCodes.contains(response.statusCode) { + return .success + } else { + let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) + return .failure(AFError.responseValidationFailed(reason: reason)) + } + } + + // MARK: Content Type + + fileprivate func validate( + contentType acceptableContentTypes: S, + response: HTTPURLResponse, + data: Data?) + -> ValidationResult + where S.Iterator.Element == String + { + guard let data = data, data.count > 0 else { return .success } + + guard + let responseContentType = response.mimeType, + let responseMIMEType = MIMEType(responseContentType) + else { + for contentType in acceptableContentTypes { + if let mimeType = MIMEType(contentType), mimeType.isWildcard { + return .success + } + } + + let error: AFError = { + let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } + + for contentType in acceptableContentTypes { + if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { + return .success + } + } + + let error: AFError = { + let reason: ErrorReason = .unacceptableContentType( + acceptableContentTypes: Array(acceptableContentTypes), + responseContentType: responseContentType + ) + + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } +} + +// MARK: - + +extension DataRequest { + /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the + /// request was valid. + public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> 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. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validationExecution: () -> Void = { [unowned self] in + if + let response = self.response, + self.delegate.error == nil, + case let .failure(error) = validation(self.request, response, self.delegate.data) + { + self.delegate.error = error + } + } + + validations.append(validationExecution) + + return self + } + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - returns: The request. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + return validate { [unowned self] _, response, _ in + return self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// 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. + @discardableResult + public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, data in + return self.validate(contentType: acceptableContentTypes, response: response, data: data) + } + } + + /// 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. + @discardableResult + public func validate() -> Self { + return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + } +} + +// MARK: - + +extension DownloadRequest { + /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a + /// destination URL, and returns whether the request was valid. + public typealias Validation = ( + _ request: URLRequest?, + _ response: HTTPURLResponse, + _ temporaryURL: URL?, + _ destinationURL: URL?) + -> 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. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validationExecution: () -> Void = { [unowned self] in + let request = self.request + let temporaryURL = self.downloadDelegate.temporaryURL + let destinationURL = self.downloadDelegate.destinationURL + + if + let response = self.response, + self.delegate.error == nil, + case let .failure(error) = validation(request, response, temporaryURL, destinationURL) + { + self.delegate.error = error + } + } + + validations.append(validationExecution) + + return self + } + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - returns: The request. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + return validate { [unowned self] _, response, _, _ in + return self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// 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. + @discardableResult + public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, _, _ in + let fileURL = self.downloadDelegate.fileURL + + guard let validFileURL = fileURL else { + return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) + } + + do { + let data = try Data(contentsOf: validFileURL) + return self.validate(contentType: acceptableContentTypes, response: response, data: data) + } catch { + return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) + } + } + } + + /// 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. + @discardableResult + public func validate() -> Self { + return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + } +} diff --git a/Pods/Manifest.lock b/Pods/Manifest.lock index 16acd90..dcf7cec 100644 --- a/Pods/Manifest.lock +++ b/Pods/Manifest.lock @@ -1,18 +1,22 @@ PODS: + - Alamofire (4.7.3) - EVReflection (5.6.2): - EVReflection/Core (= 5.6.2) - EVReflection/Core (5.6.2) DEPENDENCIES: + - Alamofire (~> 4.7) - EVReflection SPEC REPOS: https://github.com/cocoapods/specs.git: + - Alamofire - EVReflection SPEC CHECKSUMS: + Alamofire: c7287b6e5d7da964a70935e5db17046b7fde6568 EVReflection: 640322f8a3aaf78cbc3c23892476b6adb636ebf0 -PODFILE CHECKSUM: 37c990d763bcdd56cefd04cd5de41c1753bf9fd2 +PODFILE CHECKSUM: 2957bc01138d95002ce3ca76aa00047ba9e7f4ac COCOAPODS: 1.5.2 diff --git a/Pods/Pods.xcodeproj/project.pbxproj b/Pods/Pods.xcodeproj/project.pbxproj index fd2d7c5..47cb17f 100644 --- a/Pods/Pods.xcodeproj/project.pbxproj +++ b/Pods/Pods.xcodeproj/project.pbxproj @@ -7,28 +7,48 @@ objects = { /* Begin PBXBuildFile section */ - 106F53E394D3ABC4099DE1A69DD605B1 /* EVObject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25F397D55CD049AD0C1057047F274F41 /* EVObject.swift */; }; - 11A2606802F2CD8556892D95CCB730AB /* PrintOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 040D4F9EC5EE0A83E5B0792DC2464CA6 /* PrintOptions.swift */; }; - 2B4DBF73B18FBDF203ADBBFF1FEA4543 /* EVCustomReflectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 362437F5A32E040AA07FAA8D70B37C93 /* EVCustomReflectable.swift */; }; - 39C7B7DB3B10CEF04173A3A90A1EB8DD /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5A16F4CFC63FAC439D7A04994F579A03 /* Foundation.framework */; }; + 106F53E394D3ABC4099DE1A69DD605B1 /* EVObject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87D9952AFE07B4E9F3D42D7FB41E8CAE /* EVObject.swift */; }; + 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = D31B7CCA15AA686CB755B3BEB4CCC4F2 /* Timeline.swift */; }; + 11A2606802F2CD8556892D95CCB730AB /* PrintOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB4842859605A20A0D3DCD70B63E5326 /* PrintOptions.swift */; }; + 1A9C61AAD6B4E7C666D0D815AE3BDE22 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5A16F4CFC63FAC439D7A04994F579A03 /* Foundation.framework */; }; + 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 0FE0A094DD430E6D7E581F66F9E5E4E1 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 226FA026D93E7F8FC585FC6063181AD3 /* Pods-ProjectX-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 456584BEEF505836D62F0D8D6079D1C1 /* Pods-ProjectX-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2B4DBF73B18FBDF203ADBBFF1FEA4543 /* EVCustomReflectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = CF9A2B2D3BD3E17D2866B00730C12E5B /* EVCustomReflectable.swift */; }; + 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4D36953E28E733ADC9430DD42B1AAB67 /* TaskDelegate.swift */; }; 3EE267E487945EE42F4FC893B92E37AC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5A16F4CFC63FAC439D7A04994F579A03 /* Foundation.framework */; }; - 4149B139A944EED0B567BAB79DC11B11 /* EVReflection-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F5BC3277893161864ABA7EE6BA160AA /* EVReflection-dummy.m */; }; - 46B8F4E1B21BED078515D240556F539F /* Pods-ProjectX-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 23AB0DCD45A05D2B56DE773D2FB218F0 /* Pods-ProjectX-dummy.m */; }; - 56AC36A1233DFE8B92E3ACDEB2865CFA /* EVReflectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = D08C807F1AF55611B3525C7D6894A948 /* EVReflectable.swift */; }; - 609B212E172C917DE6BC45AD18C6F50F /* Pods-ProjectX-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 456584BEEF505836D62F0D8D6079D1C1 /* Pods-ProjectX-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4149B139A944EED0B567BAB79DC11B11 /* EVReflection-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = D3A8442EBD60B094ED734F9FBA9BF206 /* EVReflection-dummy.m */; }; + 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89D943A25196E9D7FADBEA76D41E996D /* Request.swift */; }; + 56AC36A1233DFE8B92E3ACDEB2865CFA /* EVReflectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1FE06C3722CB431DA5B7AACED623C775 /* EVReflectable.swift */; }; + 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 91C7228805FFB0B2BF80ADF671D40ACC /* DispatchQueue+Alamofire.swift */; }; + 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16B2D7EE8C9A7F6EB81C231F36D776D9 /* ServerTrustPolicy.swift */; }; + 698BBBFB3185479E0F43E43146AD95AD /* Pods-ProjectX-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 23AB0DCD45A05D2B56DE773D2FB218F0 /* Pods-ProjectX-dummy.m */; }; 6A3EAA190229B501133298572493C3DA /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5A16F4CFC63FAC439D7A04994F579A03 /* Foundation.framework */; }; + 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 786892933E9577D5BB5FD25419EC0356 /* SessionDelegate.swift */; }; + 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 39388A98A520E7B6C70EFEA1FB478E24 /* Result.swift */; }; 8288207F41ADB3D2C021C7213C94504D /* Pods-ProjectXUITests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F56FD24E7B6B9B9E6DDCB943AB106B13 /* Pods-ProjectXUITests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 8F6B9442BBF9A217EC880C8E4F5E91FA /* EVReflection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F93EBA41699B4D27F5D40C2B378B471 /* EVReflection.swift */; }; - B16BCD41FEB0C413C29D022509B7F5C1 /* ConversionOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F80D6DF9FED45651595974E33369C47 /* ConversionOptions.swift */; }; + 834F4D9819C6010E611A7E151B8899C3 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5A16F4CFC63FAC439D7A04994F579A03 /* Foundation.framework */; }; + 8F6B9442BBF9A217EC880C8E4F5E91FA /* EVReflection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F8ABE89AFB38CC8C5D4C20C733637D0 /* EVReflection.swift */; }; + 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90985C7D00EB2781B9D7C10F9454DD65 /* AFError.swift */; }; + A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58EE7E05F8843C96D608E0834C0402D6 /* NetworkReachabilityManager.swift */; }; + A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 7838B0F3B42DD125B9DC3A7FBB914649 /* Alamofire-dummy.m */; }; + AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = B323BF9BFD620EDBD1E226D030FEF743 /* SessionManager.swift */; }; + B16BCD41FEB0C413C29D022509B7F5C1 /* ConversionOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = CFA995F7B67DF9DDF7433A616851D1E7 /* ConversionOptions.swift */; }; B4E269A07271CD388F59A18EC4EBA4E5 /* Pods-ProjectXUITests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F2C10805549FD99D7CB5349496E41D33 /* Pods-ProjectXUITests-dummy.m */; }; - C68645588E5D3AF68DFB86F3DB3518D1 /* DeserializationStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD9E34AAFD2F397F5CA5A31C2A99C477 /* DeserializationStatus.swift */; }; - E0D50D8790C8FF18ADF380EE9FCB74EE /* EVReflection-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 60608AFF6D1377B72B9EE8839ECF6219 /* EVReflection-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - E0EB6A6E80003A0375782FEB80CE214E /* EVWorkaroundHelpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 773AB32C3E8834F0A37D800AA7CCB8B1 /* EVWorkaroundHelpers.swift */; }; + B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FC586154B9EE9C95D7DACA5AC2BDDA0 /* MultipartFormData.swift */; }; + BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 91E8C8BB25B6049ED0E24B7BD8A72833 /* Validation.swift */; }; + BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7A3FCC387D1BB397D5D908B8FDBB32E /* ParameterEncoding.swift */; }; + C68645588E5D3AF68DFB86F3DB3518D1 /* DeserializationStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA09D21BD88D27191EB7FEB74DEF2A6F /* DeserializationStatus.swift */; }; + CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E32A555B668C08C9B0FDA759BBBE75E /* Response.swift */; }; + E0D50D8790C8FF18ADF380EE9FCB74EE /* EVReflection-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3C04272C831DD5AEF394F7E4982361F1 /* EVReflection-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E0EB6A6E80003A0375782FEB80CE214E /* EVWorkaroundHelpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = D42DCF6741917DCCD58018EB68642680 /* EVWorkaroundHelpers.swift */; }; E35A36FFEE7685B7B343E05A33654F29 /* Pods-ProjectXTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 31045782C4C78F6AC34EC4FA0704B70E /* Pods-ProjectXTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - EEFBED65C004846B53DE5C177818FA2D /* EVArrayExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 299FD3F61E6B452738CEB4805AD93880 /* EVArrayExtension.swift */; }; + EEFBED65C004846B53DE5C177818FA2D /* EVArrayExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4F83337BF9A0B47A9F3D3C8E4A3C34E /* EVArrayExtension.swift */; }; + EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1936A02288153121851CCFD65AF6DB49 /* Notifications.swift */; }; F1936E60EF226756434024D3F3224C48 /* Pods-ProjectXTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 27E5306AEAE10B2427DF688B80FA7E15 /* Pods-ProjectXTests-dummy.m */; }; - F6D09350B5F2C52A3448B2C10AB7D316 /* EVDictionaryExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10268EF3DA5E9A3D12A71EE2DC188FFD /* EVDictionaryExtension.swift */; }; + F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E41B3F448C672B94770C3E5D335F0F3 /* ResponseSerialization.swift */; }; + F6D09350B5F2C52A3448B2C10AB7D316 /* EVDictionaryExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 716AF443A9B8873087461733477C19AF /* EVDictionaryExtension.swift */; }; F6D93BA618F407031E2F5478ACE2457C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5A16F4CFC63FAC439D7A04994F579A03 /* Foundation.framework */; }; + F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = C64B17CD8558BB38EEF54A0A1CA52F0F /* Alamofire.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -36,17 +56,24 @@ isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 768F964FE6D39D87DEDD9546C2AAB36B; + remoteGlobalIDString = FEEFCCE4BDE6B310D7D9580655442504; remoteInfo = "Pods-ProjectX"; }; + 7FE4583BDA073E1C008082710298ED0B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; + remoteInfo = Alamofire; + }; 9B9945FEE36193EF2B13A4E181CCD20B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 768F964FE6D39D87DEDD9546C2AAB36B; + remoteGlobalIDString = FEEFCCE4BDE6B310D7D9580655442504; remoteInfo = "Pods-ProjectX"; }; - FA922E8AE223D814E1916D80C3B03A3A /* PBXContainerItemProxy */ = { + A2C70781B2C669F4EF1202CD4896A6CB /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; @@ -56,82 +83,106 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 040D4F9EC5EE0A83E5B0792DC2464CA6 /* PrintOptions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PrintOptions.swift; path = Source/PrintOptions.swift; sourceTree = ""; }; + 07962C021D7DC740148106B461AC0419 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + 0887948D7E0906E9DAAD757041CD4C3D /* EVReflection-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "EVReflection-prefix.pch"; sourceTree = ""; }; 0A7519B851AFCD7521A01CE8121793A4 /* Pods-ProjectXUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ProjectXUITests.debug.xcconfig"; sourceTree = ""; }; 0B9B81CF083BBFE02712ABE90A4229E5 /* Pods-ProjectXTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-ProjectXTests.modulemap"; sourceTree = ""; }; - 10268EF3DA5E9A3D12A71EE2DC188FFD /* EVDictionaryExtension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVDictionaryExtension.swift; path = Source/EVDictionaryExtension.swift; sourceTree = ""; }; - 1F93EBA41699B4D27F5D40C2B378B471 /* EVReflection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVReflection.swift; path = Source/EVReflection.swift; sourceTree = ""; }; + 0C0B1B43BC0B691F634814C5950D6D53 /* EVReflection.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = EVReflection.xcconfig; sourceTree = ""; }; + 0FE0A094DD430E6D7E581F66F9E5E4E1 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + 157ACE4A08CC6F08E17163855D06659C /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire.framework; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 16B2D7EE8C9A7F6EB81C231F36D776D9 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + 1936A02288153121851CCFD65AF6DB49 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + 1F8ABE89AFB38CC8C5D4C20C733637D0 /* EVReflection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVReflection.swift; path = Source/EVReflection.swift; sourceTree = ""; }; + 1FE06C3722CB431DA5B7AACED623C775 /* EVReflectable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVReflectable.swift; path = Source/EVReflectable.swift; sourceTree = ""; }; 23AB0DCD45A05D2B56DE773D2FB218F0 /* Pods-ProjectX-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-ProjectX-dummy.m"; sourceTree = ""; }; - 25F397D55CD049AD0C1057047F274F41 /* EVObject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVObject.swift; path = Source/EVObject.swift; sourceTree = ""; }; + 24AC4A0182080FA5C1FF2C2646E92184 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; 27E5306AEAE10B2427DF688B80FA7E15 /* Pods-ProjectXTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-ProjectXTests-dummy.m"; sourceTree = ""; }; - 299FD3F61E6B452738CEB4805AD93880 /* EVArrayExtension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVArrayExtension.swift; path = Source/EVArrayExtension.swift; sourceTree = ""; }; 2D3E61C4EFFADA9D6AFD35546658C3F8 /* Pods-ProjectX-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-ProjectX-acknowledgements.plist"; sourceTree = ""; }; 305A9F31B46411DAB1B031159F218E01 /* Pods-ProjectX.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ProjectX.debug.xcconfig"; sourceTree = ""; }; 31045782C4C78F6AC34EC4FA0704B70E /* Pods-ProjectXTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-ProjectXTests-umbrella.h"; sourceTree = ""; }; - 335E57D30C9727F19AB7A32FB7D62E37 /* EVReflection.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = EVReflection.modulemap; sourceTree = ""; }; - 362437F5A32E040AA07FAA8D70B37C93 /* EVCustomReflectable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVCustomReflectable.swift; path = Source/EVCustomReflectable.swift; sourceTree = ""; }; + 39388A98A520E7B6C70EFEA1FB478E24 /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + 3C04272C831DD5AEF394F7E4982361F1 /* EVReflection-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "EVReflection-umbrella.h"; sourceTree = ""; }; 3DF6AE867C5A575732F56559B5386169 /* Pods-ProjectX-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-ProjectX-acknowledgements.markdown"; sourceTree = ""; }; 3ED23512DEB1500FD7B88590D2F5C755 /* Pods-ProjectX-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ProjectX-resources.sh"; sourceTree = ""; }; 420A658C87B5C16A7246B50997B0B3BD /* Pods-ProjectX.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-ProjectX.modulemap"; sourceTree = ""; }; 43E12FCAA7246A653DD5464184D0C293 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 456584BEEF505836D62F0D8D6079D1C1 /* Pods-ProjectX-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-ProjectX-umbrella.h"; sourceTree = ""; }; + 4904A902F4B68B72C3AA30834763C994 /* Pods_ProjectXUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_ProjectXUITests.framework; path = "Pods-ProjectXUITests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; 497677A62BD9A6C58E7B4C660B781C01 /* Pods-ProjectXTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ProjectXTests.debug.xcconfig"; sourceTree = ""; }; - 4F5BC3277893161864ABA7EE6BA160AA /* EVReflection-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "EVReflection-dummy.m"; sourceTree = ""; }; - 4F80D6DF9FED45651595974E33369C47 /* ConversionOptions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConversionOptions.swift; path = Source/ConversionOptions.swift; sourceTree = ""; }; + 4D36953E28E733ADC9430DD42B1AAB67 /* TaskDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TaskDelegate.swift; path = Source/TaskDelegate.swift; sourceTree = ""; }; + 58EE7E05F8843C96D608E0834C0402D6 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; 5A16F4CFC63FAC439D7A04994F579A03 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS11.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; 5D1E7732F3AF0C4E8E74A8FA2EBFBFAE /* Pods-ProjectXUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ProjectXUITests.release.xcconfig"; sourceTree = ""; }; - 60608AFF6D1377B72B9EE8839ECF6219 /* EVReflection-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "EVReflection-umbrella.h"; sourceTree = ""; }; - 648BD518C079FF03326404E352BAE5DE /* EVReflection-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "EVReflection-prefix.pch"; sourceTree = ""; }; + 634B4EBB683228097C9F925C048EDE56 /* Pods_ProjectXTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_ProjectXTests.framework; path = "Pods-ProjectXTests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; 6582ECDA324E305E3C024639FB5F564D /* Pods-ProjectXTests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ProjectXTests-resources.sh"; sourceTree = ""; }; - 6C690E2A9F1189BF962293860A419B0E /* Pods_ProjectXTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_ProjectXTests.framework; path = "Pods-ProjectXTests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; - 6DED991DC9DDB3966A93BEB6DF15C315 /* Pods_ProjectXUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_ProjectXUITests.framework; path = "Pods-ProjectXUITests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; - 6FA8A74480C0CBE7684F3C66CA463B01 /* Pods_ProjectX.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_ProjectX.framework; path = "Pods-ProjectX.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + 6E41B3F448C672B94770C3E5D335F0F3 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + 716AF443A9B8873087461733477C19AF /* EVDictionaryExtension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVDictionaryExtension.swift; path = Source/EVDictionaryExtension.swift; sourceTree = ""; }; 719568D778ECBEAC0743C12D4B4D0FB8 /* Pods-ProjectXUITests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ProjectXUITests-resources.sh"; sourceTree = ""; }; + 7200DBA258F9700EBF34D80990C03641 /* EVReflection.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = EVReflection.modulemap; sourceTree = ""; }; 7465B6D6DC6B76C1BC646E475B90886E /* Pods-ProjectXTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-ProjectXTests-acknowledgements.markdown"; sourceTree = ""; }; - 773AB32C3E8834F0A37D800AA7CCB8B1 /* EVWorkaroundHelpers.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVWorkaroundHelpers.swift; path = Source/EVWorkaroundHelpers.swift; sourceTree = ""; }; + 7838B0F3B42DD125B9DC3A7FBB914649 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + 786892933E9577D5BB5FD25419EC0356 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; 7E0BA159F9BBE27A724C9A25571CDEE7 /* Pods-ProjectXUITests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-ProjectXUITests-acknowledgements.plist"; sourceTree = ""; }; + 7E32A555B668C08C9B0FDA759BBBE75E /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; 84402BE490A57FF70CF669DFCFFD1C30 /* Pods-ProjectXTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-ProjectXTests-acknowledgements.plist"; sourceTree = ""; }; 855574B8A989C812505B042C43B00E82 /* Pods-ProjectX.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ProjectX.release.xcconfig"; sourceTree = ""; }; - 8B768B344769B3ED48B03F731575232D /* EVReflection.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = EVReflection.xcconfig; sourceTree = ""; }; + 85B02DA6190FBD3121D47CD0E4DDAD39 /* Pods_ProjectX.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_ProjectX.framework; path = "Pods-ProjectX.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + 87D9952AFE07B4E9F3D42D7FB41E8CAE /* EVObject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVObject.swift; path = Source/EVObject.swift; sourceTree = ""; }; + 89D943A25196E9D7FADBEA76D41E996D /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; 8BC616271F9C0A95561935E0B77D0FEF /* Pods-ProjectXTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ProjectXTests.release.xcconfig"; sourceTree = ""; }; 8BE4C8769E2C82924CF5ECDD07415C2C /* Pods-ProjectXUITests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-ProjectXUITests-acknowledgements.markdown"; sourceTree = ""; }; + 8FC586154B9EE9C95D7DACA5AC2BDDA0 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + 90985C7D00EB2781B9D7C10F9454DD65 /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; + 91C7228805FFB0B2BF80ADF671D40ACC /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; + 91E8C8BB25B6049ED0E24B7BD8A72833 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 95B8524EE0B9DD8D39357EB2B7FC820B /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 96ACCA3094945DF5BBE2D8D224485424 /* Pods-ProjectXUITests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-ProjectXUITests.modulemap"; sourceTree = ""; }; 9E916D5A43140393068ABE4FB3805993 /* Pods-ProjectX-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ProjectX-frameworks.sh"; sourceTree = ""; }; + A7A3FCC387D1BB397D5D908B8FDBB32E /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; AE00356EB2CE5E448251991823BCE830 /* Pods-ProjectXTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ProjectXTests-frameworks.sh"; sourceTree = ""; }; + B323BF9BFD620EDBD1E226D030FEF743 /* SessionManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionManager.swift; path = Source/SessionManager.swift; sourceTree = ""; }; B44D80BE69259915A76261B2B85A0351 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; C60241298B0E74F49459E0856751B985 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - D08C807F1AF55611B3525C7D6894A948 /* EVReflectable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVReflectable.swift; path = Source/EVReflectable.swift; sourceTree = ""; }; - DD9E34AAFD2F397F5CA5A31C2A99C477 /* DeserializationStatus.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DeserializationStatus.swift; path = Source/DeserializationStatus.swift; sourceTree = ""; }; - E3586B7C51148D9443F976B1695E5E5A /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - E949E031ED776DA8BAB844E8D88D5B95 /* EVReflection.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = EVReflection.framework; path = EVReflection.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + C64B17CD8558BB38EEF54A0A1CA52F0F /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + CF9A2B2D3BD3E17D2866B00730C12E5B /* EVCustomReflectable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVCustomReflectable.swift; path = Source/EVCustomReflectable.swift; sourceTree = ""; }; + CFA995F7B67DF9DDF7433A616851D1E7 /* ConversionOptions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConversionOptions.swift; path = Source/ConversionOptions.swift; sourceTree = ""; }; + D31B7CCA15AA686CB755B3BEB4CCC4F2 /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; + D3A8442EBD60B094ED734F9FBA9BF206 /* EVReflection-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "EVReflection-dummy.m"; sourceTree = ""; }; + D42DCF6741917DCCD58018EB68642680 /* EVWorkaroundHelpers.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVWorkaroundHelpers.swift; path = Source/EVWorkaroundHelpers.swift; sourceTree = ""; }; + D4F83337BF9A0B47A9F3D3C8E4A3C34E /* EVArrayExtension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EVArrayExtension.swift; path = Source/EVArrayExtension.swift; sourceTree = ""; }; + EB4842859605A20A0D3DCD70B63E5326 /* PrintOptions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PrintOptions.swift; path = Source/PrintOptions.swift; sourceTree = ""; }; EB52B1C1E3B9C8FE28F8E4149F406EFF /* Pods-ProjectXUITests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ProjectXUITests-frameworks.sh"; sourceTree = ""; }; + EC0E37150EFE8744FA8694F3B9639AC1 /* EVReflection.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = EVReflection.framework; path = EVReflection.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + F026B38923B00F0B25B507FAF7755003 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; F2C10805549FD99D7CB5349496E41D33 /* Pods-ProjectXUITests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-ProjectXUITests-dummy.m"; sourceTree = ""; }; F56FD24E7B6B9B9E6DDCB943AB106B13 /* Pods-ProjectXUITests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-ProjectXUITests-umbrella.h"; sourceTree = ""; }; + FA09D21BD88D27191EB7FEB74DEF2A6F /* DeserializationStatus.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DeserializationStatus.swift; path = Source/DeserializationStatus.swift; sourceTree = ""; }; + FB826EC0A8CB94A9F42A6B9635E16690 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Alamofire.modulemap; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ - 3B0CD109FD613DD1279B794DC00F9BA2 /* Frameworks */ = { + 3DF234E730676FAA51C9BE2A2DBE9291 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 39C7B7DB3B10CEF04173A3A90A1EB8DD /* Foundation.framework in Frameworks */, + 6A3EAA190229B501133298572493C3DA /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; - 3DF234E730676FAA51C9BE2A2DBE9291 /* Frameworks */ = { + 566E1423DE21CB8B9DC0ED01F349A68F /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 6A3EAA190229B501133298572493C3DA /* Foundation.framework in Frameworks */, + 3EE267E487945EE42F4FC893B92E37AC /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; - 566E1423DE21CB8B9DC0ED01F349A68F /* Frameworks */ = { + 99195E4207764744AEC07ECCBCD550EB /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 3EE267E487945EE42F4FC893B92E37AC /* Foundation.framework in Frameworks */, + 834F4D9819C6010E611A7E151B8899C3 /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -143,24 +194,38 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + B6224973D5EBEA224F18B39D4DF37E2E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 1A9C61AAD6B4E7C666D0D815AE3BDE22 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 3D2775AE14F466B11982004A4A13C3BC /* Core */ = { + 1E452B2E449D4AAD10A2A21C6B1357EF /* Pods */ = { isa = PBXGroup; children = ( - 4F80D6DF9FED45651595974E33369C47 /* ConversionOptions.swift */, - DD9E34AAFD2F397F5CA5A31C2A99C477 /* DeserializationStatus.swift */, - 299FD3F61E6B452738CEB4805AD93880 /* EVArrayExtension.swift */, - 362437F5A32E040AA07FAA8D70B37C93 /* EVCustomReflectable.swift */, - 10268EF3DA5E9A3D12A71EE2DC188FFD /* EVDictionaryExtension.swift */, - 25F397D55CD049AD0C1057047F274F41 /* EVObject.swift */, - D08C807F1AF55611B3525C7D6894A948 /* EVReflectable.swift */, - 1F93EBA41699B4D27F5D40C2B378B471 /* EVReflection.swift */, - 773AB32C3E8834F0A37D800AA7CCB8B1 /* EVWorkaroundHelpers.swift */, - 040D4F9EC5EE0A83E5B0792DC2464CA6 /* PrintOptions.swift */, + D45BDD867BC6ACB27C46D69C5B0DAAA3 /* Alamofire */, + ECDDF771C01C7C0B930C3333E29E5F48 /* EVReflection */, ); - name = Core; + name = Pods; + sourceTree = ""; + }; + 39BCD84CAE6A4070B7D31D70ACD279D4 /* Support Files */ = { + isa = PBXGroup; + children = ( + 7200DBA258F9700EBF34D80990C03641 /* EVReflection.modulemap */, + 0C0B1B43BC0B691F634814C5950D6D53 /* EVReflection.xcconfig */, + D3A8442EBD60B094ED734F9FBA9BF206 /* EVReflection-dummy.m */, + 0887948D7E0906E9DAAD757041CD4C3D /* EVReflection-prefix.pch */, + 3C04272C831DD5AEF394F7E4982361F1 /* EVReflection-umbrella.h */, + 95B8524EE0B9DD8D39357EB2B7FC820B /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/EVReflection"; sourceTree = ""; }; 5E0D919E635D23B70123790B8308F8EF /* iOS */ = { @@ -171,6 +236,23 @@ name = iOS; sourceTree = ""; }; + 5F388EAEC8DB889FD267869D95DF16DC /* Core */ = { + isa = PBXGroup; + children = ( + CFA995F7B67DF9DDF7433A616851D1E7 /* ConversionOptions.swift */, + FA09D21BD88D27191EB7FEB74DEF2A6F /* DeserializationStatus.swift */, + D4F83337BF9A0B47A9F3D3C8E4A3C34E /* EVArrayExtension.swift */, + CF9A2B2D3BD3E17D2866B00730C12E5B /* EVCustomReflectable.swift */, + 716AF443A9B8873087461733477C19AF /* EVDictionaryExtension.swift */, + 87D9952AFE07B4E9F3D42D7FB41E8CAE /* EVObject.swift */, + 1FE06C3722CB431DA5B7AACED623C775 /* EVReflectable.swift */, + 1F8ABE89AFB38CC8C5D4C20C733637D0 /* EVReflection.swift */, + D42DCF6741917DCCD58018EB68642680 /* EVWorkaroundHelpers.swift */, + EB4842859605A20A0D3DCD70B63E5326 /* PrintOptions.swift */, + ); + name = Core; + sourceTree = ""; + }; 774320EDA837D015D6BE4201FA23655B /* Pods-ProjectXUITests */ = { isa = PBXGroup; children = ( @@ -189,38 +271,17 @@ path = "Target Support Files/Pods-ProjectXUITests"; sourceTree = ""; }; - 78849575C95BAEEF4B546717CADDD8D8 /* Products */ = { - isa = PBXGroup; - children = ( - E949E031ED776DA8BAB844E8D88D5B95 /* EVReflection.framework */, - 6FA8A74480C0CBE7684F3C66CA463B01 /* Pods_ProjectX.framework */, - 6C690E2A9F1189BF962293860A419B0E /* Pods_ProjectXTests.framework */, - 6DED991DC9DDB3966A93BEB6DF15C315 /* Pods_ProjectXUITests.framework */, - ); - name = Products; - sourceTree = ""; - }; 7DB346D0F39D3F0E887471402A8071AB = { isa = PBXGroup; children = ( 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, BC3CA7F9E30CC8F7E2DD044DD34432FC /* Frameworks */, - CF251A3E683FF9995A4523384DCA9040 /* Pods */, - 78849575C95BAEEF4B546717CADDD8D8 /* Products */, + 1E452B2E449D4AAD10A2A21C6B1357EF /* Pods */, + BCAC7F36C287DF32CC3151E86BC6ACE3 /* Products */, CF1C85C5C43BD8393C1913E22079FC3C /* Targets Support Files */, ); sourceTree = ""; }; - 88F46CBD5427C433CE22D81DF6D7F14F /* EVReflection */ = { - isa = PBXGroup; - children = ( - 3D2775AE14F466B11982004A4A13C3BC /* Core */, - D7B1A7C328EF10A3D656B76A99AFD2B2 /* Support Files */, - ); - name = EVReflection; - path = EVReflection; - sourceTree = ""; - }; A9D9DEE7D6513E287223CC0F151611E1 /* Pods-ProjectX */ = { isa = PBXGroup; children = ( @@ -265,6 +326,18 @@ path = "Target Support Files/Pods-ProjectXTests"; sourceTree = ""; }; + BCAC7F36C287DF32CC3151E86BC6ACE3 /* Products */ = { + isa = PBXGroup; + children = ( + 157ACE4A08CC6F08E17163855D06659C /* Alamofire.framework */, + EC0E37150EFE8744FA8694F3B9639AC1 /* EVReflection.framework */, + 85B02DA6190FBD3121D47CD0E4DDAD39 /* Pods_ProjectX.framework */, + 634B4EBB683228097C9F925C048EDE56 /* Pods_ProjectXTests.framework */, + 4904A902F4B68B72C3AA30834763C994 /* Pods_ProjectXUITests.framework */, + ); + name = Products; + sourceTree = ""; + }; CF1C85C5C43BD8393C1913E22079FC3C /* Targets Support Files */ = { isa = PBXGroup; children = ( @@ -275,31 +348,67 @@ name = "Targets Support Files"; sourceTree = ""; }; - CF251A3E683FF9995A4523384DCA9040 /* Pods */ = { + D0AC307BA480DC306EDE67D4DE3C3D06 /* Support Files */ = { isa = PBXGroup; children = ( - 88F46CBD5427C433CE22D81DF6D7F14F /* EVReflection */, + FB826EC0A8CB94A9F42A6B9635E16690 /* Alamofire.modulemap */, + 24AC4A0182080FA5C1FF2C2646E92184 /* Alamofire.xcconfig */, + 7838B0F3B42DD125B9DC3A7FBB914649 /* Alamofire-dummy.m */, + 07962C021D7DC740148106B461AC0419 /* Alamofire-prefix.pch */, + 0FE0A094DD430E6D7E581F66F9E5E4E1 /* Alamofire-umbrella.h */, + F026B38923B00F0B25B507FAF7755003 /* Info.plist */, ); - name = Pods; + name = "Support Files"; + path = "../Target Support Files/Alamofire"; sourceTree = ""; }; - D7B1A7C328EF10A3D656B76A99AFD2B2 /* Support Files */ = { + D45BDD867BC6ACB27C46D69C5B0DAAA3 /* Alamofire */ = { isa = PBXGroup; children = ( - 335E57D30C9727F19AB7A32FB7D62E37 /* EVReflection.modulemap */, - 8B768B344769B3ED48B03F731575232D /* EVReflection.xcconfig */, - 4F5BC3277893161864ABA7EE6BA160AA /* EVReflection-dummy.m */, - 648BD518C079FF03326404E352BAE5DE /* EVReflection-prefix.pch */, - 60608AFF6D1377B72B9EE8839ECF6219 /* EVReflection-umbrella.h */, - E3586B7C51148D9443F976B1695E5E5A /* Info.plist */, + 90985C7D00EB2781B9D7C10F9454DD65 /* AFError.swift */, + C64B17CD8558BB38EEF54A0A1CA52F0F /* Alamofire.swift */, + 91C7228805FFB0B2BF80ADF671D40ACC /* DispatchQueue+Alamofire.swift */, + 8FC586154B9EE9C95D7DACA5AC2BDDA0 /* MultipartFormData.swift */, + 58EE7E05F8843C96D608E0834C0402D6 /* NetworkReachabilityManager.swift */, + 1936A02288153121851CCFD65AF6DB49 /* Notifications.swift */, + A7A3FCC387D1BB397D5D908B8FDBB32E /* ParameterEncoding.swift */, + 89D943A25196E9D7FADBEA76D41E996D /* Request.swift */, + 7E32A555B668C08C9B0FDA759BBBE75E /* Response.swift */, + 6E41B3F448C672B94770C3E5D335F0F3 /* ResponseSerialization.swift */, + 39388A98A520E7B6C70EFEA1FB478E24 /* Result.swift */, + 16B2D7EE8C9A7F6EB81C231F36D776D9 /* ServerTrustPolicy.swift */, + 786892933E9577D5BB5FD25419EC0356 /* SessionDelegate.swift */, + B323BF9BFD620EDBD1E226D030FEF743 /* SessionManager.swift */, + 4D36953E28E733ADC9430DD42B1AAB67 /* TaskDelegate.swift */, + D31B7CCA15AA686CB755B3BEB4CCC4F2 /* Timeline.swift */, + 91E8C8BB25B6049ED0E24B7BD8A72833 /* Validation.swift */, + D0AC307BA480DC306EDE67D4DE3C3D06 /* Support Files */, ); - name = "Support Files"; - path = "../Target Support Files/EVReflection"; + name = Alamofire; + path = Alamofire; + sourceTree = ""; + }; + ECDDF771C01C7C0B930C3333E29E5F48 /* EVReflection */ = { + isa = PBXGroup; + children = ( + 5F388EAEC8DB889FD267869D95DF16DC /* Core */, + 39BCD84CAE6A4070B7D31D70ACD279D4 /* Support Files */, + ); + name = EVReflection; + path = EVReflection; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ + 30CC8A9A4F61EE5EF6260CB8A46BDE90 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 226FA026D93E7F8FC585FC6063181AD3 /* Pods-ProjectX-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 3B4E64726DCB072C61F2A31ACA34DFAA /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; @@ -324,11 +433,11 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - ADF8CC690BCFA366F2318EFA03CC0F15 /* Headers */ = { + B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 609B212E172C917DE6BC45AD18C6F50F /* Pods-ProjectX-umbrella.h in Headers */, + 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -349,7 +458,7 @@ ); name = EVReflection; productName = EVReflection; - productReference = E949E031ED776DA8BAB844E8D88D5B95 /* EVReflection.framework */; + productReference = EC0E37150EFE8744FA8694F3B9639AC1 /* EVReflection.framework */; productType = "com.apple.product-type.framework"; }; 6234938D11D80B3FC422F04A4C0130CB /* Pods-ProjectXUITests */ = { @@ -367,25 +476,24 @@ ); name = "Pods-ProjectXUITests"; productName = "Pods-ProjectXUITests"; - productReference = 6DED991DC9DDB3966A93BEB6DF15C315 /* Pods_ProjectXUITests.framework */; + productReference = 4904A902F4B68B72C3AA30834763C994 /* Pods_ProjectXUITests.framework */; productType = "com.apple.product-type.framework"; }; - 768F964FE6D39D87DEDD9546C2AAB36B /* Pods-ProjectX */ = { + 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */ = { isa = PBXNativeTarget; - buildConfigurationList = F068C03EA322D2C370067F34739F7B95 /* Build configuration list for PBXNativeTarget "Pods-ProjectX" */; + buildConfigurationList = 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */; buildPhases = ( - 9A39E58BCFA3E61971CD7D4580355BF0 /* Sources */, - 3B0CD109FD613DD1279B794DC00F9BA2 /* Frameworks */, - ADF8CC690BCFA366F2318EFA03CC0F15 /* Headers */, + 32B9974868188C4803318E36329C87FE /* Sources */, + 99195E4207764744AEC07ECCBCD550EB /* Frameworks */, + B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */, ); buildRules = ( ); dependencies = ( - 15DCB334AD5D88D54C2E2929DA0C2A0C /* PBXTargetDependency */, ); - name = "Pods-ProjectX"; - productName = "Pods-ProjectX"; - productReference = 6FA8A74480C0CBE7684F3C66CA463B01 /* Pods_ProjectX.framework */; + name = Alamofire; + productName = Alamofire; + productReference = 157ACE4A08CC6F08E17163855D06659C /* Alamofire.framework */; productType = "com.apple.product-type.framework"; }; 8CD9126840F30ADCBC799E2EF885B001 /* Pods-ProjectXTests */ = { @@ -403,7 +511,26 @@ ); name = "Pods-ProjectXTests"; productName = "Pods-ProjectXTests"; - productReference = 6C690E2A9F1189BF962293860A419B0E /* Pods_ProjectXTests.framework */; + productReference = 634B4EBB683228097C9F925C048EDE56 /* Pods_ProjectXTests.framework */; + productType = "com.apple.product-type.framework"; + }; + FEEFCCE4BDE6B310D7D9580655442504 /* Pods-ProjectX */ = { + isa = PBXNativeTarget; + buildConfigurationList = 080F218308F73956B61CCDD7AB7EA216 /* Build configuration list for PBXNativeTarget "Pods-ProjectX" */; + buildPhases = ( + D4EB12AA41DA9499A2516F627E4235AD /* Sources */, + B6224973D5EBEA224F18B39D4DF37E2E /* Frameworks */, + 30CC8A9A4F61EE5EF6260CB8A46BDE90 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + 5742B9630C9F2F7A3A59030497337035 /* PBXTargetDependency */, + 5CFB7FB574747C912210A8D803436C02 /* PBXTargetDependency */, + ); + name = "Pods-ProjectX"; + productName = "Pods-ProjectX"; + productReference = 85B02DA6190FBD3121D47CD0E4DDAD39 /* Pods_ProjectX.framework */; productType = "com.apple.product-type.framework"; }; /* End PBXNativeTarget section */ @@ -423,12 +550,13 @@ en, ); mainGroup = 7DB346D0F39D3F0E887471402A8071AB; - productRefGroup = 78849575C95BAEEF4B546717CADDD8D8 /* Products */; + productRefGroup = BCAC7F36C287DF32CC3151E86BC6ACE3 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( + 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */, 16297A64D8F519B9DFFF85EBEF75A597 /* EVReflection */, - 768F964FE6D39D87DEDD9546C2AAB36B /* Pods-ProjectX */, + FEEFCCE4BDE6B310D7D9580655442504 /* Pods-ProjectX */, 8CD9126840F30ADCBC799E2EF885B001 /* Pods-ProjectXTests */, 6234938D11D80B3FC422F04A4C0130CB /* Pods-ProjectXUITests */, ); @@ -452,6 +580,31 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 32B9974868188C4803318E36329C87FE /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */, + A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */, + F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */, + 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */, + B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */, + A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */, + EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */, + BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */, + 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */, + CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */, + F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */, + 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */, + 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */, + 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */, + AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */, + 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */, + 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */, + BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 896EA02A9C036F568B2734D92771BE44 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -470,33 +623,39 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 9A39E58BCFA3E61971CD7D4580355BF0 /* Sources */ = { + D4EB12AA41DA9499A2516F627E4235AD /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 46B8F4E1B21BED078515D240556F539F /* Pods-ProjectX-dummy.m in Sources */, + 698BBBFB3185479E0F43E43146AD95AD /* Pods-ProjectX-dummy.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ - 15DCB334AD5D88D54C2E2929DA0C2A0C /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = EVReflection; - target = 16297A64D8F519B9DFFF85EBEF75A597 /* EVReflection */; - targetProxy = FA922E8AE223D814E1916D80C3B03A3A /* PBXContainerItemProxy */; - }; 3F891F3D150F7E2343E40B01A2AD3658 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = "Pods-ProjectX"; - target = 768F964FE6D39D87DEDD9546C2AAB36B /* Pods-ProjectX */; + target = FEEFCCE4BDE6B310D7D9580655442504 /* Pods-ProjectX */; targetProxy = 3501ED93CE17B04955EB5DED0D489C9D /* PBXContainerItemProxy */; }; + 5742B9630C9F2F7A3A59030497337035 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; + targetProxy = 7FE4583BDA073E1C008082710298ED0B /* PBXContainerItemProxy */; + }; + 5CFB7FB574747C912210A8D803436C02 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = EVReflection; + target = 16297A64D8F519B9DFFF85EBEF75A597 /* EVReflection */; + targetProxy = A2C70781B2C669F4EF1202CD4896A6CB /* PBXContainerItemProxy */; + }; 82C8D595986866A369CD0BDCA105BC06 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = "Pods-ProjectX"; - target = 768F964FE6D39D87DEDD9546C2AAB36B /* Pods-ProjectX */; + target = FEEFCCE4BDE6B310D7D9580655442504 /* Pods-ProjectX */; targetProxy = 9B9945FEE36193EF2B13A4E181CCD20B /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ @@ -504,7 +663,7 @@ /* Begin XCBuildConfiguration section */ 0F6755768619F57B13D49E6FFB1CC903 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 8B768B344769B3ED48B03F731575232D /* EVReflection.xcconfig */; + baseConfigurationReference = 0C0B1B43BC0B691F634814C5950D6D53 /* EVReflection.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; @@ -541,7 +700,7 @@ }; 2FA0876FCE3CE5A2DBC955DDA1DB8FB9 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 8B768B344769B3ED48B03F731575232D /* EVReflection.xcconfig */; + baseConfigurationReference = 0C0B1B43BC0B691F634814C5950D6D53 /* EVReflection.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; @@ -575,6 +734,46 @@ }; name = Debug; }; + 42BC3F076FC8F830FD81A26DD98E366D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 305A9F31B46411DAB1B031159F218E01 /* Pods-ProjectX.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-ProjectX/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 11.4; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-ProjectX/Pods-ProjectX.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; 5DC0083F57E9AB706B46C5B5D73B38D8 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { @@ -676,7 +875,7 @@ }; name = Debug; }; - 8463FD86DE9B578730B3CE45A29B1067 /* Release */ = { + 8D46EC130AA7A1776B423A7022D70578 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 855574B8A989C812505B042C43B00E82 /* Pods-ProjectX.release.xcconfig */; buildSettings = { @@ -794,6 +993,43 @@ }; name = Release; }; + A18C9CC7E37563F2891E7DC87F2DE6CE /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 24AC4A0182080FA5C1FF2C2646E92184 /* Alamofire.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + 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"; + PRODUCT_MODULE_NAME = Alamofire; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 4.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; AEEA80476F98EB645C4DD53EB2BB6D88 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { @@ -890,12 +1126,10 @@ }; name = Debug; }; - E2BD13BA5C72A87935E16BFCA49347AF /* Debug */ = { + EA0ADC75B20BB62958101306980460E6 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 305A9F31B46411DAB1B031159F218E01 /* Pods-ProjectX.debug.xcconfig */; + baseConfigurationReference = 24AC4A0182080FA5C1FF2C2646E92184 /* Alamofire.xcconfig */; buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CLANG_ENABLE_OBJC_WEAK = NO; CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; @@ -905,25 +1139,23 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-ProjectX/Info.plist"; + 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 = 11.4; + 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-ProjectX/Pods-ProjectX.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + PRODUCT_MODULE_NAME = Alamofire; + PRODUCT_NAME = Alamofire; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 4.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; @@ -933,6 +1165,15 @@ /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ + 080F218308F73956B61CCDD7AB7EA216 /* Build configuration list for PBXNativeTarget "Pods-ProjectX" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 42BC3F076FC8F830FD81A26DD98E366D /* Debug */, + 8D46EC130AA7A1776B423A7022D70578 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; 159F432BBF4726F7B46458EA31E9CA43 /* Build configuration list for PBXNativeTarget "EVReflection" */ = { isa = XCConfigurationList; buildConfigurations = ( @@ -951,20 +1192,20 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - E61F6B7F97001CDE567FEE6527F4E8B2 /* Build configuration list for PBXNativeTarget "Pods-ProjectXUITests" */ = { + 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { isa = XCConfigurationList; buildConfigurations = ( - C14BD4CE0B805C67985AA6D5DD3612D4 /* Debug */, - 975B858BCC20AA8111F38C3B3ED0C9B2 /* Release */, + EA0ADC75B20BB62958101306980460E6 /* Debug */, + A18C9CC7E37563F2891E7DC87F2DE6CE /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - F068C03EA322D2C370067F34739F7B95 /* Build configuration list for PBXNativeTarget "Pods-ProjectX" */ = { + E61F6B7F97001CDE567FEE6527F4E8B2 /* Build configuration list for PBXNativeTarget "Pods-ProjectXUITests" */ = { isa = XCConfigurationList; buildConfigurations = ( - E2BD13BA5C72A87935E16BFCA49347AF /* Debug */, - 8463FD86DE9B578730B3CE45A29B1067 /* Release */, + C14BD4CE0B805C67985AA6D5DD3612D4 /* Debug */, + 975B858BCC20AA8111F38C3B3ED0C9B2 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; diff --git a/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/Alamofire.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/Alamofire.xcscheme new file mode 100644 index 0000000..72d11d0 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/Alamofire.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/Pods-ProjectX.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/Pods-ProjectX.xcscheme index 23822aa..65ab82a 100644 --- a/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/Pods-ProjectX.xcscheme +++ b/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/Pods-ProjectX.xcscheme @@ -14,7 +14,7 @@ buildForAnalyzing = "YES"> @@ -45,7 +45,7 @@ diff --git a/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/xcschememanagement.plist b/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/xcschememanagement.plist index f6db755..dfe3bf2 100644 --- a/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/xcschememanagement.plist +++ b/Pods/Pods.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/xcschememanagement.plist @@ -4,34 +4,41 @@ SchemeUserState - EVReflection.xcscheme + Alamofire.xcscheme isShown orderHint 0 - Pods-ProjectX.xcscheme + EVReflection.xcscheme isShown orderHint 1 - Pods-ProjectXTests.xcscheme + Pods-ProjectX.xcscheme isShown orderHint 2 - Pods-ProjectXUITests.xcscheme + Pods-ProjectXTests.xcscheme isShown orderHint 3 + Pods-ProjectXUITests.xcscheme + + isShown + + orderHint + 4 + SuppressBuildableAutocreation diff --git a/Pods/Target Support Files/Alamofire/Alamofire-dummy.m b/Pods/Target Support Files/Alamofire/Alamofire-dummy.m new file mode 100644 index 0000000..a6c4594 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Alamofire : NSObject +@end +@implementation PodsDummy_Alamofire +@end diff --git a/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch b/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h b/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h new file mode 100644 index 0000000..00014e3 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double AlamofireVersionNumber; +FOUNDATION_EXPORT const unsigned char AlamofireVersionString[]; + diff --git a/Pods/Target Support Files/Alamofire/Alamofire.modulemap b/Pods/Target Support Files/Alamofire/Alamofire.modulemap new file mode 100644 index 0000000..d1f125f --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire.modulemap @@ -0,0 +1,6 @@ +framework module Alamofire { + umbrella header "Alamofire-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Alamofire/Alamofire.xcconfig b/Pods/Target Support Files/Alamofire/Alamofire.xcconfig new file mode 100644 index 0000000..6b8baab --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Alamofire +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +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_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/Alamofire/Info.plist b/Pods/Target Support Files/Alamofire/Info.plist new file mode 100644 index 0000000..2aba7e5 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 4.7.3 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-acknowledgements.markdown b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-acknowledgements.markdown index 91105db..32907cc 100644 --- a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-acknowledgements.markdown +++ b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-acknowledgements.markdown @@ -1,6 +1,29 @@ # Acknowledgements This application makes use of the following third party libraries: +## Alamofire + +Copyright (c) 2014-2018 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. + + ## EVReflection MIT 3 License diff --git a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-acknowledgements.plist b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-acknowledgements.plist index a36a999..0f3ed87 100644 --- a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-acknowledgements.plist +++ b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-acknowledgements.plist @@ -12,6 +12,35 @@ Type PSGroupSpecifier + + FooterText + Copyright (c) 2014-2018 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. + + License + MIT + Title + Alamofire + Type + PSGroupSpecifier + FooterText MIT 3 License diff --git a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-frameworks.sh b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-frameworks.sh index 08514d0..be77bf1 100755 --- a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-frameworks.sh +++ b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-frameworks.sh @@ -143,9 +143,11 @@ strip_invalid_archs() { if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" install_framework "${BUILT_PRODUCTS_DIR}/EVReflection/EVReflection.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" install_framework "${BUILT_PRODUCTS_DIR}/EVReflection/EVReflection.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then diff --git a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.debug.xcconfig b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.debug.xcconfig index 5634160..b3da02c 100644 --- a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.debug.xcconfig +++ b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.debug.xcconfig @@ -1,9 +1,9 @@ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection" 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}/EVReflection/EVReflection.framework/Headers" -OTHER_LDFLAGS = $(inherited) -framework "EVReflection" +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection/EVReflection.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "EVReflection" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) diff --git a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.release.xcconfig b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.release.xcconfig index 5634160..b3da02c 100644 --- a/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.release.xcconfig +++ b/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.release.xcconfig @@ -1,9 +1,9 @@ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection" 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}/EVReflection/EVReflection.framework/Headers" -OTHER_LDFLAGS = $(inherited) -framework "EVReflection" +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection/EVReflection.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "EVReflection" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) diff --git a/Pods/Target Support Files/Pods-ProjectXTests/Pods-ProjectXTests.debug.xcconfig b/Pods/Target Support Files/Pods-ProjectXTests/Pods-ProjectXTests.debug.xcconfig index 612c2bc..e3ca40e 100644 --- a/Pods/Target Support Files/Pods-ProjectXTests/Pods-ProjectXTests.debug.xcconfig +++ b/Pods/Target Support Files/Pods-ProjectXTests/Pods-ProjectXTests.debug.xcconfig @@ -1,7 +1,7 @@ -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection" 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}/EVReflection/EVReflection.framework/Headers" +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection/EVReflection.framework/Headers" PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. diff --git a/Pods/Target Support Files/Pods-ProjectXTests/Pods-ProjectXTests.release.xcconfig b/Pods/Target Support Files/Pods-ProjectXTests/Pods-ProjectXTests.release.xcconfig index 612c2bc..e3ca40e 100644 --- a/Pods/Target Support Files/Pods-ProjectXTests/Pods-ProjectXTests.release.xcconfig +++ b/Pods/Target Support Files/Pods-ProjectXTests/Pods-ProjectXTests.release.xcconfig @@ -1,7 +1,7 @@ -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection" 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}/EVReflection/EVReflection.framework/Headers" +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection/EVReflection.framework/Headers" PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. diff --git a/Pods/Target Support Files/Pods-ProjectXUITests/Pods-ProjectXUITests.debug.xcconfig b/Pods/Target Support Files/Pods-ProjectXUITests/Pods-ProjectXUITests.debug.xcconfig index 612c2bc..e3ca40e 100644 --- a/Pods/Target Support Files/Pods-ProjectXUITests/Pods-ProjectXUITests.debug.xcconfig +++ b/Pods/Target Support Files/Pods-ProjectXUITests/Pods-ProjectXUITests.debug.xcconfig @@ -1,7 +1,7 @@ -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection" 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}/EVReflection/EVReflection.framework/Headers" +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection/EVReflection.framework/Headers" PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. diff --git a/Pods/Target Support Files/Pods-ProjectXUITests/Pods-ProjectXUITests.release.xcconfig b/Pods/Target Support Files/Pods-ProjectXUITests/Pods-ProjectXUITests.release.xcconfig index 612c2bc..e3ca40e 100644 --- a/Pods/Target Support Files/Pods-ProjectXUITests/Pods-ProjectXUITests.release.xcconfig +++ b/Pods/Target Support Files/Pods-ProjectXUITests/Pods-ProjectXUITests.release.xcconfig @@ -1,7 +1,7 @@ -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection" 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}/EVReflection/EVReflection.framework/Headers" +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/EVReflection/EVReflection.framework/Headers" PODS_BUILD_DIR = ${BUILD_DIR} PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_PODFILE_DIR_PATH = ${SRCROOT}/. diff --git a/ProjectX.xcodeproj/project.pbxproj b/ProjectX.xcodeproj/project.pbxproj index fcf2c7f..5d8ca28 100644 --- a/ProjectX.xcodeproj/project.pbxproj +++ b/ProjectX.xcodeproj/project.pbxproj @@ -376,10 +376,12 @@ ); inputPaths = ( "${SRCROOT}/Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX-frameworks.sh", + "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework", "${BUILT_PRODUCTS_DIR}/EVReflection/EVReflection.framework", ); name = "[CP] Embed Pods Frameworks"; outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/EVReflection.framework", ); runOnlyForDeploymentPostprocessing = 0; diff --git a/ProjectX.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/xcschememanagement.plist b/ProjectX.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/xcschememanagement.plist index c6e979b..24f3435 100644 --- a/ProjectX.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/xcschememanagement.plist +++ b/ProjectX.xcodeproj/xcuserdata/burcugen.xcuserdatad/xcschemes/xcschememanagement.plist @@ -7,7 +7,7 @@ ProjectX.xcscheme orderHint - 4 + 5 diff --git a/ProjectX.xcworkspace/xcuserdata/burcugen.xcuserdatad/UserInterfaceState.xcuserstate b/ProjectX.xcworkspace/xcuserdata/burcugen.xcuserdatad/UserInterfaceState.xcuserstate index 45f5f4b265d7c8d8a9bc7c1606536c5967718d52..01c8803c67d72ced4a5f21126bea7d76c2fd8524 100644 GIT binary patch delta 6480 zcmZu#2V7Lg^WWJea^>CKyZWwk+(YbGvE11}ELac$dqI#>v7vyy+?+;@v3u5-sDO&S zmqcSMF-DCkYD}}lRAWqxKhum!%zqEW6#u*rpZD&)*_rRo&U|-fcZJ~L99UvuJJ`;p zwpu|ei6#nSBqm}e)k!?5L28m(q&BHT>XW9VE9pkkNOzJ>dXNl~NwP>!(u?#a1IZvV zgp4L*NC6p3#*soYo&*V!XUSZ$m@FYn$ud$(%E(5tiEJk2WDD6vc9X;8W%3F+LQas= z&urFc=Q`Fak!xD3}33KnTH1m<7+mY?uR!U@}NSo5OG>InDuCyCXqrK>0I+Tv21+<73(@AtX z4bjc{ES}Y1HCZiIo7G`;SyR@G zHD@hY66?acvTiJmb!Um`tOx7Q2C#u_5F5_&*$6h0jb{_sL^g#z&*rlQY$033ma!FV zC0oVTvJ$q5Z3%ayt=X&S4KJdjj8@_$GOAI7R;-3c(TDM24XYO}Wo^Qlth>#cn$o^^ z{+PUiiCHi3Sl|Ogqz*;M9;aQ5KwFh!g?ep@B3ks78134m5R+;QW`jNO2(iiO|q(3_Nklkim zbCOMROUYo8gHDvOdX;b<8BPpkBtV9eVdz3P#*~qKZhItpxV>2Jpkt{*dDQf-yOTlS}!V#442&$dvzA<@5@bap;xXj@|GNWg#+iP+DfU z@x?jZqe+E@Ig`ssh|D61z0)!)eqQQOVRSZ`lPwybNd9fTjLiP0{pZMh5?4y*k>{}{ z)+!|n$U>}*b+{i?Qce#NCNGe<&15-QK~|DgWHniXb+H~MV0~&O0mHzA8aMtiJ^pS z!^S0K2R1=(wy5KSd*zH8A1F$y7*{2_hwP8Q-AndiA~r202gm_z#;^E3>4gO&0z-=X zWThA66{T0nA0@}0sD2GwpttJ7NpdQh#BJDs@rv*ot2>3fNzOfyJddsZmVBGMQz=+A z^dfmbg5eUmjBT)OX=MHt^NtT!wdt(5DDgs_#b`%89rc&go7m6TwH7@m}10ST;N13Ngt z2`+GBI`+T}%)~70iM_Bl_Ss5gh~=7+NitN2c&Gt2xnufrtrEYM;3nLRySarPDr5Ml za%Eh2lsv4LH{YhLoWI<2p z1-+pU^o4#n1oJR}Lva`m$NX{_00UtVWb-Qra&ZKX#2Gk~U-NMRN4HumC6GWc2nNS}-cFXi#3kkny7fV~V>5#tbVSUJ+fe6nbpH zNtJvv3znBg7(ox$*^|rRH%6`9t#qg*{VwicjJ$k#JUT zo_#~}M+GX7z&_X??jXdlQaBJ!5xnt_6&!-Yup4LN9Gq2=ts-28SGnS2@ERP46X6Yl z#Gb=>;UhxRD0m%ChjkhY*YQSJqj5#Sn{YOqps5=L=SU)ds1rs*BlQJ7{B1Y^@4{>0 zV+N_lLVT_g!X>!eGcB`cM%PlfL=r2VbtMuAAK+q~6pl3-gNe@g*gYJAPPXgSK=yMjcYb?E=h*_JQaQ1nJ-kN z<9o*GF%K(Nw`%a8@K+=m9^s26B$>;_hsT*6-Dwo9#$Q+LWHcJrJ?0&%;yW2tQvugw z=@ZVOI%@ncOHdQ>Pz!G0R!exw+%eg*se{HmCB~V8da;a)ZA9xCO+IUtPg9ddy%^M{?$pbo{uHd9k7tn=t5nW7|(4}-44b$a#3}3_Jcmhx2DSRDI z;~QJ~qO78;=^FY1T}xl2FVS^;fzIG(_$A&CfiVQ85LiOM0hCPm3`fYSa zBpSBkn_Z9U1hq(3N7R4$!pVMz6aK4~l(y!>(^cMYw z-o}scWBdfK;x)XEH~1bxzx&r7^65YJkiX%Cw}=lTIBdVuN0m7KmLQJRV+~1M8B1XGSp)nLf5M;3SR>Y$ zHNjs(U)&#|l|d2% z?@y4wH3r=v^M*K?mpok}g$-o#8m2Gw=fz5-P?-kHcz63IT!44rJ-Ea>+G}uwZ(?8Y z&h{4ErqMK(%DjKAO%rKr+J*P5z3G68j&&lP#xs2-Pvu=a3s2K?yd}NN8_}=nkBl%g zvoa@hGf$BBoOM_O-eb0AZTY&SuvFH=bj)2uQ$ru(M9%u!~+tTUU; zwaj(RN#;y*FLVD&Pf&PVo6LTEe|$3!M4`&HQ`t=3e((jK&StRo3|R;tgg_mFS^_={ zfhGjn&8#CFX0zEGPOFD`9Lx!UE(Cf`uX7^t;H`*<-pzx-#oXab*izmnB^2k64#-I- z=Dn)y-8UfwVnwOI!fbgj-lydh2TEC(Bo4|d$jh1R$tm_UYT#?!MEtgbbJ=Q=TS7EQ z|BlKR**eZ-k#{9*eF)5tcV1TdL^3imsAii8+fti?vuT^z^AW(}hR6SNd$Qtsr8^qSLqwG5SE-E@ojIu_59{pwX z_t6g&pwKBS3YQ{Y(OA(z(Mi!+(N&SANLOSivJ|}(eH0@VqZI{;af%|vc*R7;WW`j) zbVX3HTCrVmRdH7trEIKhtISm9D2FKXl;f1e$_dKJ%Bjlf%B9K|lrWoKPf85GDyzgt@|V!aQNVus|pi_6YlhgTl+g5#d$goN!)vOL$xO zMEF$rO!z|hM)+3vPPnV7rm3k()HK)lG_5pkG)bDynqUu2rlzN+x2CUVsAjaLKr>EL zq?w|brkSBZ%}mV-%{t9?%|6Wm%^}Upn&X<2n%6aNXx`LZ(cIA7(cIVkr1?ejK=YRt zv`qVqHd<@f%Gw6nL~S!|3vFv{TWzv7MVqUAR=ZTYQM*~YMY~PAL%U16N4rmZKzm4g zPWx6+`?mI7?M3Zn?G^2Z+K;tYwb!-xbV{A1OVG8@b=MW@=IEB{*6B)gWxCC}ExK*G zOS(^WpXejG6Wfae#qr_{F(l3sXN$|k60uC& zB$kU?#qHuwaku!IctSiSo)*uD!L#Cd@q+k{cvZZmr+SONkv?5NKtE1DL%&eJSie*s z*00d7(y!64)o;`9(C^ak(eKkA&>zyjtUsdv%s>qBhR%kuh82cmhU10{hKq*FhAW0o z4A%@d3^xs58-6xCGW=x(qspi=8jKF3%NS#fH8wS-8v7VW8s{441&#BK3yq77OO3A^ zFBmTxFB`8IKQw-6{K5FM@mJ$-#@|iMB$(=$8koA92ABq!2AgtC!%X?638tB*1*S!& zC8lMjlcw{go2IW!zjIcrZ*F4FHZL~6Xx?bvW8P;zU_N9%Zhpgj-hA2of%zlzC+7c| zA6cR;N{iZ}vFI#8tHo|{THF?o#cQc!Nwl=J^sxjiV=QAWg_dH=1WV8ovdpr~w#>E6 zvy@v-TW(22Qc5aGkZh7ua!aw2ELE3UNFAh9sf&~*rArx7e`&CkE9FT;r6OsHG)ALi-bVvG5x-0!IJ+cxj zvp!>uwmPhF)>_s&)_T_Z)|S?G*7nwp)>Lb{HN%=^?Pcv_&9#oSPO=8AA?qybZ0iE+ zBI^?CGV5~dX6tV23F{T>4>pxeuxV|g&0wozYhv@;I@(6qCfFv~rr3hhY%^?O+X~w% z+Zx+i+e^01w(Yi^w%xY9w%2SYY^Q9eZ5M5qZC7j`+OFAd+wR!DxBXyO*j0AHuC2Nzd4zDB55$~w!@H<*L+BlLN z?HuhLog7^pX+cL1N2X(hW3FSlW4q&qU7g*XJ)D`&SMM(1AVe&<2wVOKSm(dBi;x#C?lUA0|xT?wuRt~RbDS36gGS4UT>tBb3f ztGjE0YlZ8m>r?kL?%M7QceXpvJ=8tiJ=$I19_J1gxo5g(yXU%>yUX00+~w}A?(OcK z?%nRa?i21)?$how?z8Um?hEdB-0!)6jj_bEj2Rp=CuV!h<(Qi>U&Y*txgB#i=3dPG zn4dh%BYKP;v&ZVOdz_xyp2nWGo*te|Pft&8PhU@e&p=PMC&yFhDfUe8O!7?eO!Lg} zV9+zu^Q>o)XN_l{=bYz;=f_xeY+S4_c53X**m<$bV@qPU#BPh-5xXn)VC>=8BeBO~ zkH_BkYP|8@`d**6rMI;=$(!Qs=uP$Z@(%Q7dvm-)yd%7$ykop$y@lSj-gDlcy^rK) zWUcIwy>gr!FV~do%MIlwax=MwoGb@ZebanFU&!~YZ?12-Z>4XwZ>?{g zZ-cMYx6yabch_(AC;PkjGyMbn+5X}F0)Mf8mVdT?k$|fz8?cm?!FZXZr@AU8X tzwAHiKjuH~KkGl|f6M>A|3m-B{;U4){rCM39@i$c^3L}ByEgGZ{68f@X*K`= delta 6235 zcmZu#2V7Iv_doYOlos2nsk6bF9`utt-{4bpZ~X zt+kG7t+v+DI$F22wN>k=QfFJ+I{!ByT7UkN56R=bbMG17?>Xn5Je*24O(JsyZah~I zs25VpuO-zW6eOSr1MpA-YC$7Lmo| zL$ZYUSCciQjI1Y{$tPqR`JC(~Uy&o^C^<&Xksru;a*{;8b#~TMzkqyPFvBA^iA4{cBj3lmky-qbU4kXIdmKyPYdW| zI)%PNKcq|OQa@crm(vxrn3m8|x{|J=AJebsKKeD?PY=+8^bq}q9;YYhIr;-VPjAyZ z^e(+e@6$i%pY$*Kfc{PYq5sl{^buE$tImaT5>CUJISXgyY@D5Qa89l+7s*9&^|+>- zoAYq3xi(x|t^?PbOXd1-eK~DEZUC3gWpF+&lgr`qxY2<;+JgHGQv;vUEWH)NAROhW zL>0dGeoa-7Gz_kp7hGde4TSkVAA?)i$wdRDj9v-M2`qVFxrfG}? z1q~ZSIb$0ZMmY-_G>(aha=IJF78afaDab$$anJ@L*1{Xm44Oj=XbJJq3KF0-YEg%J zG$4-x8qtK}T4)PSXb&BrBfJTn*mV~)GqYx50LySaZe!Px=zFVUo3?E;GV^nCLt5qf zyn%(1T>-yD%&1bB3h6Vro2RhM(VHmy^GQby9!`_)N z6o!EVBhXW!CK89>+c=rU#n&gxJ1%EbesZqQ7r3ih5Rs&uHZ-9-x5|dix=6c7Kzy^pt2_G?KAH!z&1Sa&&$VneH zoM}wy(K$6gbGR=r-#dH+HpE7OIff=JU>j^t)9BmuOm6dBu5(VhH$O8cy99PX?En9$ zQteLI6$s&@Lf~_VWfzgnUk&0HER54w{h0to*n~y7DZ+^gw(Wz(#Zbti9#gr`K{%AA zsTJ@tHn%maL*bjC+RFd)&H7L{3`f#5;lby+&M#0dfuljOire8YZ&wlQJ2(yz#qd4G z6~hU9gC)#5b^Ula1LuOb&tkJ;_yL=vFS(01GrMZh1-JydQurBufs5DzTVi}ETxO76 z!Bz~RK`a|ZjW-!?2JJ7$gdnb!`Ewf{K*Soj19#yb+=oBlPxuR4V;gLX?XW#|z>aI+ zZ}Br2lD&e#PLu`71N z?$~1u(GnfeLl?rcD;|?D8T&BP`m(FOn7ZYAJ4eDbhUaFHFj50_B_y0gU<&puAvH-Y z?1jCV9~X5Ne-tcUfiYULrve2MLmKo;Olp&v9>m_8JFbMpKy3J4sC;Rv|A+b{mNcoP zK6>%3O4?UIOWt6#C(TH6?2l>xL;FgWKhFfx23$cV4|u`kS2!DFCqf{NZa?%wh zknXUVaXfmUH_z9XedqeJ7)eL_7_Tz0VWkJjBqb#=iP5}-BtvZFy(6io4zQEB#mT1#7Z)Nc*#JLj+rEp%FPPf(sib3zwSooGf3v%&dH0ZkL>>3}2PaTgaynv0??jxUrpl7F@mqrxcT& z_)ewAe)2`o<2__APQ@87J>EwSzUIau=Ek=;jkz(Mx$&Yag~w+OsBoi7^LOOrYimz| zgPg%42Fbganx;{+)fN53|Gc4u$M@U&$|gUO3qflu@c9|vLsrXKcO{pC)?OyR;w+r| z(%Ng}=4%?unYFiYHnVmPrgjUD#}2RTf1f-EE@|@$rolD;R;-zasp0V>R=l$02?dBK zAy3IOd>`kRP(mp#zzLJBeuztO>1wK>TB-vF zHL$L`3`=n(3&v{p$6z!BgE@ADmvyj=j`_afc@@3)s@xU$QXUb=lP8MLV@vJS3A$qH zz~#l%g)12I9177yYtULOTC^q>7t`8U!fJ7_qjd|+RM`DAn#R0X(*RdtYSm_qY3wT$ zp>7)YLh=n<^HQ<}ZTYHX0&UA;L0i){xE9xyu#|H!S1O$0gNKE@uGv}RI{UoCe1T_* zm?YYnCRV{oyW)oDaMB)RW+_dg$utEw;>Wn<1*Eh$?f1Ws(zn1#({K}m^dsi@+sg1T znn8!WCYH&>hT&!=_6ZX^sI-UC5j6ibu~AHH41UVQwlc9$Rk)c>p#Gp&g>)ir#~mzf zSrJjOw=XbI73NRVSYEi+GczxfrD?EEbsad=m!6+j71XJ84m*y~X>>ZBL5t|SbS8a| z&Z4t%C+@<}aW{T}dvGs)iC?W{2F#-Y`aYdc7tjyrLb{0Q+K1oa3A{Loz$C&B_}nBC zQbCb~Krc(Ve-&NB;s}p%U@o{Kb?@#Ga@NxRBpPjbxua$C;PKj-_oNMt&kpJ zt?<}?T4DdH<56c{_Tc;>RS`K!PX}3b3coL=XYe=+w$*8Wlm1ArfUb=GL@&^v=`Zvm zy+kk5U-2ZK!qa#L&*C}!0neAws|*GQ{f*wBHz`X{{E-Doi9g{5{26~?*Qr~kIE^HX zKIT|@meMEmDSd{Q@G|~d$`Ouo9A3d^c!zLY6mu*p>w~ZtDFmcG_u8+OnZEk@O(RY$WYX z`mvF80BhwL#82jv9po_io}3`3$Qg2hO_-O-6>^>2Am!v1D~7B((K@UQd1wOdN_)`0 zbO4(i^Vr;ojQES$xcCWU<{^5No}yvAOzPwt=gVl7n?8gc>~fED6S%^ZqUY_c{*0v*=VzmNC?{n}q+}y_ z5}UH;ax1t?+)eI&=;xtdgdPk%5&C23jnKQHe@j3@BvfLR)R8okw2;J05+rRT?Iax} zZ%R5#5+zsgB?}}6BtJ;*NbS-{X$xsDX@+!+beyz6 zS}65PCrSO2rSC|mNoPoxNS8@hNK2$ErK_c7(sj}e(oNEjrMsl3q?e`t%0gsjS#w!; zS%z$stVp&}wnz4*Y@cku?4azT?1t>F?6KS-kCfMw*OxbtH>AseF}ujr<4sW%+ga4SBizmi(cjnnJEn`W0%0Rv{|F6s;8P6h1|+B406DF;-Ei zn5vki2q;!4HYm0!b|`i#K39}0{#448YGn;&v@%uMUpYfrqFkw5tt?ZnQ*KdiQ|?gi zRPIyWQr=ftRW($dRNYjgRg+ayRnt}Ps@_x0R&7^(tvaasMs-AWO!d9$wCb|zhRR>A zx~00KdZ7A8^-%R#^;BI~ouKZcPFD|74^ay8UZ&q(n?^PdBUspfU7&Wn)R+^rgbWN@%Uo%=WRx@5RK{HWIuRE?gsXMJZtGlSXrYqO|sh8=sdb8f9cj#Suzgyo{pQ!Jq@1alD z_tdB9z4~;$Pd`|nsn69H>F4X0>o@4P>bL7Z)9=#n)*sLx(toQzqCckpUVqylH$)rS z8@d^~8O9~XNFyd-G;-4 zbB1!mpN1#A%+G6Cnc;aOZ|9wS7$3pcWCh2=C-B|*-n@?=!Vl$#^Ev!T{vCcEAK>5T z7x1P0YQBtL&u`>E;`i}K_~ZOZ{xpAmo5C#kWOd(6i7Dfo;goy$QZwpg|xxzwWv9Lr~Cae)X(XF6}XZn|mu-E_xv&-8}~ zA`z(=B5FlJG>K->A-cqHv4+@OOcS%j9C4(WFOC++ij&0YVv#sgoF&c?mx?RJ)nb|G zUng!Bw}@NC?c!(R5%IKmS-c^Zi?_r(;sfy?@uB!wd}>yhd2^V#jycj?&s^W!#OyZ5 znVXqgn7f<%meq@s<5i9TC2e-SWVU%*4oy( z)_T_Z)&|xV)-Kkr*6!9MYl^j(HPzbJI@FqF&9;uP=34Wuqpf4D@Bww<=!wmr75Y+u_B*iP9l*!(wbk8DqD&+Np`*{j(@ z?NYnkZnfL(PJ5U=!d}x}+g{fmWskPI?XB(o?0NR-_NDf%_G9)djv9_AMHyyt_ZaW@1sWZe`-6?UZom!{f z$vcgHXS_4px!76iT<6^4-0M8({Kk3MdDMBzdB%CpdEWVx^Q!Z@^Op0Wi?}#fHCL!h z<3WlC(={T z6X$8}Y3WJuwDq+2bn_&6Qarsp13X?&x+lw%;~DA6^St9J^316`C{Z@n1z+66%I~UA H&%FNwDULi* From 1347ee8b638d8a6aaefad8b9cd08badbf5be1640 Mon Sep 17 00:00:00 2001 From: Burcu Geneci Date: Thu, 9 Aug 2018 12:08:45 +0300 Subject: [PATCH 4/5] Service Manager service call example. --- ProjectX.xcodeproj/project.pbxproj | 4 ++ ProjectX/Service/Model/BaseModels.swift | 12 ++++++ ProjectX/Service/ServiceManager.swift | 52 +++++++++++++++++++++++++ ProjectX/ViewController.swift | 9 +++++ 4 files changed, 77 insertions(+) create mode 100644 ProjectX/Service/ServiceManager.swift diff --git a/ProjectX.xcodeproj/project.pbxproj b/ProjectX.xcodeproj/project.pbxproj index 5d8ca28..a66edca 100644 --- a/ProjectX.xcodeproj/project.pbxproj +++ b/ProjectX.xcodeproj/project.pbxproj @@ -11,6 +11,7 @@ AB8A370CC1BBFFA3F6022451 /* Pods_ProjectXUITests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 24CCC3DFFE3507708E94E347 /* Pods_ProjectXUITests.framework */; }; C97E23EA011DD39C7D2C3F0E /* Pods_ProjectX.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 82D2DA5945F42F2A91D57748 /* Pods_ProjectX.framework */; }; E2222F43211378A800AB33CC /* BaseModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2222F42211378A800AB33CC /* BaseModels.swift */; }; + E2222F452113854900AB33CC /* ServiceManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2222F442113854800AB33CC /* ServiceManager.swift */; }; E25D0D0C20DE4F3A0050A254 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = E25D0D0B20DE4F3A0050A254 /* AppDelegate.swift */; }; E25D0D0E20DE4F3A0050A254 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E25D0D0D20DE4F3A0050A254 /* ViewController.swift */; }; E25D0D1120DE4F3A0050A254 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = E25D0D0F20DE4F3A0050A254 /* Main.storyboard */; }; @@ -48,6 +49,7 @@ ACBF95D0EEC860AD39502B82 /* Pods-ProjectX.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ProjectX.release.xcconfig"; path = "Pods/Target Support Files/Pods-ProjectX/Pods-ProjectX.release.xcconfig"; sourceTree = ""; }; B70FA1B5BBA6872F2F2C4247 /* Pods-ProjectXUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ProjectXUITests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-ProjectXUITests/Pods-ProjectXUITests.debug.xcconfig"; sourceTree = ""; }; E2222F42211378A800AB33CC /* BaseModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BaseModels.swift; sourceTree = ""; }; + E2222F442113854800AB33CC /* ServiceManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ServiceManager.swift; sourceTree = ""; }; E25D0D0820DE4F3A0050A254 /* ProjectX.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ProjectX.app; sourceTree = BUILT_PRODUCTS_DIR; }; E25D0D0B20DE4F3A0050A254 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; E25D0D0D20DE4F3A0050A254 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; @@ -118,6 +120,7 @@ isa = PBXGroup; children = ( E2222F412113789300AB33CC /* Model */, + E2222F442113854800AB33CC /* ServiceManager.swift */, ); path = Service; sourceTree = ""; @@ -399,6 +402,7 @@ E2222F43211378A800AB33CC /* BaseModels.swift in Sources */, E25D0D0E20DE4F3A0050A254 /* ViewController.swift in Sources */, E25D0D0C20DE4F3A0050A254 /* AppDelegate.swift in Sources */, + E2222F452113854900AB33CC /* ServiceManager.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/ProjectX/Service/Model/BaseModels.swift b/ProjectX/Service/Model/BaseModels.swift index 8911467..9a44cf2 100644 --- a/ProjectX/Service/Model/BaseModels.swift +++ b/ProjectX/Service/Model/BaseModels.swift @@ -14,3 +14,15 @@ class BaseModel: EVObject { } class BaseRequestModel : BaseModel { } class BaseResponseModel : BaseModel { } + +class ErrorModel : BaseModel { + var code : String? +} + +class PokemonFormModel : BaseModel{ + var url : String? + var name : String? +} +class PokemonResponseModel : BaseResponseModel{ + var forms :[PokemonFormModel] = [PokemonFormModel]() +} diff --git a/ProjectX/Service/ServiceManager.swift b/ProjectX/Service/ServiceManager.swift new file mode 100644 index 0000000..fb86692 --- /dev/null +++ b/ProjectX/Service/ServiceManager.swift @@ -0,0 +1,52 @@ +// +// ServiceManager.swift +// ProjectX +// +// Created by Burcu Geneci on 2.08.2018. +// Copyright © 2018 GDG Istanbul. All rights reserved. +// + +import UIKit +import Alamofire +import EVReflection + +class ServiceManager: NSObject { + static let shared = ServiceManager() + private override init() {} + + typealias SuccessCompletion = (BaseResponseModel?) -> Void + typealias ErrorCompletion = (ErrorModel?) -> Void + + func request(url : String, + method : HTTPMethod? = .post, + request : BaseRequestModel? = nil, + responseClass : BaseResponseModel.Type? = BaseResponseModel.self, + successCompletion : SuccessCompletion? = nil, + errorCompletion : ErrorCompletion? = nil){ + + Alamofire.request(url).responseData { (response) in + switch response.result{ + case .success(let data): + do{ + let dataDictionary = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary + let className = NSStringFromClass(responseClass!) +// EVReflection.setBundleIdentifier(BaseModel.self) + let responseModel = EVReflection.fromDictionary(dataDictionary!, anyobjectTypeString: className) as? BaseResponseModel + debugPrint(responseModel) + successCompletion?(responseModel) + }catch{ + + } + break + case .failure(let error): + let errorModel = ErrorModel() + errorModel.code = error.localizedDescription + errorCompletion?(errorModel) + break + } + } + } + + + +} diff --git a/ProjectX/ViewController.swift b/ProjectX/ViewController.swift index 8c991d3..6cbd91b 100644 --- a/ProjectX/ViewController.swift +++ b/ProjectX/ViewController.swift @@ -7,12 +7,21 @@ // import UIKit +import Alamofire +import EVReflection class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. + + + + ServiceManager.shared.request(url: "https://pokeapi.co/api/v2/pokemon/1/", + responseClass: PokemonResponseModel.self) + + } override func didReceiveMemoryWarning() { From 8db76cd78eb1caf4fcec15cf874081068383b2e5 Mon Sep 17 00:00:00 2001 From: Burcu Geneci Date: Fri, 7 Sep 2018 11:28:01 +0300 Subject: [PATCH 5/5] FeedItemsModel added. --- ProjectX.xcodeproj/project.pbxproj | 4 ++++ ProjectX/Service/Model/BaseModels.swift | 22 +++++++++++++++++----- ProjectX/Service/ServiceEndpoints.swift | 18 ++++++++++++++++++ ProjectX/Service/ServiceManager.swift | 11 +++++++++-- ProjectX/ViewController.swift | 13 +++++++------ 5 files changed, 55 insertions(+), 13 deletions(-) create mode 100644 ProjectX/Service/ServiceEndpoints.swift diff --git a/ProjectX.xcodeproj/project.pbxproj b/ProjectX.xcodeproj/project.pbxproj index a66edca..1d13642 100644 --- a/ProjectX.xcodeproj/project.pbxproj +++ b/ProjectX.xcodeproj/project.pbxproj @@ -19,6 +19,7 @@ E25D0D1620DE4F3D0050A254 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = E25D0D1420DE4F3D0050A254 /* LaunchScreen.storyboard */; }; E25D0D2120DE4F3D0050A254 /* ProjectXTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E25D0D2020DE4F3D0050A254 /* ProjectXTests.swift */; }; E25D0D2C20DE4F3D0050A254 /* ProjectXUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E25D0D2B20DE4F3D0050A254 /* ProjectXUITests.swift */; }; + E2B38D3021419F9D00AFEE1D /* ServiceEndpoints.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2B38D2F21419F9D00AFEE1D /* ServiceEndpoints.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -63,6 +64,7 @@ E25D0D2720DE4F3D0050A254 /* ProjectXUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = ProjectXUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; E25D0D2B20DE4F3D0050A254 /* ProjectXUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProjectXUITests.swift; sourceTree = ""; }; E25D0D2D20DE4F3D0050A254 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + E2B38D2F21419F9D00AFEE1D /* ServiceEndpoints.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ServiceEndpoints.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -121,6 +123,7 @@ children = ( E2222F412113789300AB33CC /* Model */, E2222F442113854800AB33CC /* ServiceManager.swift */, + E2B38D2F21419F9D00AFEE1D /* ServiceEndpoints.swift */, ); path = Service; sourceTree = ""; @@ -402,6 +405,7 @@ E2222F43211378A800AB33CC /* BaseModels.swift in Sources */, E25D0D0E20DE4F3A0050A254 /* ViewController.swift in Sources */, E25D0D0C20DE4F3A0050A254 /* AppDelegate.swift in Sources */, + E2B38D3021419F9D00AFEE1D /* ServiceEndpoints.swift in Sources */, E2222F452113854900AB33CC /* ServiceManager.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/ProjectX/Service/Model/BaseModels.swift b/ProjectX/Service/Model/BaseModels.swift index 9a44cf2..9e39299 100644 --- a/ProjectX/Service/Model/BaseModels.swift +++ b/ProjectX/Service/Model/BaseModels.swift @@ -9,6 +9,8 @@ import UIKit import EVReflection +//class BaseModel: Codable { } We can continue with Codable either. + class BaseModel: EVObject { } class BaseRequestModel : BaseModel { } @@ -19,10 +21,20 @@ class ErrorModel : BaseModel { var code : String? } -class PokemonFormModel : BaseModel{ - var url : String? - var name : String? +class FeedResponseModel : BaseResponseModel{ + var feedItems : [FeedItemModel] = [FeedItemModel]() } -class PokemonResponseModel : BaseResponseModel{ - var forms :[PokemonFormModel] = [PokemonFormModel]() + +class FeedItemModel : BaseModel { + var id : Int = 0 + var categoryId : Int = 0 + var lat : CGFloat = 0.0 + var long : CGFloat = 0.0 + var title : String? + var openingTime : Int = 0 + var maxLiveTime : Int = 0 + var serviceHour : Int = 0 + var numberOfComments : Int = 0 + var numberOfBids : Int = 0 } + diff --git a/ProjectX/Service/ServiceEndpoints.swift b/ProjectX/Service/ServiceEndpoints.swift new file mode 100644 index 0000000..1df717c --- /dev/null +++ b/ProjectX/Service/ServiceEndpoints.swift @@ -0,0 +1,18 @@ +// +// ServiceEndpoints.swift +// ProjectX +// +// Created by Burcu Geneci on 6.09.2018. +// Copyright © 2018 GDG Istanbul. All rights reserved. +// + +import UIKit + +public enum ServiceEndpoints : String{ + case base = "https://us-central1-zumbara-x.cloudfunctions.net" + case feed = "getFeeds" + + public func getUrl()-> String{ + return "\(ServiceEndpoints.base.rawValue)/\(self.rawValue)" + } +} diff --git a/ProjectX/Service/ServiceManager.swift b/ProjectX/Service/ServiceManager.swift index fb86692..d10c4ef 100644 --- a/ProjectX/Service/ServiceManager.swift +++ b/ProjectX/Service/ServiceManager.swift @@ -17,21 +17,28 @@ class ServiceManager: NSObject { typealias SuccessCompletion = (BaseResponseModel?) -> Void typealias ErrorCompletion = (ErrorModel?) -> Void - func request(url : String, + func request(endPoint : ServiceEndpoints, method : HTTPMethod? = .post, request : BaseRequestModel? = nil, responseClass : BaseResponseModel.Type? = BaseResponseModel.self, successCompletion : SuccessCompletion? = nil, errorCompletion : ErrorCompletion? = nil){ + let url = endPoint.getUrl() + Alamofire.request(url).responseData { (response) in switch response.result{ case .success(let data): do{ let dataDictionary = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary let className = NSStringFromClass(responseClass!) -// EVReflection.setBundleIdentifier(BaseModel.self) + EVReflection.setBundleIdentifier(BaseModel.self) let responseModel = EVReflection.fromDictionary(dataDictionary!, anyobjectTypeString: className) as? BaseResponseModel + + /* Codable Implementation */ + // let responseModel = try? JSONDecoder().decode(responseClass!, from: data) + /* Codable Implementation End */ + debugPrint(responseModel) successCompletion?(responseModel) }catch{ diff --git a/ProjectX/ViewController.swift b/ProjectX/ViewController.swift index 6cbd91b..22ff132 100644 --- a/ProjectX/ViewController.swift +++ b/ProjectX/ViewController.swift @@ -14,12 +14,13 @@ class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() - // Do any additional setup after loading the view, typically from a nib. - - - - ServiceManager.shared.request(url: "https://pokeapi.co/api/v2/pokemon/1/", - responseClass: PokemonResponseModel.self) + ServiceManager.shared.request(endPoint: ServiceEndpoints.feed, + responseClass: FeedResponseModel.self, + successCompletion :{(response) in + if let responseModel = response as? FeedResponseModel{ + print(responseModel) + } + }) }