diff --git a/.gitignore b/.gitignore index d534044..5d40f71 100644 --- a/.gitignore +++ b/.gitignore @@ -52,7 +52,7 @@ playground.xcworkspace # Add this line if you want to avoid checking in source code from Carthage dependencies. # Carthage/Checkouts -Carthage/Build +# Carthage/Build # fastlane # diff --git a/APNSUtil.podspec b/APNSUtil.podspec index 62ff149..7b9dfcd 100644 --- a/APNSUtil.podspec +++ b/APNSUtil.podspec @@ -10,22 +10,12 @@ Pod::Spec.new do |s| s.name = 'APNSUtil' s.version = '1.0.0' s.summary = 'APNSUtil is makes code simple using apple push notification service.' - -# This description is used to generate tags and improve search results. -# * Think: What does it do? Why did you write it? What is the focus? -# * Try to keep it short, snappy and to the point. -# * Write the description between the DESC delimiters below. -# * Finally, don't worry about the indent, CocoaPods strips it! - s.description = 'APNSUtil is makes code simple using apple push notification service.' - s.homepage = 'https://github.com/pisces/APNSUtil' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'pisces' => 'hh963103@gmail.com' } s.source = { :git => 'https://github.com/pisces/APNSUtil.git', :tag => s.version.to_s } - - s.ios.deployment_target = '8.0' - + s.ios.deployment_target = '9.0' s.source_files = 'APNSUtil/Classes/**/*' - s.dependency 'AlamofireObjectMapper', '~> 5.0.0' + s.dependency 'ObjectMapper', '~> 2.0' end diff --git a/APNSUtil.xcodeproj/project.pbxproj b/APNSUtil.xcodeproj/project.pbxproj new file mode 100644 index 0000000..aed8b3e --- /dev/null +++ b/APNSUtil.xcodeproj/project.pbxproj @@ -0,0 +1,341 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 48; + objects = { + +/* Begin PBXBuildFile section */ + 2301E972205A51F300E0E358 /* APNSUtil.h in Headers */ = {isa = PBXBuildFile; fileRef = 2301E970205A51F300E0E358 /* APNSUtil.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2301E97B205A524B00E0E358 /* APNSInstance.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2301E978205A524B00E0E358 /* APNSInstance.swift */; }; + 2301E97C205A524B00E0E358 /* APNSManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2301E979205A524B00E0E358 /* APNSManager.swift */; }; + 2301E97D205A524B00E0E358 /* NSObject+Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2301E97A205A524B00E0E358 /* NSObject+Codable.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 2301E96D205A51F300E0E358 /* APNSUtil.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = APNSUtil.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 2301E970205A51F300E0E358 /* APNSUtil.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = APNSUtil.h; sourceTree = ""; }; + 2301E971205A51F300E0E358 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 2301E978205A524B00E0E358 /* APNSInstance.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = APNSInstance.swift; path = Classes/APNSInstance.swift; sourceTree = ""; }; + 2301E979205A524B00E0E358 /* APNSManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = APNSManager.swift; path = Classes/APNSManager.swift; sourceTree = ""; }; + 2301E97A205A524B00E0E358 /* NSObject+Codable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = "NSObject+Codable.swift"; path = "Classes/NSObject+Codable.swift"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 2301E969205A51F300E0E358 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 2301E963205A51F300E0E358 = { + isa = PBXGroup; + children = ( + 2301E96F205A51F300E0E358 /* APNSUtil */, + 2301E96E205A51F300E0E358 /* Products */, + ); + sourceTree = ""; + }; + 2301E96E205A51F300E0E358 /* Products */ = { + isa = PBXGroup; + children = ( + 2301E96D205A51F300E0E358 /* APNSUtil.framework */, + ); + name = Products; + sourceTree = ""; + }; + 2301E96F205A51F300E0E358 /* APNSUtil */ = { + isa = PBXGroup; + children = ( + 2301E978205A524B00E0E358 /* APNSInstance.swift */, + 2301E979205A524B00E0E358 /* APNSManager.swift */, + 2301E97A205A524B00E0E358 /* NSObject+Codable.swift */, + 2301E970205A51F300E0E358 /* APNSUtil.h */, + 2301E971205A51F300E0E358 /* Info.plist */, + ); + path = APNSUtil; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 2301E96A205A51F300E0E358 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 2301E972205A51F300E0E358 /* APNSUtil.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 2301E96C205A51F300E0E358 /* APNSUtil */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2301E975205A51F300E0E358 /* Build configuration list for PBXNativeTarget "APNSUtil" */; + buildPhases = ( + 2301E968205A51F300E0E358 /* Sources */, + 2301E969205A51F300E0E358 /* Frameworks */, + 2301E96A205A51F300E0E358 /* Headers */, + 2301E96B205A51F300E0E358 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = APNSUtil; + productName = APNSUtil; + productReference = 2301E96D205A51F300E0E358 /* APNSUtil.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 2301E964205A51F300E0E358 /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0920; + ORGANIZATIONNAME = pisces; + TargetAttributes = { + 2301E96C205A51F300E0E358 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 0920; + ProvisioningStyle = Automatic; + }; + }; + }; + buildConfigurationList = 2301E967205A51F300E0E358 /* Build configuration list for PBXProject "APNSUtil" */; + compatibilityVersion = "Xcode 8.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 2301E963205A51F300E0E358; + productRefGroup = 2301E96E205A51F300E0E358 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 2301E96C205A51F300E0E358 /* APNSUtil */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 2301E96B205A51F300E0E358 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 2301E968205A51F300E0E358 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2301E97B205A524B00E0E358 /* APNSInstance.swift in Sources */, + 2301E97D205A524B00E0E358 /* NSObject+Codable.swift in Sources */, + 2301E97C205A524B00E0E358 /* APNSManager.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + 2301E973205A51F300E0E358 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 2301E974205A51F300E0E358 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 2301E976205A51F300E0E358 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = ""; + CODE_SIGN_STYLE = Automatic; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + FRAMEWORK_SEARCH_PATHS = "${PROJECT_DIR}/Carthage/Build/iOS"; + INFOPLIST_FILE = APNSUtil/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + ONLY_ACTIVE_ARCH = YES; + OTHER_LDFLAGS = ""; + PRODUCT_BUNDLE_IDENTIFIER = pisces.lib.APNSUtil; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 2301E977205A51F300E0E358 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = ""; + CODE_SIGN_STYLE = Automatic; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + FRAMEWORK_SEARCH_PATHS = "${PROJECT_DIR}/Carthage/Build/iOS"; + INFOPLIST_FILE = APNSUtil/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + ONLY_ACTIVE_ARCH = YES; + OTHER_LDFLAGS = ""; + PRODUCT_BUNDLE_IDENTIFIER = pisces.lib.APNSUtil; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 2301E967205A51F300E0E358 /* Build configuration list for PBXProject "APNSUtil" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2301E973205A51F300E0E358 /* Debug */, + 2301E974205A51F300E0E358 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2301E975205A51F300E0E358 /* Build configuration list for PBXNativeTarget "APNSUtil" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2301E976205A51F300E0E358 /* Debug */, + 2301E977205A51F300E0E358 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 2301E964205A51F300E0E358 /* Project object */; +} diff --git a/APNSUtil.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/APNSUtil.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..c656a11 --- /dev/null +++ b/APNSUtil.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/APNSUtil.xcodeproj/xcshareddata/xcschemes/APNSUtil.xcscheme b/APNSUtil.xcodeproj/xcshareddata/xcschemes/APNSUtil.xcscheme new file mode 100644 index 0000000..521fe16 --- /dev/null +++ b/APNSUtil.xcodeproj/xcshareddata/xcschemes/APNSUtil.xcscheme @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/APNSUtil/APNSUtil.h b/APNSUtil/APNSUtil.h new file mode 100644 index 0000000..588d230 --- /dev/null +++ b/APNSUtil/APNSUtil.h @@ -0,0 +1,19 @@ +// +// APNSUtil.h +// APNSUtil +// +// Created by KWANG HYOUN KIM on 15/03/2018. +// Copyright © 2018 pisces. All rights reserved. +// + +#import + +//! Project version number for APNSUtil. +FOUNDATION_EXPORT double APNSUtilVersionNumber; + +//! Project version string for APNSUtil. +FOUNDATION_EXPORT const unsigned char APNSUtilVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import + + diff --git a/APNSUtil/Classes/APNSInstance.swift b/APNSUtil/Classes/APNSInstance.swift index 565d7d6..7da55c3 100644 --- a/APNSUtil/Classes/APNSInstance.swift +++ b/APNSUtil/Classes/APNSInstance.swift @@ -8,7 +8,7 @@ import Foundation -@objcMembers public class APNSInstance: NSObject { +@objc public class APNSInstance: NSObject { // MARK: - Constants @@ -36,14 +36,6 @@ import Foundation // MARK: - Public methods - private class func decodeInstance() -> APNSInstance { - guard let data = UserDefaults.standard.data(forKey: Const.keyForAPNSInstance), - let instance = NSKeyedUnarchiver.unarchiveObject(with: data) as? APNSInstance else { - return APNSInstance() - } - return instance - } - public func clear() { token = nil @@ -57,6 +49,16 @@ import Foundation UserDefaults.standard.set(NSKeyedArchiver.archivedData(withRootObject: self), forKey: Const.keyForAPNSInstance) UserDefaults.standard.synchronize() } + + // MARK: - Private methods + + private class func decodeInstance() -> APNSInstance { + guard let data = UserDefaults.standard.data(forKey: Const.keyForAPNSInstance), + let instance = NSKeyedUnarchiver.unarchiveObject(with: data) as? APNSInstance else { + return APNSInstance() + } + return instance + } } extension APNSInstance: NSCoding { diff --git a/APNSUtil/Classes/APNSManager.swift b/APNSUtil/Classes/APNSManager.swift index dc67d88..8d3d2ef 100644 --- a/APNSUtil/Classes/APNSManager.swift +++ b/APNSUtil/Classes/APNSManager.swift @@ -43,16 +43,16 @@ public class APNSManager { dequeue() return self } + public func didReceive(userInfo: [AnyHashable : Any], as: T.Type, isInactive: Bool) { + let map = Map(mappingType: .fromJSON, JSON: userInfo as! [String: Any]) + let model = T.init(map: map)! + enqueue(RemoteNotificationElement(isInactive: isInactive, model: model)).dequeue() + } public func processing(_ subscribable: Subscribable, _ closure: @escaping Processing) -> APNSManager { guard processingClosureMap[subscribable.hash] == nil else {return self} processingClosureMap[subscribable.hash] = closure return self } - public func received(_ mappable: T.Type, userInfo: [AnyHashable : Any], isInactive: Bool) { - let map = Map(mappingType: .fromJSON, JSON: userInfo as! [String: Any]) - let model = T.init(map: map)! - enqueue(RemoteNotificationElement(isInactive: isInactive, model: model)).dequeue() - } public func register() -> APNSManager { if #available(iOS 10.0, *) { let options: () -> UNAuthorizationOptions = { diff --git a/APNSUtil/Info.plist b/APNSUtil/Info.plist new file mode 100644 index 0000000..1007fd9 --- /dev/null +++ b/APNSUtil/Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + NSPrincipalClass + + + diff --git a/Cartfile b/Cartfile new file mode 100644 index 0000000..5183114 --- /dev/null +++ b/Cartfile @@ -0,0 +1 @@ +github "Hearst-DD/ObjectMapper" ~> 2.0 diff --git a/Cartfile.resolved b/Cartfile.resolved new file mode 100644 index 0000000..7bfd90e --- /dev/null +++ b/Cartfile.resolved @@ -0,0 +1 @@ +github "Hearst-DD/ObjectMapper" "2.2.9" diff --git a/Carthage/Checkouts/ObjectMapper/.github/ISSUE_TEMPLATE.md b/Carthage/Checkouts/ObjectMapper/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..5fd662f --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,43 @@ +### Your JSON dictionary: + +```json +{ + "name": "ObjectMapper", + "url": "https://github.com/Hearst-DD/ObjectMapper" +} +``` + +### Your model: + +```swift +struct Repo: Mappable { + var name: String! + var url: URL! + + init(_ map: Map) { + name <- map["name"] + url <- map["url"] + } +} +``` + +### What you did: + +```swift +let repo = Mapper().map(myJSONDictionary) +``` + +### What you expected: + +I exepected something like: + +```swift +Repo(name: "ObjectMapper", url: "https://github.com/Hearst-DD/ObjectMapper") +``` + +### What you got: + +```swift +Repo(name: "ObjectMapper", url: nil) // expected the url is mapped correctly +``` + diff --git a/Carthage/Checkouts/ObjectMapper/.gitignore b/Carthage/Checkouts/ObjectMapper/.gitignore new file mode 100644 index 0000000..44f1d2f --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/.gitignore @@ -0,0 +1,26 @@ +# Xcode +build/ +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata +*.xccheckout +*.moved-aside +DerivedData +*.xcuserstate +# AppCode etc. +.idea/ +# Desktop Servies +.DS_Store + +# Carthage +Carthage/Build + +# Swift package manager +.build/ +Packages/ diff --git a/Carthage/Checkouts/ObjectMapper/.swift-version b/Carthage/Checkouts/ObjectMapper/.swift-version new file mode 100644 index 0000000..a3ec5a4 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/.swift-version @@ -0,0 +1 @@ +3.2 diff --git a/Carthage/Checkouts/ObjectMapper/.travis.yml b/Carthage/Checkouts/ObjectMapper/.travis.yml new file mode 100644 index 0000000..012afe2 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/.travis.yml @@ -0,0 +1,51 @@ +language: objective-c +osx_image: xcode8.3 + +env: + global: + - LANG=en_US.UTF-8 + - LC_ALL=en_US.UTF-8 + - WORKSPACE="ObjectMapper.xcworkspace" + - IOS_FRAMEWORK_SCHEME="ObjectMapper-iOS" + - OSX_FRAMEWORK_SCHEME="ObjectMapper-Mac" + - TVOS_FRAMEWORK_SCHEME="ObjectMapper-tvOS" + - WATCHOS_FRAMEWORK_SCHEME="ObjectMapper-watchOS" + - IOS_SDK=iphonesimulator10.3 + - OSX_SDK=macosx10.12 + - TVOS_SDK=appletvsimulator10.2 + - WATCHOS_SDK=watchsimulator3.2 + matrix: + - DESTINATION="OS=10.3.1,name=iPhone 5s" SCHEME="$IOS_FRAMEWORK_SCHEME" SDK="$IOS_SDK" RUN_TESTS="YES" + - DESTINATION="OS=10.3.1,name=iPhone 6" SCHEME="$IOS_FRAMEWORK_SCHEME" SDK="$IOS_SDK" RUN_TESTS="YES" + - DESTINATION="OS=10.3.1,name=iPhone 6 Plus" SCHEME="$IOS_FRAMEWORK_SCHEME" SDK="$IOS_SDK" RUN_TESTS="YES" + - DESTINATION="OS=10.3.1,name=iPhone 6s" SCHEME="$IOS_FRAMEWORK_SCHEME" SDK="$IOS_SDK" RUN_TESTS="YES" + - DESTINATION="OS=10.3.1,name=iPhone 6s Plus" SCHEME="$IOS_FRAMEWORK_SCHEME" SDK="$IOS_SDK" RUN_TESTS="YES" + - DESTINATION="OS=10.3.1,name=iPhone 7" SCHEME="$IOS_FRAMEWORK_SCHEME" SDK="$IOS_SDK" RUN_TESTS="YES" + - DESTINATION="arch=x86_64" SCHEME="$OSX_FRAMEWORK_SCHEME" SDK="$OSX_SDK" RUN_TESTS="YES" + - DESTINATION="OS=10.2,name=Apple TV 1080p" SCHEME="$TVOS_FRAMEWORK_SCHEME" SDK="$TVOS_SDK" RUN_TESTS="YES" + - DESTINATION="OS=3.2,name=Apple Watch - 38mm" SCHEME="$WATCHOS_FRAMEWORK_SCHEME" SDK="$WATCHOS_SDK" RUN_TESTS="NO" + +before_install: + - gem install xcpretty --no-rdoc --no-ri --no-document --quiet + +script: + - set -o pipefail + - xcodebuild -version + - xcodebuild -showsdks + + # Build Framework in Debug and Run Tests if specified + - if [ $RUN_TESTS == "YES" ]; then + travis_retry xcodebuild -workspace "$WORKSPACE" -scheme "$SCHEME" -sdk "$SDK" -destination "$DESTINATION" -configuration Debug ONLY_ACTIVE_ARCH=NO test | xcpretty -c; + else + travis_retry xcodebuild -workspace "$WORKSPACE" -scheme "$SCHEME" -sdk "$SDK" -destination "$DESTINATION" -configuration Debug ONLY_ACTIVE_ARCH=NO build | xcpretty -c; + fi + + # Build Framework in Release and Run Tests if specified + - if [ $RUN_TESTS == "YES" ]; then + travis_retry xcodebuild -workspace "$WORKSPACE" -scheme "$SCHEME" -sdk "$SDK" -destination "$DESTINATION" -configuration Release ONLY_ACTIVE_ARCH=NO test | xcpretty -c; + else + travis_retry xcodebuild -workspace "$WORKSPACE" -scheme "$SCHEME" -sdk "$SDK" -destination "$DESTINATION" -configuration Release ONLY_ACTIVE_ARCH=NO build | xcpretty -c; + fi + +notifications: + email: false diff --git a/Carthage/Checkouts/ObjectMapper/LICENSE b/Carthage/Checkouts/ObjectMapper/LICENSE new file mode 100644 index 0000000..be48bc6 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/LICENSE @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2014 Hearst + +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/Carthage/Checkouts/ObjectMapper/ObjectMapper.podspec b/Carthage/Checkouts/ObjectMapper/ObjectMapper.podspec new file mode 100644 index 0000000..c8c08d2 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/ObjectMapper.podspec @@ -0,0 +1,22 @@ +Pod::Spec.new do |s| + s.name = 'ObjectMapper' + s.version = '2.2.9' + s.license = 'MIT' + s.summary = 'JSON Object mapping written in Swift' + s.homepage = 'https://github.com/Hearst-DD/ObjectMapper' + s.authors = { 'Tristan Himmelman' => 'tristanhimmelman@gmail.com' } + s.source = { :git => 'https://github.com/Hearst-DD/ObjectMapper.git', :tag => s.version.to_s } + + s.watchos.deployment_target = '2.0' + s.ios.deployment_target = '8.0' + s.osx.deployment_target = '10.9' + s.tvos.deployment_target = '9.0' + + + s.pod_target_xcconfig = { + 'SWIFT_VERSION' => '3.2', + } + + s.requires_arc = true + s.source_files = 'Sources/**/*.swift' +end diff --git a/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcodeproj/project.pbxproj b/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcodeproj/project.pbxproj new file mode 100644 index 0000000..77889d5 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcodeproj/project.pbxproj @@ -0,0 +1,1459 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 030114A91D95187600FBFD4F /* ImmutableMappable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 030114A81D95187600FBFD4F /* ImmutableMappable.swift */; }; + 030114AC1D951A4F00FBFD4F /* ImmutableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 030114AA1D95197100FBFD4F /* ImmutableTests.swift */; }; + 030114AD1D951A5300FBFD4F /* ImmutableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 030114AA1D95197100FBFD4F /* ImmutableTests.swift */; }; + 030114AE1D951A5600FBFD4F /* ImmutableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 030114AA1D95197100FBFD4F /* ImmutableTests.swift */; }; + 030114AF1D951A6C00FBFD4F /* ImmutableMappable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 030114A81D95187600FBFD4F /* ImmutableMappable.swift */; }; + 030114B01D951A7100FBFD4F /* ImmutableMappable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 030114A81D95187600FBFD4F /* ImmutableMappable.swift */; }; + 030114B11D951A7500FBFD4F /* ImmutableMappable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 030114A81D95187600FBFD4F /* ImmutableMappable.swift */; }; + 030E75F51E588BF30027D94A /* IntegerOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 038F0A021E55FE2400613148 /* IntegerOperators.swift */; }; + 030E75F61E588BF80027D94A /* IntegerOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 038F0A021E55FE2400613148 /* IntegerOperators.swift */; }; + 030E75F71E588BFC0027D94A /* IntegerOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 038F0A021E55FE2400613148 /* IntegerOperators.swift */; }; + 038F0A031E55FE2400613148 /* IntegerOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 038F0A021E55FE2400613148 /* IntegerOperators.swift */; }; + 1865416F1E972FA800F95A19 /* URLTransformTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1865416E1E972FA800F95A19 /* URLTransformTests.swift */; }; + 37AFD9B91AAD191C00AB59B5 /* CustomDateFormatTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37AFD9B81AAD191C00AB59B5 /* CustomDateFormatTransform.swift */; }; + 3BAD2C0C1BDDB10D00E6B203 /* Mappable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BAD2C0B1BDDB10D00E6B203 /* Mappable.swift */; }; + 3BAD2C0D1BDDB10D00E6B203 /* Mappable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BAD2C0B1BDDB10D00E6B203 /* Mappable.swift */; }; + 3BAD2C0E1BDDB10D00E6B203 /* Mappable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BAD2C0B1BDDB10D00E6B203 /* Mappable.swift */; }; + 3BAD2C101BDDC0B000E6B203 /* MappableExtensionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BAD2C0F1BDDC0B000E6B203 /* MappableExtensionsTests.swift */; }; + 3BAD2C111BDDC0B000E6B203 /* MappableExtensionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BAD2C0F1BDDC0B000E6B203 /* MappableExtensionsTests.swift */; }; + 6100B1C01BD76A030011114A /* NestedArrayTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6100B1BF1BD76A020011114A /* NestedArrayTests.swift */; }; + 6A05B7B01BE274BE00F19B53 /* ObjectMapper.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6A05B7A61BE274BE00F19B53 /* ObjectMapper.framework */; }; + 6A05B7BD1BE274E800F19B53 /* ObjectMapper.h in Headers */ = {isa = PBXBuildFile; fileRef = 6AAC8F7B19F03C2900E7A677 /* ObjectMapper.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6A0BF1FF1C0B53470083D1AF /* ToObjectTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A0BF1FE1C0B53470083D1AF /* ToObjectTests.swift */; }; + 6A0BF2001C0B53470083D1AF /* ToObjectTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A0BF1FE1C0B53470083D1AF /* ToObjectTests.swift */; }; + 6A0BF2011C0B53470083D1AF /* ToObjectTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A0BF1FE1C0B53470083D1AF /* ToObjectTests.swift */; }; + 6A2AD0451B2C786C0097E150 /* Mapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FC419F048FE00E7A677 /* Mapper.swift */; }; + 6A2AD0461B2C786C0097E150 /* Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FC519F048FE00E7A677 /* Operators.swift */; }; + 6A2AD0471B2C786C0097E150 /* FromJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FC319F048FE00E7A677 /* FromJSON.swift */; }; + 6A2AD0481B2C786C0097E150 /* ToJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FC719F048FE00E7A677 /* ToJSON.swift */; }; + 6A2AD0491B2C786C0097E150 /* DateTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FCB19F048FE00E7A677 /* DateTransform.swift */; }; + 6A2AD04A1B2C786C0097E150 /* DateFormatterTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A51372B1AADDE2700B82516 /* DateFormatterTransform.swift */; }; + 6A2AD04B1B2C786C0097E150 /* ISO8601DateTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = D86BDEA31A51E5AC00120819 /* ISO8601DateTransform.swift */; }; + 6A2AD04C1B2C786C0097E150 /* CustomDateFormatTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37AFD9B81AAD191C00AB59B5 /* CustomDateFormatTransform.swift */; }; + 6A2AD04D1B2C786C0097E150 /* TransformOf.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD71C8C01A7218AD009D4161 /* TransformOf.swift */; }; + 6A2AD04E1B2C786C0097E150 /* TransformType.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD50B6FC1A82518300744312 /* TransformType.swift */; }; + 6A2AD04F1B2C786C0097E150 /* URLTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A6C54CF19FE8DB600239454 /* URLTransform.swift */; }; + 6A2AD0501B2C786C0097E150 /* EnumTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC1E7F361ABC44C000F9B1CF /* EnumTransform.swift */; }; + 6A3774341A31427F00CC0AB5 /* BasicTypesTestsToJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A3774331A31427F00CC0AB5 /* BasicTypesTestsToJSON.swift */; }; + 6A412A171BAC770C001C3F67 /* ClassClusterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A412A161BAC770C001C3F67 /* ClassClusterTests.swift */; }; + 6A412A181BAC830B001C3F67 /* ClassClusterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A412A161BAC770C001C3F67 /* ClassClusterTests.swift */; }; + 6A412A241BB0DA26001C3F67 /* PerformanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A412A231BB0DA26001C3F67 /* PerformanceTests.swift */; }; + 6A412A251BB0DA26001C3F67 /* PerformanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A412A231BB0DA26001C3F67 /* PerformanceTests.swift */; }; + 6A442CA11CE251F100AB4F1F /* MapContextTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A442CA01CE251F100AB4F1F /* MapContextTests.swift */; }; + 6A442CA21CE251F100AB4F1F /* MapContextTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A442CA01CE251F100AB4F1F /* MapContextTests.swift */; }; + 6A442CA31CE251F100AB4F1F /* MapContextTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A442CA01CE251F100AB4F1F /* MapContextTests.swift */; }; + 6A51372C1AADDE2700B82516 /* DateFormatterTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A51372B1AADDE2700B82516 /* DateFormatterTransform.swift */; }; + 6A51372F1AADE12C00B82516 /* CustomTransformTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A51372E1AADE12C00B82516 /* CustomTransformTests.swift */; }; + 6A6AEB961A93874F002573D3 /* BasicTypesTestsFromJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A6AEB951A93874F002573D3 /* BasicTypesTestsFromJSON.swift */; }; + 6A6AEB981A9387D0002573D3 /* BasicTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A6AEB971A9387D0002573D3 /* BasicTypes.swift */; }; + 6A6C54D019FE8DB600239454 /* URLTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A6C54CF19FE8DB600239454 /* URLTransform.swift */; }; + 6A715C4A1D05B1FA0054AD62 /* IgnoreNilTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A715C491D05B1FA0054AD62 /* IgnoreNilTests.swift */; }; + 6A715C4B1D05B1FA0054AD62 /* IgnoreNilTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A715C491D05B1FA0054AD62 /* IgnoreNilTests.swift */; }; + 6A715C4C1D05B1FA0054AD62 /* IgnoreNilTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A715C491D05B1FA0054AD62 /* IgnoreNilTests.swift */; }; + 6AA1F66B1BE94687006EF513 /* ClassClusterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A412A161BAC770C001C3F67 /* ClassClusterTests.swift */; }; + 6AA1F66C1BE94687006EF513 /* PerformanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A412A231BB0DA26001C3F67 /* PerformanceTests.swift */; }; + 6AA1F66D1BE9468D006EF513 /* NestedArrayTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6100B1BF1BD76A020011114A /* NestedArrayTests.swift */; }; + 6AA1F66E1BE991FF006EF513 /* Mappable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BAD2C0B1BDDB10D00E6B203 /* Mappable.swift */; }; + 6AA1F66F1BE9921C006EF513 /* MappableExtensionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BAD2C0F1BDDC0B000E6B203 /* MappableExtensionsTests.swift */; }; + 6AAC8F7C19F03C2900E7A677 /* ObjectMapper.h in Headers */ = {isa = PBXBuildFile; fileRef = 6AAC8F7B19F03C2900E7A677 /* ObjectMapper.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6AAC8F8619F03C2900E7A677 /* ObjectMapperTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8F8519F03C2900E7A677 /* ObjectMapperTests.swift */; }; + 6AAC8FCD19F048FE00E7A677 /* FromJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FC319F048FE00E7A677 /* FromJSON.swift */; }; + 6AAC8FCE19F048FE00E7A677 /* Mapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FC419F048FE00E7A677 /* Mapper.swift */; }; + 6AAC8FCF19F048FE00E7A677 /* Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FC519F048FE00E7A677 /* Operators.swift */; }; + 6AAC8FD119F048FE00E7A677 /* ToJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FC719F048FE00E7A677 /* ToJSON.swift */; }; + 6AAC8FD319F048FE00E7A677 /* DateTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FCB19F048FE00E7A677 /* DateTransform.swift */; }; + 6AAE6A431ACED93500FBC899 /* ObjectMapper.framework in CopyFiles */ = {isa = PBXBuildFile; fileRef = CD1602FF1AC023D5000CD69A /* ObjectMapper.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + 6AC458191BA350CF00054758 /* ObjectMapper.h in Headers */ = {isa = PBXBuildFile; fileRef = 6AAC8F7B19F03C2900E7A677 /* ObjectMapper.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6AC692341BE3FD3A004C119A /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6ACB15D11BC7F1D0006C029C /* Map.swift */; }; + 6AC692351BE3FD3A004C119A /* Mapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FC419F048FE00E7A677 /* Mapper.swift */; }; + 6AC692361BE3FD3A004C119A /* Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FC519F048FE00E7A677 /* Operators.swift */; }; + 6AC692371BE3FD3A004C119A /* FromJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FC319F048FE00E7A677 /* FromJSON.swift */; }; + 6AC692381BE3FD3A004C119A /* ToJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FC719F048FE00E7A677 /* ToJSON.swift */; }; + 6AC692391BE3FD3A004C119A /* DateTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FCB19F048FE00E7A677 /* DateTransform.swift */; }; + 6AC6923A1BE3FD3A004C119A /* DateFormatterTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A51372B1AADDE2700B82516 /* DateFormatterTransform.swift */; }; + 6AC6923B1BE3FD3A004C119A /* ISO8601DateTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = D86BDEA31A51E5AC00120819 /* ISO8601DateTransform.swift */; }; + 6AC6923C1BE3FD3A004C119A /* CustomDateFormatTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37AFD9B81AAD191C00AB59B5 /* CustomDateFormatTransform.swift */; }; + 6AC6923D1BE3FD3A004C119A /* TransformOf.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD71C8C01A7218AD009D4161 /* TransformOf.swift */; }; + 6AC6923E1BE3FD3A004C119A /* TransformType.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD50B6FC1A82518300744312 /* TransformType.swift */; }; + 6AC6923F1BE3FD3A004C119A /* URLTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A6C54CF19FE8DB600239454 /* URLTransform.swift */; }; + 6AC692401BE3FD3A004C119A /* EnumTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC1E7F361ABC44C000F9B1CF /* EnumTransform.swift */; }; + 6AC692411BE3FD45004C119A /* BasicTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A6AEB971A9387D0002573D3 /* BasicTypes.swift */; }; + 6AC692421BE3FD45004C119A /* BasicTypesTestsFromJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A6AEB951A93874F002573D3 /* BasicTypesTestsFromJSON.swift */; }; + 6AC692431BE3FD45004C119A /* BasicTypesTestsToJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A3774331A31427F00CC0AB5 /* BasicTypesTestsToJSON.swift */; }; + 6AC692441BE3FD45004C119A /* CustomTransformTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A51372E1AADE12C00B82516 /* CustomTransformTests.swift */; }; + 6AC692451BE3FD45004C119A /* NestedKeysTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD44374C1AAE9C1100A271BA /* NestedKeysTests.swift */; }; + 6AC692461BE3FD45004C119A /* NestedArrayTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6100B1BF1BD76A020011114A /* NestedArrayTests.swift */; }; + 6AC692471BE3FD45004C119A /* ObjectMapperTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8F8519F03C2900E7A677 /* ObjectMapperTests.swift */; }; + 6ACB15D21BC7F1D0006C029C /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6ACB15D11BC7F1D0006C029C /* Map.swift */; }; + 6ACB15D31BC7F1D0006C029C /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6ACB15D11BC7F1D0006C029C /* Map.swift */; }; + 6ACB15D41BC7F1D0006C029C /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6ACB15D11BC7F1D0006C029C /* Map.swift */; }; + 6AECC9E61D79E29100222E7A /* DictionaryTransformTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AECC9E51D79E29100222E7A /* DictionaryTransformTests.swift */; }; + 6AECC9E71D79E29100222E7A /* DictionaryTransformTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AECC9E51D79E29100222E7A /* DictionaryTransformTests.swift */; }; + 6AECC9E81D79E29100222E7A /* DictionaryTransformTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AECC9E51D79E29100222E7A /* DictionaryTransformTests.swift */; }; + 6AF148841D999E31002BEA2C /* GenericObjectsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AF148831D999E31002BEA2C /* GenericObjectsTests.swift */; }; + 6AF148851D999E31002BEA2C /* GenericObjectsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AF148831D999E31002BEA2C /* GenericObjectsTests.swift */; }; + 6AF148861D999E31002BEA2C /* GenericObjectsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AF148831D999E31002BEA2C /* GenericObjectsTests.swift */; }; + 6AF148881D99A25B002BEA2C /* MapError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AF148871D99A25B002BEA2C /* MapError.swift */; }; + 6AF148891D99A25B002BEA2C /* MapError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AF148871D99A25B002BEA2C /* MapError.swift */; }; + 6AF1488A1D99A25B002BEA2C /* MapError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AF148871D99A25B002BEA2C /* MapError.swift */; }; + 6AF1488B1D99A25B002BEA2C /* MapError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AF148871D99A25B002BEA2C /* MapError.swift */; }; + 6AF1488D1D99A7A6002BEA2C /* TransformOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AF1488C1D99A7A6002BEA2C /* TransformOperators.swift */; }; + 6AF1488E1D99A7A6002BEA2C /* TransformOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AF1488C1D99A7A6002BEA2C /* TransformOperators.swift */; }; + 6AF1488F1D99A7A6002BEA2C /* TransformOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AF1488C1D99A7A6002BEA2C /* TransformOperators.swift */; }; + 6AF148901D99A7A6002BEA2C /* TransformOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AF1488C1D99A7A6002BEA2C /* TransformOperators.swift */; }; + 6AF148921D99A7CA002BEA2C /* EnumOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AF148911D99A7CA002BEA2C /* EnumOperators.swift */; }; + 6AF148931D99A7CA002BEA2C /* EnumOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AF148911D99A7CA002BEA2C /* EnumOperators.swift */; }; + 6AF148941D99A7CA002BEA2C /* EnumOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AF148911D99A7CA002BEA2C /* EnumOperators.swift */; }; + 6AF148951D99A7CA002BEA2C /* EnumOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AF148911D99A7CA002BEA2C /* EnumOperators.swift */; }; + 797FEDCE1DAB855F00E31F75 /* HexColorTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79E591C61DAB7FED008E2EEF /* HexColorTransform.swift */; }; + 797FEDCF1DAB855F00E31F75 /* HexColorTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79E591C61DAB7FED008E2EEF /* HexColorTransform.swift */; }; + 797FEDD01DAB856000E31F75 /* HexColorTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79E591C61DAB7FED008E2EEF /* HexColorTransform.swift */; }; + 79E591C71DAB7FED008E2EEF /* HexColorTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79E591C61DAB7FED008E2EEF /* HexColorTransform.swift */; }; + 84D4F8521CC3B643008B0FB6 /* NSDecimalNumberTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84D4F8511CC3B643008B0FB6 /* NSDecimalNumberTransform.swift */; }; + 84D4F8531CC3B643008B0FB6 /* NSDecimalNumberTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84D4F8511CC3B643008B0FB6 /* NSDecimalNumberTransform.swift */; }; + 84D4F8541CC3B643008B0FB6 /* NSDecimalNumberTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84D4F8511CC3B643008B0FB6 /* NSDecimalNumberTransform.swift */; }; + 84D4F8551CC3B643008B0FB6 /* NSDecimalNumberTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84D4F8511CC3B643008B0FB6 /* NSDecimalNumberTransform.swift */; }; + 84D4F8571CC3B71B008B0FB6 /* NSDecimalNumberTransformTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84D4F8561CC3B71B008B0FB6 /* NSDecimalNumberTransformTests.swift */; }; + 84D4F8581CC3B71B008B0FB6 /* NSDecimalNumberTransformTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84D4F8561CC3B71B008B0FB6 /* NSDecimalNumberTransformTests.swift */; }; + 84D4F8591CC3B71B008B0FB6 /* NSDecimalNumberTransformTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84D4F8561CC3B71B008B0FB6 /* NSDecimalNumberTransformTests.swift */; }; + 891804CD1C122AF000E5C3EE /* MappableTypesWithTransformsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 891804CC1C122AF000E5C3EE /* MappableTypesWithTransformsTests.swift */; }; + 891804CE1C122AF000E5C3EE /* MappableTypesWithTransformsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 891804CC1C122AF000E5C3EE /* MappableTypesWithTransformsTests.swift */; }; + 891804CF1C122AF000E5C3EE /* MappableTypesWithTransformsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 891804CC1C122AF000E5C3EE /* MappableTypesWithTransformsTests.swift */; }; + 997B4A471D3FA20D005E3F31 /* DictionaryTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 997B4A461D3FA20D005E3F31 /* DictionaryTransform.swift */; }; + 997B4A481D3FA20D005E3F31 /* DictionaryTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 997B4A461D3FA20D005E3F31 /* DictionaryTransform.swift */; }; + 997B4A491D3FA20D005E3F31 /* DictionaryTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 997B4A461D3FA20D005E3F31 /* DictionaryTransform.swift */; }; + 997B4A4A1D3FA20D005E3F31 /* DictionaryTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 997B4A461D3FA20D005E3F31 /* DictionaryTransform.swift */; }; + BC1E7F371ABC44C000F9B1CF /* EnumTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC1E7F361ABC44C000F9B1CF /* EnumTransform.swift */; }; + C135CAB41D762F6900BA9338 /* DataTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = C135CAB31D762F6900BA9338 /* DataTransform.swift */; }; + C135CAB71D76303E00BA9338 /* DataTransformTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C135CAB61D76303E00BA9338 /* DataTransformTests.swift */; }; + C135CAB81D76303E00BA9338 /* DataTransformTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C135CAB61D76303E00BA9338 /* DataTransformTests.swift */; }; + C135CAB91D76303E00BA9338 /* DataTransformTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C135CAB61D76303E00BA9338 /* DataTransformTests.swift */; }; + C135CABA1D7631DB00BA9338 /* DataTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = C135CAB31D762F6900BA9338 /* DataTransform.swift */; }; + C135CABB1D7631DB00BA9338 /* DataTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = C135CAB31D762F6900BA9338 /* DataTransform.swift */; }; + C135CABC1D7631DC00BA9338 /* DataTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = C135CAB31D762F6900BA9338 /* DataTransform.swift */; }; + CD16030A1AC023D6000CD69A /* ObjectMapper.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CD1602FF1AC023D5000CD69A /* ObjectMapper.framework */; }; + CD1603181AC02437000CD69A /* ObjectMapper.h in Headers */ = {isa = PBXBuildFile; fileRef = 6AAC8F7B19F03C2900E7A677 /* ObjectMapper.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CD1603191AC02451000CD69A /* Mapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FC419F048FE00E7A677 /* Mapper.swift */; }; + CD16031A1AC02451000CD69A /* Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FC519F048FE00E7A677 /* Operators.swift */; }; + CD16031B1AC02451000CD69A /* FromJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FC319F048FE00E7A677 /* FromJSON.swift */; }; + CD16031C1AC02451000CD69A /* ToJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FC719F048FE00E7A677 /* ToJSON.swift */; }; + CD16031D1AC02461000CD69A /* DateTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8FCB19F048FE00E7A677 /* DateTransform.swift */; }; + CD16031E1AC02461000CD69A /* DateFormatterTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A51372B1AADDE2700B82516 /* DateFormatterTransform.swift */; }; + CD16031F1AC02461000CD69A /* ISO8601DateTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = D86BDEA31A51E5AC00120819 /* ISO8601DateTransform.swift */; }; + CD1603201AC02461000CD69A /* CustomDateFormatTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37AFD9B81AAD191C00AB59B5 /* CustomDateFormatTransform.swift */; }; + CD1603211AC02472000CD69A /* TransformOf.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD71C8C01A7218AD009D4161 /* TransformOf.swift */; }; + CD1603221AC02472000CD69A /* TransformType.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD50B6FC1A82518300744312 /* TransformType.swift */; }; + CD1603231AC02472000CD69A /* URLTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A6C54CF19FE8DB600239454 /* URLTransform.swift */; }; + CD1603241AC02472000CD69A /* EnumTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC1E7F361ABC44C000F9B1CF /* EnumTransform.swift */; }; + CD1603251AC02480000CD69A /* BasicTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A6AEB971A9387D0002573D3 /* BasicTypes.swift */; }; + CD1603261AC02480000CD69A /* BasicTypesTestsFromJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A6AEB951A93874F002573D3 /* BasicTypesTestsFromJSON.swift */; }; + CD1603271AC02480000CD69A /* BasicTypesTestsToJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A3774331A31427F00CC0AB5 /* BasicTypesTestsToJSON.swift */; }; + CD1603281AC02480000CD69A /* CustomTransformTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A51372E1AADE12C00B82516 /* CustomTransformTests.swift */; }; + CD1603291AC02480000CD69A /* NestedKeysTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD44374C1AAE9C1100A271BA /* NestedKeysTests.swift */; }; + CD16032A1AC02480000CD69A /* ObjectMapperTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AAC8F8519F03C2900E7A677 /* ObjectMapperTests.swift */; }; + CD4437491AAD692B00A271BA /* ObjectMapper.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6AAC8F7619F03C2900E7A677 /* ObjectMapper.framework */; }; + CD44374B1AAD698400A271BA /* ObjectMapper.framework in Copy Frameworks */ = {isa = PBXBuildFile; fileRef = 6AAC8F7619F03C2900E7A677 /* ObjectMapper.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + CD44374D1AAE9C1100A271BA /* NestedKeysTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD44374C1AAE9C1100A271BA /* NestedKeysTests.swift */; }; + CD50B6FD1A82518300744312 /* TransformType.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD50B6FC1A82518300744312 /* TransformType.swift */; }; + CD71C8C11A7218AD009D4161 /* TransformOf.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD71C8C01A7218AD009D4161 /* TransformOf.swift */; }; + D86BDEA41A51E5AD00120819 /* ISO8601DateTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = D86BDEA31A51E5AC00120819 /* ISO8601DateTransform.swift */; }; + DC99C8CC1CA261A8005C788C /* NullableKeysFromJSONTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC99C8CB1CA261A8005C788C /* NullableKeysFromJSONTests.swift */; }; + DC99C8CD1CA261AD005C788C /* NullableKeysFromJSONTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC99C8CB1CA261A8005C788C /* NullableKeysFromJSONTests.swift */; }; + DC99C8CE1CA261AE005C788C /* NullableKeysFromJSONTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC99C8CB1CA261A8005C788C /* NullableKeysFromJSONTests.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 6A05B7B11BE274BE00F19B53 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 6AAC8F6D19F03C2900E7A677 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 6A05B7A51BE274BE00F19B53; + remoteInfo = "ObjectMapper-tvOS"; + }; + 6AAC8FD519F04A5600E7A677 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 6AAC8F6D19F03C2900E7A677 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 6AAC8F7519F03C2900E7A677; + remoteInfo = ObjectMapper; + }; + CD16030B1AC023D6000CD69A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 6AAC8F6D19F03C2900E7A677 /* Project object */; + proxyType = 1; + remoteGlobalIDString = CD1602FE1AC023D5000CD69A; + remoteInfo = "ObjectMapper-Mac"; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 6AAE6A421ACED92700FBC899 /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + 6AAE6A431ACED93500FBC899 /* ObjectMapper.framework in CopyFiles */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CD44374A1AAD696B00A271BA /* Copy Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + CD44374B1AAD698400A271BA /* ObjectMapper.framework in Copy Frameworks */, + ); + name = "Copy Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 030114A81D95187600FBFD4F /* ImmutableMappable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ImmutableMappable.swift; sourceTree = ""; }; + 030114AA1D95197100FBFD4F /* ImmutableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ImmutableTests.swift; path = ObjectMapperTests/ImmutableTests.swift; sourceTree = ""; }; + 038F0A021E55FE2400613148 /* IntegerOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IntegerOperators.swift; sourceTree = ""; }; + 1865416E1E972FA800F95A19 /* URLTransformTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = URLTransformTests.swift; path = ObjectMapperTests/URLTransformTests.swift; sourceTree = ""; }; + 37AFD9B81AAD191C00AB59B5 /* CustomDateFormatTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CustomDateFormatTransform.swift; sourceTree = ""; }; + 3BAD2C0B1BDDB10D00E6B203 /* Mappable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = Mappable.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 3BAD2C0F1BDDC0B000E6B203 /* MappableExtensionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MappableExtensionsTests.swift; path = ObjectMapperTests/MappableExtensionsTests.swift; sourceTree = ""; }; + 6100B1BF1BD76A020011114A /* NestedArrayTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = NestedArrayTests.swift; path = ObjectMapperTests/NestedArrayTests.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 6A05B7A61BE274BE00F19B53 /* ObjectMapper.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = ObjectMapper.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 6A05B7AF1BE274BE00F19B53 /* ObjectMapper-tvOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "ObjectMapper-tvOSTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + 6A0BF1FE1C0B53470083D1AF /* ToObjectTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ToObjectTests.swift; path = ObjectMapperTests/ToObjectTests.swift; sourceTree = ""; }; + 6A2AD03D1B2C78540097E150 /* ObjectMapper.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = ObjectMapper.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 6A3774331A31427F00CC0AB5 /* BasicTypesTestsToJSON.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = BasicTypesTestsToJSON.swift; path = ObjectMapperTests/BasicTypesTestsToJSON.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 6A412A161BAC770C001C3F67 /* ClassClusterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ClassClusterTests.swift; path = ObjectMapperTests/ClassClusterTests.swift; sourceTree = ""; }; + 6A412A231BB0DA26001C3F67 /* PerformanceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = PerformanceTests.swift; path = ObjectMapperTests/PerformanceTests.swift; sourceTree = ""; }; + 6A442CA01CE251F100AB4F1F /* MapContextTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = MapContextTests.swift; path = ObjectMapperTests/MapContextTests.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 6A51372B1AADDE2700B82516 /* DateFormatterTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateFormatterTransform.swift; sourceTree = ""; }; + 6A51372E1AADE12C00B82516 /* CustomTransformTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = CustomTransformTests.swift; path = ObjectMapperTests/CustomTransformTests.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 6A6AEB951A93874F002573D3 /* BasicTypesTestsFromJSON.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = BasicTypesTestsFromJSON.swift; path = ObjectMapperTests/BasicTypesTestsFromJSON.swift; sourceTree = ""; }; + 6A6AEB971A9387D0002573D3 /* BasicTypes.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = BasicTypes.swift; path = ObjectMapperTests/BasicTypes.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 6A6C54CF19FE8DB600239454 /* URLTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URLTransform.swift; sourceTree = ""; }; + 6A715C491D05B1FA0054AD62 /* IgnoreNilTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = IgnoreNilTests.swift; path = ObjectMapperTests/IgnoreNilTests.swift; sourceTree = ""; }; + 6A9EEBD41AC5BFA30011F22C /* README.md */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = net.daringfireball.markdown; lineEnding = 0; path = README.md; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.markdown; }; + 6AAC8F7619F03C2900E7A677 /* ObjectMapper.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = ObjectMapper.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 6AAC8F7A19F03C2900E7A677 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 6AAC8F7B19F03C2900E7A677 /* ObjectMapper.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ObjectMapper.h; sourceTree = ""; }; + 6AAC8F8119F03C2900E7A677 /* ObjectMapper-iOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "ObjectMapper-iOSTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + 6AAC8F8419F03C2900E7A677 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 6AAC8F8519F03C2900E7A677 /* ObjectMapperTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = ObjectMapperTests.swift; path = ObjectMapperTests/ObjectMapperTests.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 6AAC8FC319F048FE00E7A677 /* FromJSON.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = FromJSON.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 6AAC8FC419F048FE00E7A677 /* Mapper.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = Mapper.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 6AAC8FC519F048FE00E7A677 /* Operators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = Operators.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 6AAC8FC719F048FE00E7A677 /* ToJSON.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = ToJSON.swift; sourceTree = ""; }; + 6AAC8FCB19F048FE00E7A677 /* DateTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateTransform.swift; sourceTree = ""; }; + 6ACB15D11BC7F1D0006C029C /* Map.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = ""; }; + 6AECC9E51D79E29100222E7A /* DictionaryTransformTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = DictionaryTransformTests.swift; path = ObjectMapperTests/DictionaryTransformTests.swift; sourceTree = ""; }; + 6AF148831D999E31002BEA2C /* GenericObjectsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = GenericObjectsTests.swift; path = ObjectMapperTests/GenericObjectsTests.swift; sourceTree = ""; }; + 6AF148871D99A25B002BEA2C /* MapError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MapError.swift; sourceTree = ""; }; + 6AF1488C1D99A7A6002BEA2C /* TransformOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = TransformOperators.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 6AF148911D99A7CA002BEA2C /* EnumOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = EnumOperators.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 79E591C61DAB7FED008E2EEF /* HexColorTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HexColorTransform.swift; sourceTree = ""; }; + 84D4F8511CC3B643008B0FB6 /* NSDecimalNumberTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDecimalNumberTransform.swift; sourceTree = ""; }; + 84D4F8561CC3B71B008B0FB6 /* NSDecimalNumberTransformTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = NSDecimalNumberTransformTests.swift; path = ObjectMapperTests/NSDecimalNumberTransformTests.swift; sourceTree = ""; }; + 891804CC1C122AF000E5C3EE /* MappableTypesWithTransformsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MappableTypesWithTransformsTests.swift; path = ObjectMapperTests/MappableTypesWithTransformsTests.swift; sourceTree = ""; }; + 997B4A461D3FA20D005E3F31 /* DictionaryTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DictionaryTransform.swift; sourceTree = ""; }; + BC1E7F361ABC44C000F9B1CF /* EnumTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumTransform.swift; sourceTree = ""; }; + C135CAB31D762F6900BA9338 /* DataTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataTransform.swift; sourceTree = ""; }; + C135CAB61D76303E00BA9338 /* DataTransformTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = DataTransformTests.swift; path = ObjectMapperTests/DataTransformTests.swift; sourceTree = ""; }; + CD1602FF1AC023D5000CD69A /* ObjectMapper.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = ObjectMapper.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + CD1603091AC023D6000CD69A /* ObjectMapper-MacTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "ObjectMapper-MacTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + CD44374C1AAE9C1100A271BA /* NestedKeysTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = NestedKeysTests.swift; path = ObjectMapperTests/NestedKeysTests.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + CD50B6FC1A82518300744312 /* TransformType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransformType.swift; sourceTree = ""; }; + CD71C8C01A7218AD009D4161 /* TransformOf.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = TransformOf.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + D86BDEA31A51E5AC00120819 /* ISO8601DateTransform.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ISO8601DateTransform.swift; sourceTree = ""; }; + DC99C8CB1CA261A8005C788C /* NullableKeysFromJSONTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = NullableKeysFromJSONTests.swift; path = ObjectMapperTests/NullableKeysFromJSONTests.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 6A05B7A21BE274BE00F19B53 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6A05B7AC1BE274BE00F19B53 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 6A05B7B01BE274BE00F19B53 /* ObjectMapper.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6A2AD0391B2C78540097E150 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6AAC8F7219F03C2900E7A677 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6AAC8F7E19F03C2900E7A677 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + CD4437491AAD692B00A271BA /* ObjectMapper.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CD1602FB1AC023D5000CD69A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CD1603061AC023D6000CD69A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + CD16030A1AC023D6000CD69A /* ObjectMapper.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 6A51372D1AADDEE400B82516 /* Date */ = { + isa = PBXGroup; + children = ( + 6AAC8FCB19F048FE00E7A677 /* DateTransform.swift */, + 6A51372B1AADDE2700B82516 /* DateFormatterTransform.swift */, + D86BDEA31A51E5AC00120819 /* ISO8601DateTransform.swift */, + 37AFD9B81AAD191C00AB59B5 /* CustomDateFormatTransform.swift */, + ); + name = Date; + sourceTree = ""; + }; + 6AAC8F6C19F03C2900E7A677 = { + isa = PBXGroup; + children = ( + 6A9EEBD41AC5BFA30011F22C /* README.md */, + 6AAC8F7819F03C2900E7A677 /* ObjectMapper */, + 6AAC8F8219F03C2900E7A677 /* ObjectMapperTests */, + ); + sourceTree = ""; + usesTabs = 1; + }; + 6AAC8F7719F03C2900E7A677 /* Products */ = { + isa = PBXGroup; + children = ( + 6AAC8F7619F03C2900E7A677 /* ObjectMapper.framework */, + 6AAC8F8119F03C2900E7A677 /* ObjectMapper-iOSTests.xctest */, + CD1602FF1AC023D5000CD69A /* ObjectMapper.framework */, + CD1603091AC023D6000CD69A /* ObjectMapper-MacTests.xctest */, + 6A2AD03D1B2C78540097E150 /* ObjectMapper.framework */, + 6A05B7A61BE274BE00F19B53 /* ObjectMapper.framework */, + 6A05B7AF1BE274BE00F19B53 /* ObjectMapper-tvOSTests.xctest */, + ); + name = Products; + path = ..; + sourceTree = ""; + }; + 6AAC8F7819F03C2900E7A677 /* ObjectMapper */ = { + isa = PBXGroup; + children = ( + 6AAC8F7B19F03C2900E7A677 /* ObjectMapper.h */, + 6AAC8FC219F048FE00E7A677 /* Core */, + 6AAC8FCA19F048FE00E7A677 /* Transforms */, + 6AAC8F7919F03C2900E7A677 /* Supporting Files */, + ); + name = ObjectMapper; + path = Sources; + sourceTree = ""; + }; + 6AAC8F7919F03C2900E7A677 /* Supporting Files */ = { + isa = PBXGroup; + children = ( + 6AAC8F7A19F03C2900E7A677 /* Info.plist */, + ); + name = "Supporting Files"; + sourceTree = ""; + }; + 6AAC8F8219F03C2900E7A677 /* ObjectMapperTests */ = { + isa = PBXGroup; + children = ( + 6A6AEB971A9387D0002573D3 /* BasicTypes.swift */, + 6A3774331A31427F00CC0AB5 /* BasicTypesTestsToJSON.swift */, + 6A6AEB951A93874F002573D3 /* BasicTypesTestsFromJSON.swift */, + 6A412A161BAC770C001C3F67 /* ClassClusterTests.swift */, + 6A51372E1AADE12C00B82516 /* CustomTransformTests.swift */, + C135CAB61D76303E00BA9338 /* DataTransformTests.swift */, + 6AECC9E51D79E29100222E7A /* DictionaryTransformTests.swift */, + 6AF148831D999E31002BEA2C /* GenericObjectsTests.swift */, + 6A715C491D05B1FA0054AD62 /* IgnoreNilTests.swift */, + 030114AA1D95197100FBFD4F /* ImmutableTests.swift */, + 6A442CA01CE251F100AB4F1F /* MapContextTests.swift */, + 3BAD2C0F1BDDC0B000E6B203 /* MappableExtensionsTests.swift */, + 891804CC1C122AF000E5C3EE /* MappableTypesWithTransformsTests.swift */, + 6100B1BF1BD76A020011114A /* NestedArrayTests.swift */, + CD44374C1AAE9C1100A271BA /* NestedKeysTests.swift */, + 84D4F8561CC3B71B008B0FB6 /* NSDecimalNumberTransformTests.swift */, + DC99C8CB1CA261A8005C788C /* NullableKeysFromJSONTests.swift */, + 6AAC8F8519F03C2900E7A677 /* ObjectMapperTests.swift */, + 6A412A231BB0DA26001C3F67 /* PerformanceTests.swift */, + 6A0BF1FE1C0B53470083D1AF /* ToObjectTests.swift */, + 1865416E1E972FA800F95A19 /* URLTransformTests.swift */, + 6AAC8F7719F03C2900E7A677 /* Products */, + 6AAC8F8319F03C2900E7A677 /* Supporting Files */, + ); + name = ObjectMapperTests; + path = Tests; + sourceTree = ""; + }; + 6AAC8F8319F03C2900E7A677 /* Supporting Files */ = { + isa = PBXGroup; + children = ( + 6AAC8F8419F03C2900E7A677 /* Info.plist */, + ); + name = "Supporting Files"; + sourceTree = ""; + }; + 6AAC8FC219F048FE00E7A677 /* Core */ = { + isa = PBXGroup; + children = ( + 6ACB15D11BC7F1D0006C029C /* Map.swift */, + 6AF148871D99A25B002BEA2C /* MapError.swift */, + 3BAD2C0B1BDDB10D00E6B203 /* Mappable.swift */, + 030114A81D95187600FBFD4F /* ImmutableMappable.swift */, + 6AAC8FC419F048FE00E7A677 /* Mapper.swift */, + 6AF148961D99A912002BEA2C /* Operators */, + 6AAC8FC319F048FE00E7A677 /* FromJSON.swift */, + 6AAC8FC719F048FE00E7A677 /* ToJSON.swift */, + ); + name = Core; + sourceTree = ""; + }; + 6AAC8FCA19F048FE00E7A677 /* Transforms */ = { + isa = PBXGroup; + children = ( + 6A51372D1AADDEE400B82516 /* Date */, + CD71C8C01A7218AD009D4161 /* TransformOf.swift */, + CD50B6FC1A82518300744312 /* TransformType.swift */, + 6A6C54CF19FE8DB600239454 /* URLTransform.swift */, + BC1E7F361ABC44C000F9B1CF /* EnumTransform.swift */, + 84D4F8511CC3B643008B0FB6 /* NSDecimalNumberTransform.swift */, + 997B4A461D3FA20D005E3F31 /* DictionaryTransform.swift */, + C135CAB31D762F6900BA9338 /* DataTransform.swift */, + 79E591C61DAB7FED008E2EEF /* HexColorTransform.swift */, + ); + name = Transforms; + sourceTree = ""; + }; + 6AF148961D99A912002BEA2C /* Operators */ = { + isa = PBXGroup; + children = ( + 6AAC8FC519F048FE00E7A677 /* Operators.swift */, + 6AF148911D99A7CA002BEA2C /* EnumOperators.swift */, + 6AF1488C1D99A7A6002BEA2C /* TransformOperators.swift */, + 038F0A021E55FE2400613148 /* IntegerOperators.swift */, + ); + name = Operators; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 6A05B7A31BE274BE00F19B53 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 6A05B7BD1BE274E800F19B53 /* ObjectMapper.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6A2AD03A1B2C78540097E150 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 6AC458191BA350CF00054758 /* ObjectMapper.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6AAC8F7319F03C2900E7A677 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 6AAC8F7C19F03C2900E7A677 /* ObjectMapper.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CD1602FC1AC023D5000CD69A /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + CD1603181AC02437000CD69A /* ObjectMapper.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 6A05B7A51BE274BE00F19B53 /* ObjectMapper-tvOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6A05B7BB1BE274BE00F19B53 /* Build configuration list for PBXNativeTarget "ObjectMapper-tvOS" */; + buildPhases = ( + 6A05B7A11BE274BE00F19B53 /* Sources */, + 6A05B7A21BE274BE00F19B53 /* Frameworks */, + 6A05B7A31BE274BE00F19B53 /* Headers */, + 6A05B7A41BE274BE00F19B53 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "ObjectMapper-tvOS"; + productName = "ObjectMapper-tvOS"; + productReference = 6A05B7A61BE274BE00F19B53 /* ObjectMapper.framework */; + productType = "com.apple.product-type.framework"; + }; + 6A05B7AE1BE274BE00F19B53 /* ObjectMapper-tvOSTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6A05B7BC1BE274BE00F19B53 /* Build configuration list for PBXNativeTarget "ObjectMapper-tvOSTests" */; + buildPhases = ( + 6A05B7AB1BE274BE00F19B53 /* Sources */, + 6A05B7AC1BE274BE00F19B53 /* Frameworks */, + 6A05B7AD1BE274BE00F19B53 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 6A05B7B21BE274BE00F19B53 /* PBXTargetDependency */, + ); + name = "ObjectMapper-tvOSTests"; + productName = "ObjectMapper-tvOSTests"; + productReference = 6A05B7AF1BE274BE00F19B53 /* ObjectMapper-tvOSTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 6A2AD03C1B2C78540097E150 /* ObjectMapper-watchOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6A2AD0441B2C78540097E150 /* Build configuration list for PBXNativeTarget "ObjectMapper-watchOS" */; + buildPhases = ( + 6A2AD0381B2C78540097E150 /* Sources */, + 6A2AD0391B2C78540097E150 /* Frameworks */, + 6A2AD03A1B2C78540097E150 /* Headers */, + 6A2AD03B1B2C78540097E150 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "ObjectMapper-watchOS"; + productName = "ObjectMapper-watchOS"; + productReference = 6A2AD03D1B2C78540097E150 /* ObjectMapper.framework */; + productType = "com.apple.product-type.framework"; + }; + 6AAC8F7519F03C2900E7A677 /* ObjectMapper-iOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6AAC8F8919F03C2900E7A677 /* Build configuration list for PBXNativeTarget "ObjectMapper-iOS" */; + buildPhases = ( + 6AAC8F7119F03C2900E7A677 /* Sources */, + 6AAC8F7219F03C2900E7A677 /* Frameworks */, + 6AAC8F7319F03C2900E7A677 /* Headers */, + 6AAC8F7419F03C2900E7A677 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "ObjectMapper-iOS"; + productName = ObjectMapper; + productReference = 6AAC8F7619F03C2900E7A677 /* ObjectMapper.framework */; + productType = "com.apple.product-type.framework"; + }; + 6AAC8F8019F03C2900E7A677 /* ObjectMapper-iOSTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6AAC8F8C19F03C2900E7A677 /* Build configuration list for PBXNativeTarget "ObjectMapper-iOSTests" */; + buildPhases = ( + 6AAC8F7D19F03C2900E7A677 /* Sources */, + 6AAC8F7E19F03C2900E7A677 /* Frameworks */, + 6AAC8F7F19F03C2900E7A677 /* Resources */, + CD44374A1AAD696B00A271BA /* Copy Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 6AAC8FD619F04A5600E7A677 /* PBXTargetDependency */, + ); + name = "ObjectMapper-iOSTests"; + productName = ObjectMapperTests; + productReference = 6AAC8F8119F03C2900E7A677 /* ObjectMapper-iOSTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + CD1602FE1AC023D5000CD69A /* ObjectMapper-Mac */ = { + isa = PBXNativeTarget; + buildConfigurationList = CD1603161AC023D6000CD69A /* Build configuration list for PBXNativeTarget "ObjectMapper-Mac" */; + buildPhases = ( + CD1602FA1AC023D5000CD69A /* Sources */, + CD1602FB1AC023D5000CD69A /* Frameworks */, + CD1602FC1AC023D5000CD69A /* Headers */, + CD1602FD1AC023D5000CD69A /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "ObjectMapper-Mac"; + productName = "ObjectMapper-Mac"; + productReference = CD1602FF1AC023D5000CD69A /* ObjectMapper.framework */; + productType = "com.apple.product-type.framework"; + }; + CD1603081AC023D6000CD69A /* ObjectMapper-MacTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = CD1603171AC023D6000CD69A /* Build configuration list for PBXNativeTarget "ObjectMapper-MacTests" */; + buildPhases = ( + CD1603051AC023D6000CD69A /* Sources */, + CD1603061AC023D6000CD69A /* Frameworks */, + CD1603071AC023D6000CD69A /* Resources */, + 6AAE6A421ACED92700FBC899 /* CopyFiles */, + ); + buildRules = ( + ); + dependencies = ( + CD16030C1AC023D6000CD69A /* PBXTargetDependency */, + ); + name = "ObjectMapper-MacTests"; + productName = "ObjectMapper-MacTests"; + productReference = CD1603091AC023D6000CD69A /* ObjectMapper-MacTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 6AAC8F6D19F03C2900E7A677 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0710; + LastUpgradeCheck = 0800; + ORGANIZATIONNAME = hearst; + TargetAttributes = { + 6A05B7A51BE274BE00F19B53 = { + CreatedOnToolsVersion = 7.1; + LastSwiftMigration = 0800; + }; + 6A05B7AE1BE274BE00F19B53 = { + CreatedOnToolsVersion = 7.1; + LastSwiftMigration = 0800; + ProvisioningStyle = Manual; + }; + 6A2AD03C1B2C78540097E150 = { + CreatedOnToolsVersion = 7.0; + }; + 6AAC8F7519F03C2900E7A677 = { + CreatedOnToolsVersion = 6.0.1; + LastSwiftMigration = 0800; + }; + 6AAC8F8019F03C2900E7A677 = { + CreatedOnToolsVersion = 6.0.1; + LastSwiftMigration = 0800; + }; + CD1602FE1AC023D5000CD69A = { + CreatedOnToolsVersion = 6.2; + }; + CD1603081AC023D6000CD69A = { + CreatedOnToolsVersion = 6.2; + }; + }; + }; + buildConfigurationList = 6AAC8F7019F03C2900E7A677 /* Build configuration list for PBXProject "ObjectMapper" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 6AAC8F6C19F03C2900E7A677; + productRefGroup = 6AAC8F7719F03C2900E7A677 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 6AAC8F7519F03C2900E7A677 /* ObjectMapper-iOS */, + CD1602FE1AC023D5000CD69A /* ObjectMapper-Mac */, + 6A2AD03C1B2C78540097E150 /* ObjectMapper-watchOS */, + 6A05B7A51BE274BE00F19B53 /* ObjectMapper-tvOS */, + 6AAC8F8019F03C2900E7A677 /* ObjectMapper-iOSTests */, + CD1603081AC023D6000CD69A /* ObjectMapper-MacTests */, + 6A05B7AE1BE274BE00F19B53 /* ObjectMapper-tvOSTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 6A05B7A41BE274BE00F19B53 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6A05B7AD1BE274BE00F19B53 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6A2AD03B1B2C78540097E150 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6AAC8F7419F03C2900E7A677 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6AAC8F7F19F03C2900E7A677 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CD1602FD1AC023D5000CD69A /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CD1603071AC023D6000CD69A /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 6A05B7A11BE274BE00F19B53 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 030E75F71E588BFC0027D94A /* IntegerOperators.swift in Sources */, + 6AA1F66E1BE991FF006EF513 /* Mappable.swift in Sources */, + 6AC692341BE3FD3A004C119A /* Map.swift in Sources */, + 6AF148901D99A7A6002BEA2C /* TransformOperators.swift in Sources */, + 6AC692351BE3FD3A004C119A /* Mapper.swift in Sources */, + 6AC692361BE3FD3A004C119A /* Operators.swift in Sources */, + 84D4F8551CC3B643008B0FB6 /* NSDecimalNumberTransform.swift in Sources */, + 6AC692371BE3FD3A004C119A /* FromJSON.swift in Sources */, + 6AF148951D99A7CA002BEA2C /* EnumOperators.swift in Sources */, + 997B4A4A1D3FA20D005E3F31 /* DictionaryTransform.swift in Sources */, + 6AC692381BE3FD3A004C119A /* ToJSON.swift in Sources */, + 6AC692391BE3FD3A004C119A /* DateTransform.swift in Sources */, + 6AC6923A1BE3FD3A004C119A /* DateFormatterTransform.swift in Sources */, + 6AC6923B1BE3FD3A004C119A /* ISO8601DateTransform.swift in Sources */, + 6AC6923C1BE3FD3A004C119A /* CustomDateFormatTransform.swift in Sources */, + 6AC6923D1BE3FD3A004C119A /* TransformOf.swift in Sources */, + 6AC6923E1BE3FD3A004C119A /* TransformType.swift in Sources */, + 6AC6923F1BE3FD3A004C119A /* URLTransform.swift in Sources */, + 6AC692401BE3FD3A004C119A /* EnumTransform.swift in Sources */, + 797FEDD01DAB856000E31F75 /* HexColorTransform.swift in Sources */, + 6AF1488B1D99A25B002BEA2C /* MapError.swift in Sources */, + C135CABC1D7631DC00BA9338 /* DataTransform.swift in Sources */, + 030114B11D951A7500FBFD4F /* ImmutableMappable.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6A05B7AB1BE274BE00F19B53 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6AA1F66F1BE9921C006EF513 /* MappableExtensionsTests.swift in Sources */, + 891804CF1C122AF000E5C3EE /* MappableTypesWithTransformsTests.swift in Sources */, + 6AF148861D999E31002BEA2C /* GenericObjectsTests.swift in Sources */, + C135CAB91D76303E00BA9338 /* DataTransformTests.swift in Sources */, + 6A442CA31CE251F100AB4F1F /* MapContextTests.swift in Sources */, + 6AA1F66B1BE94687006EF513 /* ClassClusterTests.swift in Sources */, + 6AECC9E81D79E29100222E7A /* DictionaryTransformTests.swift in Sources */, + 6AA1F66C1BE94687006EF513 /* PerformanceTests.swift in Sources */, + 6AC692411BE3FD45004C119A /* BasicTypes.swift in Sources */, + 6A0BF2011C0B53470083D1AF /* ToObjectTests.swift in Sources */, + 84D4F8591CC3B71B008B0FB6 /* NSDecimalNumberTransformTests.swift in Sources */, + 6AC692421BE3FD45004C119A /* BasicTypesTestsFromJSON.swift in Sources */, + 6A715C4C1D05B1FA0054AD62 /* IgnoreNilTests.swift in Sources */, + 6AC692431BE3FD45004C119A /* BasicTypesTestsToJSON.swift in Sources */, + 6AC692441BE3FD45004C119A /* CustomTransformTests.swift in Sources */, + 6AC692451BE3FD45004C119A /* NestedKeysTests.swift in Sources */, + 6AC692461BE3FD45004C119A /* NestedArrayTests.swift in Sources */, + DC99C8CE1CA261AE005C788C /* NullableKeysFromJSONTests.swift in Sources */, + 6AC692471BE3FD45004C119A /* ObjectMapperTests.swift in Sources */, + 030114AE1D951A5600FBFD4F /* ImmutableTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6A2AD0381B2C78540097E150 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 030E75F61E588BF80027D94A /* IntegerOperators.swift in Sources */, + 6A2AD0451B2C786C0097E150 /* Mapper.swift in Sources */, + 3BAD2C0E1BDDB10D00E6B203 /* Mappable.swift in Sources */, + 6AF1488F1D99A7A6002BEA2C /* TransformOperators.swift in Sources */, + 6A2AD0461B2C786C0097E150 /* Operators.swift in Sources */, + 6ACB15D41BC7F1D0006C029C /* Map.swift in Sources */, + 84D4F8541CC3B643008B0FB6 /* NSDecimalNumberTransform.swift in Sources */, + 6A2AD0471B2C786C0097E150 /* FromJSON.swift in Sources */, + 6AF148941D99A7CA002BEA2C /* EnumOperators.swift in Sources */, + 997B4A491D3FA20D005E3F31 /* DictionaryTransform.swift in Sources */, + 6A2AD0481B2C786C0097E150 /* ToJSON.swift in Sources */, + 6A2AD0491B2C786C0097E150 /* DateTransform.swift in Sources */, + 6A2AD04A1B2C786C0097E150 /* DateFormatterTransform.swift in Sources */, + 6A2AD04B1B2C786C0097E150 /* ISO8601DateTransform.swift in Sources */, + 6A2AD04C1B2C786C0097E150 /* CustomDateFormatTransform.swift in Sources */, + 6A2AD04D1B2C786C0097E150 /* TransformOf.swift in Sources */, + 6A2AD04E1B2C786C0097E150 /* TransformType.swift in Sources */, + 6A2AD04F1B2C786C0097E150 /* URLTransform.swift in Sources */, + 6A2AD0501B2C786C0097E150 /* EnumTransform.swift in Sources */, + 797FEDCF1DAB855F00E31F75 /* HexColorTransform.swift in Sources */, + 6AF1488A1D99A25B002BEA2C /* MapError.swift in Sources */, + C135CABB1D7631DB00BA9338 /* DataTransform.swift in Sources */, + 030114B01D951A7100FBFD4F /* ImmutableMappable.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6AAC8F7119F03C2900E7A677 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 37AFD9B91AAD191C00AB59B5 /* CustomDateFormatTransform.swift in Sources */, + 3BAD2C0C1BDDB10D00E6B203 /* Mappable.swift in Sources */, + 6AF1488D1D99A7A6002BEA2C /* TransformOperators.swift in Sources */, + CD50B6FD1A82518300744312 /* TransformType.swift in Sources */, + 6ACB15D21BC7F1D0006C029C /* Map.swift in Sources */, + 84D4F8521CC3B643008B0FB6 /* NSDecimalNumberTransform.swift in Sources */, + 6AAC8FD319F048FE00E7A677 /* DateTransform.swift in Sources */, + 6AF148921D99A7CA002BEA2C /* EnumOperators.swift in Sources */, + 997B4A471D3FA20D005E3F31 /* DictionaryTransform.swift in Sources */, + BC1E7F371ABC44C000F9B1CF /* EnumTransform.swift in Sources */, + D86BDEA41A51E5AD00120819 /* ISO8601DateTransform.swift in Sources */, + CD71C8C11A7218AD009D4161 /* TransformOf.swift in Sources */, + 030114A91D95187600FBFD4F /* ImmutableMappable.swift in Sources */, + 6A6C54D019FE8DB600239454 /* URLTransform.swift in Sources */, + 038F0A031E55FE2400613148 /* IntegerOperators.swift in Sources */, + 6A51372C1AADDE2700B82516 /* DateFormatterTransform.swift in Sources */, + 6AAC8FCE19F048FE00E7A677 /* Mapper.swift in Sources */, + 6AAC8FCD19F048FE00E7A677 /* FromJSON.swift in Sources */, + 6AAC8FD119F048FE00E7A677 /* ToJSON.swift in Sources */, + 79E591C71DAB7FED008E2EEF /* HexColorTransform.swift in Sources */, + 6AF148881D99A25B002BEA2C /* MapError.swift in Sources */, + C135CAB41D762F6900BA9338 /* DataTransform.swift in Sources */, + 6AAC8FCF19F048FE00E7A677 /* Operators.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6AAC8F7D19F03C2900E7A677 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 3BAD2C101BDDC0B000E6B203 /* MappableExtensionsTests.swift in Sources */, + 891804CD1C122AF000E5C3EE /* MappableTypesWithTransformsTests.swift in Sources */, + 6AF148841D999E31002BEA2C /* GenericObjectsTests.swift in Sources */, + C135CAB71D76303E00BA9338 /* DataTransformTests.swift in Sources */, + 6A442CA11CE251F100AB4F1F /* MapContextTests.swift in Sources */, + 6A6AEB961A93874F002573D3 /* BasicTypesTestsFromJSON.swift in Sources */, + 1865416F1E972FA800F95A19 /* URLTransformTests.swift in Sources */, + 6AECC9E61D79E29100222E7A /* DictionaryTransformTests.swift in Sources */, + 6A0BF1FF1C0B53470083D1AF /* ToObjectTests.swift in Sources */, + CD44374D1AAE9C1100A271BA /* NestedKeysTests.swift in Sources */, + 6A3774341A31427F00CC0AB5 /* BasicTypesTestsToJSON.swift in Sources */, + 84D4F8571CC3B71B008B0FB6 /* NSDecimalNumberTransformTests.swift in Sources */, + 6A412A171BAC770C001C3F67 /* ClassClusterTests.swift in Sources */, + 6A715C4A1D05B1FA0054AD62 /* IgnoreNilTests.swift in Sources */, + 6A51372F1AADE12C00B82516 /* CustomTransformTests.swift in Sources */, + 6A6AEB981A9387D0002573D3 /* BasicTypes.swift in Sources */, + 6A412A241BB0DA26001C3F67 /* PerformanceTests.swift in Sources */, + 6AAC8F8619F03C2900E7A677 /* ObjectMapperTests.swift in Sources */, + DC99C8CC1CA261A8005C788C /* NullableKeysFromJSONTests.swift in Sources */, + 6100B1C01BD76A030011114A /* NestedArrayTests.swift in Sources */, + 030114AC1D951A4F00FBFD4F /* ImmutableTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CD1602FA1AC023D5000CD69A /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 030E75F51E588BF30027D94A /* IntegerOperators.swift in Sources */, + CD1603221AC02472000CD69A /* TransformType.swift in Sources */, + 3BAD2C0D1BDDB10D00E6B203 /* Mappable.swift in Sources */, + 6AF1488E1D99A7A6002BEA2C /* TransformOperators.swift in Sources */, + 030114AF1D951A6C00FBFD4F /* ImmutableMappable.swift in Sources */, + CD1603201AC02461000CD69A /* CustomDateFormatTransform.swift in Sources */, + CD16031E1AC02461000CD69A /* DateFormatterTransform.swift in Sources */, + 84D4F8531CC3B643008B0FB6 /* NSDecimalNumberTransform.swift in Sources */, + 6AF148931D99A7CA002BEA2C /* EnumOperators.swift in Sources */, + 6ACB15D31BC7F1D0006C029C /* Map.swift in Sources */, + 997B4A481D3FA20D005E3F31 /* DictionaryTransform.swift in Sources */, + CD1603241AC02472000CD69A /* EnumTransform.swift in Sources */, + CD16031F1AC02461000CD69A /* ISO8601DateTransform.swift in Sources */, + CD1603211AC02472000CD69A /* TransformOf.swift in Sources */, + CD1603231AC02472000CD69A /* URLTransform.swift in Sources */, + CD16031C1AC02451000CD69A /* ToJSON.swift in Sources */, + CD16031D1AC02461000CD69A /* DateTransform.swift in Sources */, + CD1603191AC02451000CD69A /* Mapper.swift in Sources */, + CD16031A1AC02451000CD69A /* Operators.swift in Sources */, + 797FEDCE1DAB855F00E31F75 /* HexColorTransform.swift in Sources */, + 6AF148891D99A25B002BEA2C /* MapError.swift in Sources */, + CD16031B1AC02451000CD69A /* FromJSON.swift in Sources */, + C135CABA1D7631DB00BA9338 /* DataTransform.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CD1603051AC023D6000CD69A /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 3BAD2C111BDDC0B000E6B203 /* MappableExtensionsTests.swift in Sources */, + 891804CE1C122AF000E5C3EE /* MappableTypesWithTransformsTests.swift in Sources */, + 6AF148851D999E31002BEA2C /* GenericObjectsTests.swift in Sources */, + C135CAB81D76303E00BA9338 /* DataTransformTests.swift in Sources */, + 6A442CA21CE251F100AB4F1F /* MapContextTests.swift in Sources */, + 6AA1F66D1BE9468D006EF513 /* NestedArrayTests.swift in Sources */, + 6AECC9E71D79E29100222E7A /* DictionaryTransformTests.swift in Sources */, + 6A412A181BAC830B001C3F67 /* ClassClusterTests.swift in Sources */, + CD1603261AC02480000CD69A /* BasicTypesTestsFromJSON.swift in Sources */, + 6A0BF2001C0B53470083D1AF /* ToObjectTests.swift in Sources */, + 84D4F8581CC3B71B008B0FB6 /* NSDecimalNumberTransformTests.swift in Sources */, + CD1603291AC02480000CD69A /* NestedKeysTests.swift in Sources */, + 6A715C4B1D05B1FA0054AD62 /* IgnoreNilTests.swift in Sources */, + CD1603251AC02480000CD69A /* BasicTypes.swift in Sources */, + CD16032A1AC02480000CD69A /* ObjectMapperTests.swift in Sources */, + CD1603271AC02480000CD69A /* BasicTypesTestsToJSON.swift in Sources */, + 6A412A251BB0DA26001C3F67 /* PerformanceTests.swift in Sources */, + DC99C8CD1CA261AD005C788C /* NullableKeysFromJSONTests.swift in Sources */, + CD1603281AC02480000CD69A /* CustomTransformTests.swift in Sources */, + 030114AD1D951A5300FBFD4F /* ImmutableTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 6A05B7B21BE274BE00F19B53 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 6A05B7A51BE274BE00F19B53 /* ObjectMapper-tvOS */; + targetProxy = 6A05B7B11BE274BE00F19B53 /* PBXContainerItemProxy */; + }; + 6AAC8FD619F04A5600E7A677 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 6AAC8F7519F03C2900E7A677 /* ObjectMapper-iOS */; + targetProxy = 6AAC8FD519F04A5600E7A677 /* PBXContainerItemProxy */; + }; + CD16030C1AC023D6000CD69A /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = CD1602FE1AC023D5000CD69A /* ObjectMapper-Mac */; + targetProxy = CD16030B1AC023D6000CD69A /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 6A05B7B71BE274BE00F19B53 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + BITCODE_GENERATION_MODE = marker; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_BITCODE = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = Sources/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.hearst.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = "$(PROJECT_NAME)"; + SDKROOT = appletvos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.1; + TARGETED_DEVICE_FAMILY = 3; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Debug; + }; + 6A05B7B81BE274BE00F19B53 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + BITCODE_GENERATION_MODE = bitcode; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_BITCODE = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = Sources/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.hearst.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = "$(PROJECT_NAME)"; + SDKROOT = appletvos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.1; + TARGETED_DEVICE_FAMILY = 3; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Release; + }; + 6A05B7B91BE274BE00F19B53 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + DEBUG_INFORMATION_FORMAT = dwarf; + DEVELOPMENT_TEAM = ""; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = Tests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.hearst.ObjectMapper-tvOSTests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = appletvos; + SWIFT_VERSION = 3.1; + TVOS_DEPLOYMENT_TARGET = 9.0; + }; + name = Debug; + }; + 6A05B7BA1BE274BE00F19B53 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEVELOPMENT_TEAM = ""; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = Tests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.hearst.ObjectMapper-tvOSTests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = appletvos; + SWIFT_VERSION = 3.1; + TVOS_DEPLOYMENT_TARGET = 9.0; + }; + name = Release; + }; + 6A2AD0421B2C78540097E150 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + BITCODE_GENERATION_MODE = marker; + CODE_SIGN_IDENTITY = ""; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_BITCODE = YES; + ENABLE_TESTABILITY = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = Sources/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.hearst.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = "$(PROJECT_NAME)"; + SDKROOT = watchos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.1; + TARGETED_DEVICE_FAMILY = 4; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Debug; + }; + 6A2AD0431B2C78540097E150 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + BITCODE_GENERATION_MODE = bitcode; + CODE_SIGN_IDENTITY = ""; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_BITCODE = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = Sources/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.hearst.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = "$(PROJECT_NAME)"; + SDKROOT = watchos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.1; + TARGETED_DEVICE_FAMILY = 4; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Release; + }; + 6AAC8F8719F03C2900E7A677 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MACOSX_DEPLOYMENT_TARGET = 10.9; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 6AAC8F8819F03C2900E7A677 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = YES; + CURRENT_PROJECT_VERSION = 1; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MACOSX_DEPLOYMENT_TARGET = 10.9; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 3.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 6AAC8F8A19F03C2900E7A677 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + BITCODE_GENERATION_MODE = marker; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = Sources/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.hearst.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = "$(PROJECT_NAME)"; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.1; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Debug; + }; + 6AAC8F8B19F03C2900E7A677 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + BITCODE_GENERATION_MODE = bitcode; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = Sources/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.hearst.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = "$(PROJECT_NAME)"; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.1; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Release; + }; + 6AAC8F8D19F03C2900E7A677 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + FRAMEWORK_SEARCH_PATHS = "$(inherited)"; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + INFOPLIST_FILE = Tests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.heart.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.1; + }; + name = Debug; + }; + 6AAC8F8E19F03C2900E7A677 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + FRAMEWORK_SEARCH_PATHS = "$(inherited)"; + INFOPLIST_FILE = Tests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.heart.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.1; + }; + name = Release; + }; + CD1603121AC023D6000CD69A /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + BITCODE_GENERATION_MODE = marker; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "Mac Developer"; + COMBINE_HIDPI_IMAGES = YES; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + FRAMEWORK_VERSION = A; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + INFOPLIST_FILE = Sources/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.hearst.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = "$(PROJECT_NAME)"; + SDKROOT = macosx; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.1; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Debug; + }; + CD1603131AC023D6000CD69A /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + BITCODE_GENERATION_MODE = bitcode; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "3rd Party Mac Developer Application"; + COMBINE_HIDPI_IMAGES = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + FRAMEWORK_VERSION = A; + INFOPLIST_FILE = Sources/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "com.hearst.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = "$(PROJECT_NAME)"; + SDKROOT = macosx; + SKIP_INSTALL = YES; + SWIFT_VERSION = 3.1; + TVOS_DEPLOYMENT_TARGET = 9.0; + WATCHOS_DEPLOYMENT_TARGET = 2.0; + }; + name = Release; + }; + CD1603141AC023D6000CD69A /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + COMBINE_HIDPI_IMAGES = YES; + FRAMEWORK_SEARCH_PATHS = "$(inherited)"; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + INFOPLIST_FILE = Tests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.10; + PRODUCT_BUNDLE_IDENTIFIER = "com.heart.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = macosx; + SWIFT_VERSION = 3.1; + }; + name = Debug; + }; + CD1603151AC023D6000CD69A /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + COMBINE_HIDPI_IMAGES = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + FRAMEWORK_SEARCH_PATHS = "$(inherited)"; + INFOPLIST_FILE = Tests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; + MACOSX_DEPLOYMENT_TARGET = 10.10; + PRODUCT_BUNDLE_IDENTIFIER = "com.heart.$(PRODUCT_NAME:rfc1034identifier)"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = macosx; + SWIFT_VERSION = 3.1; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 6A05B7BB1BE274BE00F19B53 /* Build configuration list for PBXNativeTarget "ObjectMapper-tvOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6A05B7B71BE274BE00F19B53 /* Debug */, + 6A05B7B81BE274BE00F19B53 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6A05B7BC1BE274BE00F19B53 /* Build configuration list for PBXNativeTarget "ObjectMapper-tvOSTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6A05B7B91BE274BE00F19B53 /* Debug */, + 6A05B7BA1BE274BE00F19B53 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6A2AD0441B2C78540097E150 /* Build configuration list for PBXNativeTarget "ObjectMapper-watchOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6A2AD0421B2C78540097E150 /* Debug */, + 6A2AD0431B2C78540097E150 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6AAC8F7019F03C2900E7A677 /* Build configuration list for PBXProject "ObjectMapper" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6AAC8F8719F03C2900E7A677 /* Debug */, + 6AAC8F8819F03C2900E7A677 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6AAC8F8919F03C2900E7A677 /* Build configuration list for PBXNativeTarget "ObjectMapper-iOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6AAC8F8A19F03C2900E7A677 /* Debug */, + 6AAC8F8B19F03C2900E7A677 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6AAC8F8C19F03C2900E7A677 /* Build configuration list for PBXNativeTarget "ObjectMapper-iOSTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 6AAC8F8D19F03C2900E7A677 /* Debug */, + 6AAC8F8E19F03C2900E7A677 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + CD1603161AC023D6000CD69A /* Build configuration list for PBXNativeTarget "ObjectMapper-Mac" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + CD1603121AC023D6000CD69A /* Debug */, + CD1603131AC023D6000CD69A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + CD1603171AC023D6000CD69A /* Build configuration list for PBXNativeTarget "ObjectMapper-MacTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + CD1603141AC023D6000CD69A /* Debug */, + CD1603151AC023D6000CD69A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 6AAC8F6D19F03C2900E7A677 /* Project object */; +} diff --git a/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..d72f68d --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcodeproj/xcshareddata/xcschemes/ObjectMapper-Mac.xcscheme b/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcodeproj/xcshareddata/xcschemes/ObjectMapper-Mac.xcscheme new file mode 100644 index 0000000..c736780 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcodeproj/xcshareddata/xcschemes/ObjectMapper-Mac.xcscheme @@ -0,0 +1,113 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcodeproj/xcshareddata/xcschemes/ObjectMapper-iOS.xcscheme b/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcodeproj/xcshareddata/xcschemes/ObjectMapper-iOS.xcscheme new file mode 100644 index 0000000..0969343 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcodeproj/xcshareddata/xcschemes/ObjectMapper-iOS.xcscheme @@ -0,0 +1,113 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcodeproj/xcshareddata/xcschemes/ObjectMapper-tvOS.xcscheme b/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcodeproj/xcshareddata/xcschemes/ObjectMapper-tvOS.xcscheme new file mode 100644 index 0000000..fd2823e --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcodeproj/xcshareddata/xcschemes/ObjectMapper-tvOS.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcodeproj/xcshareddata/xcschemes/ObjectMapper-watchOS.xcscheme b/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcodeproj/xcshareddata/xcschemes/ObjectMapper-watchOS.xcscheme new file mode 100644 index 0000000..3f3dc61 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcodeproj/xcshareddata/xcschemes/ObjectMapper-watchOS.xcscheme @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcworkspace/contents.xcworkspacedata b/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..2ff4779 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/ObjectMapper.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Carthage/Checkouts/ObjectMapper/Package.swift b/Carthage/Checkouts/ObjectMapper/Package.swift new file mode 100644 index 0000000..25cce1f --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Package.swift @@ -0,0 +1,5 @@ +import PackageDescription + +let package = Package( + name: "ObjectMapper" +) diff --git a/Example/Pods/ObjectMapper/README-CN.md b/Carthage/Checkouts/ObjectMapper/README-CN.md similarity index 100% rename from Example/Pods/ObjectMapper/README-CN.md rename to Carthage/Checkouts/ObjectMapper/README-CN.md diff --git a/Carthage/Checkouts/ObjectMapper/README.md b/Carthage/Checkouts/ObjectMapper/README.md new file mode 100644 index 0000000..68a48ec --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/README.md @@ -0,0 +1,498 @@ +ObjectMapper +============ +[![CocoaPods](https://img.shields.io/cocoapods/v/ObjectMapper.svg)](https://github.com/Hearst-DD/ObjectMapper) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Swift Package Manager](https://rawgit.com/jlyonsmith/artwork/master/SwiftPackageManager/swiftpackagemanager-compatible.svg)](https://swift.org/package-manager/) +[![Build Status](https://travis-ci.org/Hearst-DD/ObjectMapper.svg?branch=master)](https://travis-ci.org/Hearst-DD/ObjectMapper) + +ObjectMapper is a framework written in Swift that makes it easy for you to convert your model objects (classes and structs) to and from JSON. + +- [Features](#features) +- [The Basics](#the-basics) +- [Mapping Nested Objects](#easy-mapping-of-nested-objects) +- [Custom Transformations](#custom-transforms) +- [Subclassing](#subclasses) +- [Generic Objects](#generic-objects) +- [Mapping Context](#mapping-context) +- [ObjectMapper + Alamofire](#objectmapper--alamofire) +- [ObjectMapper + Realm](#objectmapper--realm) +- [Projects using ObjectMapper](#projects-using-objectmapper) +- [To Do](#to-do) +- [Contributing](#contributing) +- [Installation](#installation) + +# Features: +- Mapping JSON to objects +- Mapping objects to JSON +- Nested Objects (stand alone, in arrays or in dictionaries) +- Custom transformations during mapping +- Struct support +- [Immutable support](#immutablemappable-protocol) + +# The Basics +To support mapping, a class or struct just needs to implement the ```Mappable``` protocol which includes the following functions: +```swift +init?(map: Map) +mutating func mapping(map: Map) +``` +ObjectMapper uses the ```<-``` operator to define how each member variable maps to and from JSON. + +```swift +class User: Mappable { + var username: String? + var age: Int? + var weight: Double! + var array: [Any]? + var dictionary: [String : Any] = [:] + var bestFriend: User? // Nested User object + var friends: [User]? // Array of Users + var birthday: Date? + + required init?(map: Map) { + + } + + // Mappable + func mapping(map: Map) { + username <- map["username"] + age <- map["age"] + weight <- map["weight"] + array <- map["arr"] + dictionary <- map["dict"] + bestFriend <- map["best_friend"] + friends <- map["friends"] + birthday <- (map["birthday"], DateTransform()) + } +} + +struct Temperature: Mappable { + var celsius: Double? + var fahrenheit: Double? + + init?(map: Map) { + + } + + mutating func mapping(map: Map) { + celsius <- map["celsius"] + fahrenheit <- map["fahrenheit"] + } +} +``` + +Once your class implements `Mappable`, ObjectMapper allows you to easily convert to and from JSON. + +Convert a JSON string to a model object: +```swift +let user = User(JSONString: JSONString) +``` + +Convert a model object to a JSON string: +```swift +let JSONString = user.toJSONString(prettyPrint: true) +``` + +Alternatively, the `Mapper.swift` class can also be used to accomplish the above (it also provides extra functionality for other situations): +```swift +// Convert JSON String to Model +let user = Mapper().map(JSONString: JSONString) +// Create JSON String from Model +let JSONString = Mapper().toJSONString(user, prettyPrint: true) +``` + +ObjectMapper can map classes composed of the following types: +- `Int` +- `Bool` +- `Double` +- `Float` +- `String` +- `RawRepresentable` (Enums) +- `Array` +- `Dictionary` +- `Object` +- `Array` +- `Array>` +- `Set` +- `Dictionary` +- `Dictionary>` +- Optionals of all the above +- Implicitly Unwrapped Optionals of the above + +## `Mappable` Protocol + +#### `mutating func mapping(map: Map)` +This function is where all mapping definitions should go. When parsing JSON, this function is executed after successful object creation. When generating JSON, it is the only function that is called on the object. + +#### `init?(map: Map)` +This failable initializer is used by ObjectMapper for object creation. It can be used by developers to validate JSON prior to object serialization. Returning nil within the function will prevent the mapping from occuring. You can inspect the JSON stored within the `Map` object to do your validation: +```swift +required init?(map: Map){ + // check if a required "name" property exists within the JSON. + if map.JSON["name"] == nil { + return nil + } +} +``` + +## `StaticMappable` Protocol +`StaticMappable` is an alternative to `Mappable`. It provides developers with a static function that is used by ObjectMapper for object initialization instead of `init?(map: Map)`. + +Note: `StaticMappable`, like `Mappable`, is a sub protocol of `BaseMappable` which is where the `mapping(map: Map)` function is defined. + +#### `static func objectForMapping(map: Map) -> BaseMappable?` +ObjectMapper uses this function to get objects to use for mapping. Developers should return an instance of an object that conforms to `BaseMappable` in this function. This function can also be used to: +- validate JSON prior to object serialization +- provide an existing cached object to be used for mapping +- return an object of another type (which also conforms to BaseMappable) to be used for mapping. For instance, you may inspect the JSON to infer the type of object that should be used for mapping ([see examples in ClassClusterTests.swift](https://github.com/Hearst-DD/ObjectMapper/blob/master/Tests/ObjectMapperTests/ClassClusterTests.swift#L67)) + + +If you need to implemented ObjectMapper in an extension, you will need to select this protocol instead of `Mappable`. + +## `ImmutableMappable` Protocol + +`ImmutableMappable` provides the ability to map immutable properties. This is how `ImmutableMappable` differs from `Mappable`: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ImmutableMappableMappable
Properties
+
+let id: Int
+let name: String?
+
+
+
+var id: Int!
+var name: String?
+
+
JSON -> Model
+
+init(map: Map) throws {
+  id   = try map.value("id")
+  name = try? map.value("name")
+}
+
+
+
+mutating func mapping(map: Map) {
+  id   <- map["id"]
+  name <- map["name"]
+}
+
+
Model -> JSON
+
+func mapping(map: Map) {
+  id   >>> map["id"]
+  name >>> map["name"]
+}
+
+
+
+mutating func mapping(map: Map) {
+  id   <- map["id"]
+  name <- map["name"]
+}
+
+
Initializing
+
+try User(JSONString: JSONString)
+
+
+
+User(JSONString: JSONString)
+
+
+ +#### `init(map: Map) throws` + +This throwable initializer is used to map immutable properties from the given `Map`. Every immutable property should be initialized in this initializer. + +This initializer throws an error when: +- `Map` fails to get a value for the given key +- `Map` fails to transform a value using `Transform` + +`ImmutableMappable` uses `Map.value(_:using:)` method to get values from the `Map`. This method should be used with the `try` keyword as it is throwable. `Optional` properties can easily be handled using `try?`. + +```swift +init(map: Map) throws { + name = try map.value("name") // throws an error when it fails + createdAt = try map.value("createdAt", using: DateTransform()) // throws an error when it fails + updatedAt = try? map.value("updatedAt", using: DateTransform()) // optional + posts = (try? map.value("posts")) ?? [] // optional + default value +} +``` + +#### `mutating func mapping(map: Map)` + +This method is where the reverse transform is performed (Model to JSON). Since immutable properties can not be mapped with the `<-` operator, developers have to define the reverse transform using the `>>>` operator. + +```swift +mutating func mapping(map: Map) { + name >>> map["name"] + createdAt >>> (map["createdAt"], DateTransform()) + updatedAt >>> (map["updatedAt"], DateTransform()) + posts >>> map["posts"] +} +``` + + +# Easy Mapping of Nested Objects +ObjectMapper supports dot notation within keys for easy mapping of nested objects. Given the following JSON String: +```json +"distance" : { + "text" : "102 ft", + "value" : 31 +} +``` +You can access the nested objects as follows: +```swift +func mapping(map: Map) { + distance <- map["distance.value"] +} +``` +Nested keys also support accessing values from an array. Given a JSON response with an array of distances, the value could be accessed as follows: +``` +distance <- map["distances.0.value"] +``` +If you have a key that contains `.`, you can individually disable the above feature as follows: +```swift +func mapping(map: Map) { + identifier <- map["app.identifier", nested: false] +} +``` +When you have nested keys which contain `.`, you can pass the custom nested key delimiter as follows ([#629](https://github.com/Hearst-DD/ObjectMapper/pull/629)): +```swift +func mapping(map: Map) { + appName <- map["com.myapp.info->com.myapp.name", delimiter: "->"] +} +``` + +# Custom Transforms +ObjectMapper also supports custom transforms that convert values during the mapping process. To use a transform, simply create a tuple with ```map["field_name"]``` and the transform of your choice on the right side of the ```<-``` operator: +```swift +birthday <- (map["birthday"], DateTransform()) +``` +The above transform will convert the JSON Int value to an Date when reading JSON and will convert the Date to an Int when converting objects to JSON. + +You can easily create your own custom transforms by adopting and implementing the methods in the ```TransformType``` protocol: +```swift +public protocol TransformType { + associatedtype Object + associatedtype JSON + + func transformFromJSON(_ value: Any?) -> Object? + func transformToJSON(_ value: Object?) -> JSON? +} +``` + +### TransformOf +In a lot of situations you can use the built-in transform class ```TransformOf``` to quickly perform a desired transformation. ```TransformOf``` is initialized with two types and two closures. The types define what the transform is converting to and from and the closures perform the actual transformation. + +For example, if you want to transform a JSON String value to an Int you could use ```TransformOf``` as follows: +```swift +let transform = TransformOf(fromJSON: { (value: String?) -> Int? in + // transform value from String? to Int? + return Int(value!) +}, toJSON: { (value: Int?) -> String? in + // transform value from Int? to String? + if let value = value { + return String(value) + } + return nil +}) + +id <- (map["id"], transform) +``` +Here is a more condensed version of the above: +```swift +id <- (map["id"], TransformOf(fromJSON: { Int($0!) }, toJSON: { $0.map { String($0) } })) +``` + +# Subclasses + +Classes that implement the ```Mappable``` protocol can easily be subclassed. When subclassing mappable classes, follow the structure below: + +```swift +class Base: Mappable { + var base: String? + + required init?(map: Map) { + + } + + func mapping(map: Map) { + base <- map["base"] + } +} + +class Subclass: Base { + var sub: String? + + required init?(map: Map) { + super.init(map) + } + + override func mapping(map: Map) { + super.mapping(map) + + sub <- map["sub"] + } +} +``` + +Make sure your subclass implemenation calls the right initializers and mapping functions to also apply the mappings from your superclass. + +# Generic Objects + +ObjectMapper can handle classes with generic types as long as the generic type also conforms to `Mappable`. See the following example: +```swift +class Result: Mappable { + var result: T? + + required init?(map: Map){ + + } + + func mapping(map: Map) { + result <- map["result"] + } +} + +let result = Mapper>().map(JSON) +``` + +# Mapping Context + +The `Map` object which is passed around during mapping, has an optional `MapContext` object that is available for developers to use if they need to pass information around during mapping. + +To take advantage of this feature, simply create an object that implements `MapContext` (which is an empty protocol) and pass it into `Mapper` during initialization. +```swift +struct Context: MapContext { + var importantMappingInfo = "Info that I need during mapping" +} + +class User: Mappable { + var name: String? + + required init?(map: Map){ + + } + + func mapping(map: Map){ + if let context = map.context as? Context { + // use context to make decisions about mapping + } + } +} + +let context = Context() +let user = Mapper(context: context).map(JSONString) +``` + +# ObjectMapper + Alamofire + +If you are using [Alamofire](https://github.com/Alamofire/Alamofire) for networking and you want to convert your responses to Swift objects, you can use [AlamofireObjectMapper](https://github.com/tristanhimmelman/AlamofireObjectMapper). It is a simple Alamofire extension that uses ObjectMapper to automatically map JSON response data to Swift objects. + + +# ObjectMapper + Realm + +ObjectMapper and Realm can be used together. Simply follow the class structure below and you will be able to use ObjectMapper to generate your Realm models: + +```swift +class Model: Object, Mappable { + dynamic var name = "" + + required convenience init?(map: Map) { + self.init() + } + + func mapping(map: Map) { + name <- map["name"] + } +} +``` + +If you want to serialize associated RealmObjects, you can use [ObjectMapper+Realm](https://github.com/jakenberg/ObjectMapper-Realm). It is a simple Realm extension that serializes arbitrary JSON into Realm's List class. + +To serialize Swift String, Int, Double and Bool arrays you can use [ObjectMapperAdditions/Realm](https://github.com/APUtils/ObjectMapperAdditions#realm-features). It'll wrap Swift types into RealmValues that can be stored in Realm's List class. + +Note: Generating a JSON string of a Realm Object using ObjectMappers' `toJSON` function only works within a Realm write transaction. This is caused because ObjectMapper uses the `inout` flag in its mapping functions (`<-`) which are used both for serializing and deserializing. Realm detects the flag and forces the `toJSON` function to be called within a write block even though the objects are not being modified. + +# Projects Using ObjectMapper +- [Xcode Plugin for generating `Mappable` and `ImmutableMappable` code](https://github.com/liyanhuadev/ObjectMapper-Plugin) + +If you have a project that utilizes, extends or provides tooling for ObjectMapper, please submit a PR with a link to your project in this section of the README. + +# To Do +- Improve error handling. Perhaps using `throws` +- Class cluster documentation + +# Contributing + +Contributions are very welcome 👍😃. + +Before submitting any pull request, please ensure you have run the included tests and they have passed. If you are including new functionality, please write test cases for it as well. + +# Installation +### Cocoapods +ObjectMapper can be added to your project using [CocoaPods 0.36 or later](http://blog.cocoapods.org/Pod-Authors-Guide-to-CocoaPods-Frameworks/) by adding the following line to your `Podfile`: + +```ruby +pod 'ObjectMapper', '~> 2.2' +``` + +### Carthage +If you're using [Carthage](https://github.com/Carthage/Carthage) you can add a dependency on ObjectMapper by adding it to your `Cartfile`: + +``` +github "Hearst-DD/ObjectMapper" ~> 2.2 +``` + +### Swift Package Manager +To add ObjectMapper to a [Swift Package Manager](https://swift.org/package-manager/) based project, add: + +```swift +.Package(url: "https://github.com/Hearst-DD/ObjectMapper.git", majorVersion: 2, minor: 2), +``` +to your `Package.swift` files `dependencies` array. + +### Submodule +Otherwise, ObjectMapper can be added as a submodule: + +1. Add ObjectMapper as a [submodule](http://git-scm.com/docs/git-submodule) by opening the terminal, `cd`-ing into your top-level project directory, and entering the command `git submodule add https://github.com/Hearst-DD/ObjectMapper.git` +2. Open the `ObjectMapper` folder, and drag `ObjectMapper.xcodeproj` into the file navigator of your app project. +3. In Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the "Targets" heading in the sidebar. +4. Ensure that the deployment target of `ObjectMapper.framework` matches that of the application target. +5. In the tab bar at the top of that window, open the "Build Phases" panel. +6. Expand the "Target Dependencies" group, and add `ObjectMapper.framework`. +7. Click on the `+` button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and add `ObjectMapper.framework`. diff --git a/Example/Pods/ObjectMapper/Sources/CustomDateFormatTransform.swift b/Carthage/Checkouts/ObjectMapper/Sources/CustomDateFormatTransform.swift similarity index 100% rename from Example/Pods/ObjectMapper/Sources/CustomDateFormatTransform.swift rename to Carthage/Checkouts/ObjectMapper/Sources/CustomDateFormatTransform.swift diff --git a/Example/Pods/ObjectMapper/Sources/DataTransform.swift b/Carthage/Checkouts/ObjectMapper/Sources/DataTransform.swift similarity index 100% rename from Example/Pods/ObjectMapper/Sources/DataTransform.swift rename to Carthage/Checkouts/ObjectMapper/Sources/DataTransform.swift diff --git a/Example/Pods/ObjectMapper/Sources/DateFormatterTransform.swift b/Carthage/Checkouts/ObjectMapper/Sources/DateFormatterTransform.swift similarity index 100% rename from Example/Pods/ObjectMapper/Sources/DateFormatterTransform.swift rename to Carthage/Checkouts/ObjectMapper/Sources/DateFormatterTransform.swift diff --git a/Example/Pods/ObjectMapper/Sources/DateTransform.swift b/Carthage/Checkouts/ObjectMapper/Sources/DateTransform.swift similarity index 100% rename from Example/Pods/ObjectMapper/Sources/DateTransform.swift rename to Carthage/Checkouts/ObjectMapper/Sources/DateTransform.swift diff --git a/Example/Pods/ObjectMapper/Sources/DictionaryTransform.swift b/Carthage/Checkouts/ObjectMapper/Sources/DictionaryTransform.swift similarity index 100% rename from Example/Pods/ObjectMapper/Sources/DictionaryTransform.swift rename to Carthage/Checkouts/ObjectMapper/Sources/DictionaryTransform.swift diff --git a/Example/Pods/ObjectMapper/Sources/EnumOperators.swift b/Carthage/Checkouts/ObjectMapper/Sources/EnumOperators.swift similarity index 100% rename from Example/Pods/ObjectMapper/Sources/EnumOperators.swift rename to Carthage/Checkouts/ObjectMapper/Sources/EnumOperators.swift diff --git a/Example/Pods/ObjectMapper/Sources/EnumTransform.swift b/Carthage/Checkouts/ObjectMapper/Sources/EnumTransform.swift similarity index 100% rename from Example/Pods/ObjectMapper/Sources/EnumTransform.swift rename to Carthage/Checkouts/ObjectMapper/Sources/EnumTransform.swift diff --git a/Example/Pods/ObjectMapper/Sources/FromJSON.swift b/Carthage/Checkouts/ObjectMapper/Sources/FromJSON.swift similarity index 100% rename from Example/Pods/ObjectMapper/Sources/FromJSON.swift rename to Carthage/Checkouts/ObjectMapper/Sources/FromJSON.swift diff --git a/Example/Pods/ObjectMapper/Sources/HexColorTransform.swift b/Carthage/Checkouts/ObjectMapper/Sources/HexColorTransform.swift similarity index 95% rename from Example/Pods/ObjectMapper/Sources/HexColorTransform.swift rename to Carthage/Checkouts/ObjectMapper/Sources/HexColorTransform.swift index ac045a3..dd9299f 100644 --- a/Example/Pods/ObjectMapper/Sources/HexColorTransform.swift +++ b/Carthage/Checkouts/ObjectMapper/Sources/HexColorTransform.swift @@ -35,8 +35,8 @@ open class HexColorTransform: TransformType { open func transformFromJSON(_ value: Any?) -> Object? { if let rgba = value as? String { if rgba.hasPrefix("#") { - let index = rgba.index(rgba.startIndex, offsetBy: 1) - let hex = String(rgba[index...]) + let index = rgba.characters.index(rgba.startIndex, offsetBy: 1) + let hex = rgba.substring(from: index) return getColor(hex: hex) } else { return getColor(hex: rgba) @@ -89,7 +89,7 @@ open class HexColorTransform: TransformType { let scanner = Scanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexInt64(&hexValue) { - switch (hex.count) { + switch (hex.characters.count) { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 diff --git a/Example/Pods/ObjectMapper/Sources/ISO8601DateTransform.swift b/Carthage/Checkouts/ObjectMapper/Sources/ISO8601DateTransform.swift similarity index 100% rename from Example/Pods/ObjectMapper/Sources/ISO8601DateTransform.swift rename to Carthage/Checkouts/ObjectMapper/Sources/ISO8601DateTransform.swift diff --git a/Example/Pods/ObjectMapper/Sources/ImmutableMappable.swift b/Carthage/Checkouts/ObjectMapper/Sources/ImmutableMappable.swift similarity index 95% rename from Example/Pods/ObjectMapper/Sources/ImmutableMappable.swift rename to Carthage/Checkouts/ObjectMapper/Sources/ImmutableMappable.swift index d9d242a..46ce555 100644 --- a/Example/Pods/ObjectMapper/Sources/ImmutableMappable.swift +++ b/Carthage/Checkouts/ObjectMapper/Sources/ImmutableMappable.swift @@ -108,8 +108,7 @@ public extension Map { guard let jsonArray = currentValue as? [Any] else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[Any]'", file: file, function: function, line: line) } - - return try jsonArray.map { JSONObject -> T in + return try jsonArray.enumerated().map { i, JSONObject -> T in return try Mapper(context: context).mapOrFail(JSONObject: JSONObject) } } @@ -120,10 +119,9 @@ public extension Map { guard let jsonArray = currentValue as? [Any] else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[Any]'", file: file, function: function, line: line) } - - return try jsonArray.map { json -> Transform.Object in + return try jsonArray.enumerated().map { i, json -> Transform.Object in guard let object = transform.transformFromJSON(json) else { - throw MapError(key: "\(key)", currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) + throw MapError(key: "\(key)[\(i)]", currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) } return object } @@ -185,16 +183,16 @@ public extension Map { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[[Any]]'", file: file, function: function, line: line) } - - return try json2DArray.map { jsonArray in - try jsonArray.map { json -> Transform.Object in + return try json2DArray.enumerated().map { i, jsonArray in + try jsonArray.enumerated().map { j, json -> Transform.Object in guard let object = transform.transformFromJSON(json) else { - throw MapError(key: "\(key)", currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) + throw MapError(key: "\(key)[\(i)][\(j)]", currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) } return object } } } + } public extension Mapper where N: ImmutableMappable { diff --git a/Carthage/Checkouts/ObjectMapper/Sources/Info.plist b/Carthage/Checkouts/ObjectMapper/Sources/Info.plist new file mode 100644 index 0000000..cf4a97c --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Sources/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.14 + CFBundleSignature + ???? + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + NSPrincipalClass + + + diff --git a/Example/Pods/ObjectMapper/Sources/IntegerOperators.swift b/Carthage/Checkouts/ObjectMapper/Sources/IntegerOperators.swift similarity index 94% rename from Example/Pods/ObjectMapper/Sources/IntegerOperators.swift rename to Carthage/Checkouts/ObjectMapper/Sources/IntegerOperators.swift index a4191e6..269c3bc 100644 --- a/Example/Pods/ObjectMapper/Sources/IntegerOperators.swift +++ b/Carthage/Checkouts/ObjectMapper/Sources/IntegerOperators.swift @@ -97,19 +97,19 @@ private func toSignedInteger(_ value: Any?) -> T? { return nil } - if T.self == Int.self, let x = Int(exactly: number.int64Value) { + if T.self == Int.self, let x = Int(exactly: number.int64Value)?.toIntMax() { return T.init(x) } - if T.self == Int8.self, let x = Int8(exactly: number.int64Value) { + if T.self == Int8.self, let x = Int8(exactly: number.int64Value)?.toIntMax() { return T.init(x) } - if T.self == Int16.self, let x = Int16(exactly: number.int64Value) { + if T.self == Int16.self, let x = Int16(exactly: number.int64Value)?.toIntMax() { return T.init(x) } - if T.self == Int32.self, let x = Int32(exactly: number.int64Value) { + if T.self == Int32.self, let x = Int32(exactly: number.int64Value)?.toIntMax() { return T.init(x) } - if T.self == Int64.self, let x = Int64(exactly: number.int64Value) { + if T.self == Int64.self, let x = Int64(exactly: number.int64Value)?.toIntMax() { return T.init(x) } @@ -125,19 +125,19 @@ private func toUnsignedInteger(_ value: Any?) -> T? { return nil } - if T.self == UInt.self, let x = UInt(exactly: number.uint64Value) { + if T.self == UInt.self, let x = UInt(exactly: number.uint64Value)?.toUIntMax() { return T.init(x) } - if T.self == UInt8.self, let x = UInt8(exactly: number.uint64Value) { + if T.self == UInt8.self, let x = UInt8(exactly: number.uint64Value)?.toUIntMax() { return T.init(x) } - if T.self == UInt16.self, let x = UInt16(exactly: number.uint64Value) { + if T.self == UInt16.self, let x = UInt16(exactly: number.uint64Value)?.toUIntMax() { return T.init(x) } - if T.self == UInt32.self, let x = UInt32(exactly: number.uint64Value) { + if T.self == UInt32.self, let x = UInt32(exactly: number.uint64Value)?.toUIntMax() { return T.init(x) } - if T.self == UInt64.self, let x = UInt64(exactly: number.uint64Value) { + if T.self == UInt64.self, let x = UInt64(exactly: number.uint64Value)?.toUIntMax() { return T.init(x) } diff --git a/Example/Pods/ObjectMapper/Sources/Map.swift b/Carthage/Checkouts/ObjectMapper/Sources/Map.swift similarity index 100% rename from Example/Pods/ObjectMapper/Sources/Map.swift rename to Carthage/Checkouts/ObjectMapper/Sources/Map.swift diff --git a/Example/Pods/ObjectMapper/Sources/MapError.swift b/Carthage/Checkouts/ObjectMapper/Sources/MapError.swift similarity index 96% rename from Example/Pods/ObjectMapper/Sources/MapError.swift rename to Carthage/Checkouts/ObjectMapper/Sources/MapError.swift index 8e1c69a..21e20cb 100644 --- a/Example/Pods/ObjectMapper/Sources/MapError.swift +++ b/Carthage/Checkouts/ObjectMapper/Sources/MapError.swift @@ -61,7 +61,7 @@ extension MapError: CustomStringConvertible { ("- key", key), ("- currentValue", currentValue), ] - let infoString = info.map { "\($0.0): \($0.1 ?? "nil")" }.joined(separator: "\n") + let infoString = info.map { "\($0): \($1 ?? "nil")" }.joined(separator: "\n") return "Got an error while mapping.\n\(infoString)" } diff --git a/Example/Pods/ObjectMapper/Sources/Mappable.swift b/Carthage/Checkouts/ObjectMapper/Sources/Mappable.swift similarity index 100% rename from Example/Pods/ObjectMapper/Sources/Mappable.swift rename to Carthage/Checkouts/ObjectMapper/Sources/Mappable.swift diff --git a/Example/Pods/ObjectMapper/Sources/Mapper.swift b/Carthage/Checkouts/ObjectMapper/Sources/Mapper.swift similarity index 91% rename from Example/Pods/ObjectMapper/Sources/Mapper.swift rename to Carthage/Checkouts/ObjectMapper/Sources/Mapper.swift index 30e7b8b..b3cd984 100755 --- a/Example/Pods/ObjectMapper/Sources/Mapper.swift +++ b/Carthage/Checkouts/ObjectMapper/Sources/Mapper.swift @@ -280,44 +280,6 @@ public final class Mapper { } } -extension Mapper { - // MARK: Functions that create model from JSON file - - /// JSON file to Mappable object - /// - parameter JSONfile: Filename - /// - Returns: Mappable object - public func map(JSONfile: String) -> N? { - if let path = Bundle.main.path(forResource: JSONfile, ofType: nil) { - do { - let JSONString = try String(contentsOfFile: path) - do { - return self.map(JSONString: JSONString) - } - } catch { - return nil - } - } - return nil - } - - /// JSON file to Mappable object array - /// - parameter JSONfile: Filename - /// - Returns: Mappable object array - public func mapArray(JSONfile: String) -> [N]? { - if let path = Bundle.main.path(forResource: JSONfile, ofType: nil) { - do { - let JSONString = try String(contentsOfFile: path) - do { - return self.mapArray(JSONString: JSONString) - } - } catch { - return nil - } - } - return nil - } -} - extension Mapper { // MARK: Functions that create JSON from objects @@ -340,17 +302,17 @@ extension Mapper { ///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries. public func toJSONDictionary(_ dictionary: [String: N]) -> [String: [String: Any]] { - return dictionary.map { (arg: (key: String, value: N)) in + return dictionary.map { k, v in // convert every value in dictionary to its JSON dictionary equivalent - return (arg.key, self.toJSON(arg.value)) + return (k, self.toJSON(v)) } } ///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries. public func toJSONDictionaryOfArrays(_ dictionary: [String: [N]]) -> [String: [[String: Any]]] { - return dictionary.map { (arg: (key: String, value: [N])) in + return dictionary.map { k, v in // convert every value (array) in dictionary to its JSON dictionary equivalent - return (arg.key, self.toJSONArray(arg.value)) + return (k, self.toJSONArray(v)) } } @@ -447,7 +409,7 @@ extension Mapper where N: Hashable { } extension Dictionary { - internal func map(_ f: (Element) throws -> (K, V)) rethrows -> [K: V] { + internal func map(_ f: (Element) throws -> (K, V)) rethrows -> [K: V] { var mapped = [K: V]() for element in self { @@ -458,7 +420,7 @@ extension Dictionary { return mapped } - internal func map(_ f: (Element) throws -> (K, [V])) rethrows -> [K: [V]] { + internal func map(_ f: (Element) throws -> (K, [V])) rethrows -> [K: [V]] { var mapped = [K: [V]]() for element in self { diff --git a/Example/Pods/ObjectMapper/Sources/NSDecimalNumberTransform.swift b/Carthage/Checkouts/ObjectMapper/Sources/NSDecimalNumberTransform.swift similarity index 100% rename from Example/Pods/ObjectMapper/Sources/NSDecimalNumberTransform.swift rename to Carthage/Checkouts/ObjectMapper/Sources/NSDecimalNumberTransform.swift diff --git a/Carthage/Checkouts/ObjectMapper/Sources/ObjectMapper.h b/Carthage/Checkouts/ObjectMapper/Sources/ObjectMapper.h new file mode 100644 index 0000000..7223791 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Sources/ObjectMapper.h @@ -0,0 +1,40 @@ +// +// ObjectMapper.h +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-16. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + + +#import + +//! Project version number for ObjectMapper. +FOUNDATION_EXPORT double ObjectMapperVersionNumber; + +//! Project version string for ObjectMapper. +FOUNDATION_EXPORT const unsigned char ObjectMapperVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import + + diff --git a/Example/Pods/ObjectMapper/Sources/Operators.swift b/Carthage/Checkouts/ObjectMapper/Sources/Operators.swift similarity index 100% rename from Example/Pods/ObjectMapper/Sources/Operators.swift rename to Carthage/Checkouts/ObjectMapper/Sources/Operators.swift diff --git a/Example/Pods/ObjectMapper/Sources/ToJSON.swift b/Carthage/Checkouts/ObjectMapper/Sources/ToJSON.swift similarity index 97% rename from Example/Pods/ObjectMapper/Sources/ToJSON.swift rename to Carthage/Checkouts/ObjectMapper/Sources/ToJSON.swift index bb53f61..32c3432 100644 --- a/Example/Pods/ObjectMapper/Sources/ToJSON.swift +++ b/Carthage/Checkouts/ObjectMapper/Sources/ToJSON.swift @@ -34,14 +34,14 @@ private func setValue(_ value: Any, map: Map) { private func setValue(_ value: Any, key: String, checkForNestedKeys: Bool, delimiter: String, dictionary: inout [String : Any]) { if checkForNestedKeys { - let keyComponents = ArraySlice(key.components(separatedBy: delimiter).filter { !$0.isEmpty }.map { $0 }) + let keyComponents = ArraySlice(key.components(separatedBy: delimiter).filter { !$0.isEmpty }.map { $0.characters }) setValue(value, forKeyPathComponents: keyComponents, dictionary: &dictionary) } else { dictionary[key] = value } } -private func setValue(_ value: Any, forKeyPathComponents components: ArraySlice, dictionary: inout [String : Any]) { +private func setValue(_ value: Any, forKeyPathComponents components: ArraySlice, dictionary: inout [String : Any]) { if components.isEmpty { return } diff --git a/Example/Pods/ObjectMapper/Sources/TransformOf.swift b/Carthage/Checkouts/ObjectMapper/Sources/TransformOf.swift similarity index 100% rename from Example/Pods/ObjectMapper/Sources/TransformOf.swift rename to Carthage/Checkouts/ObjectMapper/Sources/TransformOf.swift diff --git a/Example/Pods/ObjectMapper/Sources/TransformOperators.swift b/Carthage/Checkouts/ObjectMapper/Sources/TransformOperators.swift similarity index 96% rename from Example/Pods/ObjectMapper/Sources/TransformOperators.swift rename to Carthage/Checkouts/ObjectMapper/Sources/TransformOperators.swift index 0a96e00..a68f895 100644 --- a/Example/Pods/ObjectMapper/Sources/TransformOperators.swift +++ b/Carthage/Checkouts/ObjectMapper/Sources/TransformOperators.swift @@ -300,8 +300,7 @@ public func <- (left: inout Dictionary (String, [Transform.Object]) in - let (key, values) = arg + let transformedDictionary = dictionary.map { (key: String, values: [Any]) -> (String, [Transform.Object]) in if let jsonArray = fromJSONArrayWithTransform(values, transform: transform) { return (key, jsonArray) } @@ -321,9 +320,8 @@ public func >>> (left: Dictionary(left: inout Dictionary (String, [Transform.Object]) in - let (key, values) = arg + let transformedDictionary = dictionary.map { (key: String, values: [Any]) -> (String, [Transform.Object]) in if let jsonArray = fromJSONArrayWithTransform(values, transform: transform) { return (key, jsonArray) } @@ -346,6 +343,7 @@ public func <- (left: inout Dictionary>> (left: Dictionary(left: inout Dictionary (String, [Transform.Object]) in - let (key, values) = arg + let transformedDictionary = dictionary.map { (key: String, values: [Any]) -> (String, [Transform.Object]) in if let jsonArray = fromJSONArrayWithTransform(values, transform: transform) { return (key, jsonArray) } diff --git a/Example/Pods/ObjectMapper/Sources/TransformType.swift b/Carthage/Checkouts/ObjectMapper/Sources/TransformType.swift similarity index 100% rename from Example/Pods/ObjectMapper/Sources/TransformType.swift rename to Carthage/Checkouts/ObjectMapper/Sources/TransformType.swift diff --git a/Example/Pods/ObjectMapper/Sources/URLTransform.swift b/Carthage/Checkouts/ObjectMapper/Sources/URLTransform.swift similarity index 95% rename from Example/Pods/ObjectMapper/Sources/URLTransform.swift rename to Carthage/Checkouts/ObjectMapper/Sources/URLTransform.swift index 5624476..683a934 100644 --- a/Example/Pods/ObjectMapper/Sources/URLTransform.swift +++ b/Carthage/Checkouts/ObjectMapper/Sources/URLTransform.swift @@ -40,7 +40,7 @@ open class URLTransform: TransformType { to `NSURL(string:)` - returns: an initialized transformer */ - public init(shouldEncodeURLString: Bool = false, allowedCharacterSet: CharacterSet = .urlQueryAllowed) { + public init(shouldEncodeURLString: Bool = true, allowedCharacterSet: CharacterSet = .urlQueryAllowed) { self.shouldEncodeURLString = shouldEncodeURLString self.allowedCharacterSet = allowedCharacterSet } diff --git a/Carthage/Checkouts/ObjectMapper/Tests/Info.plist b/Carthage/Checkouts/ObjectMapper/Tests/Info.plist new file mode 100644 index 0000000..ba72822 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + + diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/BasicTypes.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/BasicTypes.swift new file mode 100644 index 0000000..024d3a0 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/BasicTypes.swift @@ -0,0 +1,333 @@ +// +// BasicTypes.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2015-02-17. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 +import ObjectMapper + +class BasicTypes: Mappable { + var bool: Bool = true + var boolOptional: Bool? + var boolImplicityUnwrapped: Bool! + + var int: Int = 0 + var intOptional: Int? + var intImplicityUnwrapped: Int! + + var int8: Int8 = 0 + var int8Optional: Int8? + var int8ImplicityUnwrapped: Int8! + + var int16: Int16 = 0 + var int16Optional: Int16? + var int16ImplicityUnwrapped: Int16! + + var int32: Int32 = 0 + var int32Optional: Int32? + var int32ImplicityUnwrapped: Int32! + + var int64: Int64 = 0 + var int64Optional: Int64? + var int64ImplicityUnwrapped: Int64! + + var uint: UInt = 0 + var uintOptional: UInt? + var uintImplicityUnwrapped: UInt! + + var uint8: UInt8 = 0 + var uint8Optional: UInt8? + var uint8ImplicityUnwrapped: UInt8! + + var uint16: UInt16 = 0 + var uint16Optional: UInt16? + var uint16ImplicityUnwrapped: UInt16! + + var uint32: UInt32 = 0 + var uint32Optional: UInt32? + var uint32ImplicityUnwrapped: UInt32! + + var uint64: UInt64 = 0 + var uint64Optional: UInt64? + var uint64ImplicityUnwrapped: UInt64! + + var double: Double = 1.1 + var doubleOptional: Double? + var doubleImplicityUnwrapped: Double! + var float: Float = 1.11 + var floatOptional: Float? + var floatImplicityUnwrapped: Float! + var string: String = "" + var stringOptional: String? + var stringImplicityUnwrapped: String! + var anyObject: Any = true + var anyObjectOptional: Any? + var anyObjectImplicitlyUnwrapped: Any! + + var arrayBool: Array = [] + var arrayBoolOptional: Array? + var arrayBoolImplicityUnwrapped: Array! + var arrayInt: Array = [] + var arrayIntOptional: Array? + var arrayIntImplicityUnwrapped: Array! + var arrayDouble: Array = [] + var arrayDoubleOptional: Array? + var arrayDoubleImplicityUnwrapped: Array! + var arrayFloat: Array = [] + var arrayFloatOptional: Array? + var arrayFloatImplicityUnwrapped: Array! + var arrayString: Array = [] + var arrayStringOptional: Array? + var arrayStringImplicityUnwrapped: Array! + var arrayAnyObject: Array = [] + var arrayAnyObjectOptional: Array? + var arrayAnyObjectImplicitlyUnwrapped: Array! + + var dictBool: Dictionary = [:] + var dictBoolOptional: Dictionary? + var dictBoolImplicityUnwrapped: Dictionary! + var dictInt: Dictionary = [:] + var dictIntOptional: Dictionary? + var dictIntImplicityUnwrapped: Dictionary! + var dictDouble: Dictionary = [:] + var dictDoubleOptional: Dictionary? + var dictDoubleImplicityUnwrapped: Dictionary! + var dictFloat: Dictionary = [:] + var dictFloatOptional: Dictionary? + var dictFloatImplicityUnwrapped: Dictionary! + var dictString: Dictionary = [:] + var dictStringOptional: Dictionary? + var dictStringImplicityUnwrapped: Dictionary! + var dictAnyObject: Dictionary = [:] + var dictAnyObjectOptional: Dictionary? + var dictAnyObjectImplicitlyUnwrapped: Dictionary! + + enum EnumInt: Int { + case Default + case Another + } + var enumInt: EnumInt = .Default + var enumIntOptional: EnumInt? + var enumIntImplicitlyUnwrapped: EnumInt! + + enum EnumDouble: Double { + case Default + case Another + } + var enumDouble: EnumDouble = .Default + var enumDoubleOptional: EnumDouble? + var enumDoubleImplicitlyUnwrapped: EnumDouble! + + enum EnumFloat: Float { + case Default + case Another + } + var enumFloat: EnumFloat = .Default + var enumFloatOptional: EnumFloat? + var enumFloatImplicitlyUnwrapped: EnumFloat! + + enum EnumString: String { + case Default = "Default" + case Another = "Another" + } + var enumString: EnumString = .Default + var enumStringOptional: EnumString? + var enumStringImplicitlyUnwrapped: EnumString! + + var arrayEnumInt: [EnumInt] = [] + var arrayEnumIntOptional: [EnumInt]? + var arrayEnumIntImplicitlyUnwrapped: [EnumInt]! + + var dictEnumInt: [String: EnumInt] = [:] + var dictEnumIntOptional: [String: EnumInt]? + var dictEnumIntImplicitlyUnwrapped: [String: EnumInt]! + + init(){ + + } + + required init?(map: Map){ + + } + + func mapping(map: Map) { + bool <- map["bool"] + boolOptional <- map["boolOpt"] + boolImplicityUnwrapped <- map["boolImp"] + + int <- map["int"] + intOptional <- map["intOpt"] + intImplicityUnwrapped <- map["intImp"] + + int8 <- map["int8"] + int8Optional <- map["int8Opt"] + int8ImplicityUnwrapped <- map["int8Imp"] + + int16 <- map["int16"] + int16Optional <- map["int16Opt"] + int16ImplicityUnwrapped <- map["int16Imp"] + + int32 <- map["int32"] + int32Optional <- map["int32Opt"] + int32ImplicityUnwrapped <- map["int32Imp"] + + int64 <- map["int64"] + int64Optional <- map["int64Opt"] + int64ImplicityUnwrapped <- map["int64Imp"] + + uint <- map["uint"] + uintOptional <- map["uintOpt"] + uintImplicityUnwrapped <- map["uintImp"] + + uint8 <- map["uint8"] + uint8Optional <- map["uint8Opt"] + uint8ImplicityUnwrapped <- map["uint8Imp"] + + uint16 <- map["uint16"] + uint16Optional <- map["uint16Opt"] + uint16ImplicityUnwrapped <- map["uint16Imp"] + + uint32 <- map["uint32"] + uint32Optional <- map["uint32Opt"] + uint32ImplicityUnwrapped <- map["uint32Imp"] + + uint64 <- map["uint64"] + uint64Optional <- map["uint64Opt"] + uint64ImplicityUnwrapped <- map["uint64Imp"] + + double <- map["double"] + doubleOptional <- map["doubleOpt"] + doubleImplicityUnwrapped <- map["doubleImp"] + float <- map["float"] + floatOptional <- map["floatOpt"] + floatImplicityUnwrapped <- map["floatImp"] + string <- map["string"] + stringOptional <- map["stringOpt"] + stringImplicityUnwrapped <- map["stringImp"] + anyObject <- map["anyObject"] + anyObjectOptional <- map["anyObjectOpt"] + anyObjectImplicitlyUnwrapped <- map["anyObjectImp"] + + arrayBool <- map["arrayBool"] + arrayBoolOptional <- map["arrayBoolOpt"] + arrayBoolImplicityUnwrapped <- map["arrayBoolImp"] + arrayInt <- map["arrayInt"] + arrayIntOptional <- map["arrayIntOpt"] + arrayIntImplicityUnwrapped <- map["arrayIntImp"] + arrayDouble <- map["arrayDouble"] + arrayDoubleOptional <- map["arrayDoubleOpt"] + arrayDoubleImplicityUnwrapped <- map["arrayDoubleImp"] + arrayFloat <- map["arrayFloat"] + arrayFloatOptional <- map["arrayFloatOpt"] + arrayFloatImplicityUnwrapped <- map["arrayFloatImp"] + arrayString <- map["arrayString"] + arrayStringOptional <- map["arrayStringOpt"] + arrayStringImplicityUnwrapped <- map["arrayStringImp"] + arrayAnyObject <- map["arrayAnyObject"] + arrayAnyObjectOptional <- map["arrayAnyObjectOpt"] + arrayAnyObjectImplicitlyUnwrapped <- map["arrayAnyObjectImp"] + + dictBool <- map["dictBool"] + dictBoolOptional <- map["dictBoolOpt"] + dictBoolImplicityUnwrapped <- map["dictBoolImp"] + dictInt <- map["dictInt"] + dictIntOptional <- map["dictIntOpt"] + dictIntImplicityUnwrapped <- map["dictIntImp"] + dictDouble <- map["dictDouble"] + dictDoubleOptional <- map["dictDoubleOpt"] + dictDoubleImplicityUnwrapped <- map["dictDoubleImp"] + dictFloat <- map["dictFloat"] + dictFloatOptional <- map["dictFloatOpt"] + dictFloatImplicityUnwrapped <- map["dictFloatImp"] + dictString <- map["dictString"] + dictStringOptional <- map["dictStringOpt"] + dictStringImplicityUnwrapped <- map["dictStringImp"] + dictAnyObject <- map["dictAnyObject"] + dictAnyObjectOptional <- map["dictAnyObjectOpt"] + dictAnyObjectImplicitlyUnwrapped <- map["dictAnyObjectImp"] + + enumInt <- map["enumInt"] + enumIntOptional <- map["enumIntOpt"] + enumIntImplicitlyUnwrapped <- map["enumIntImp"] + enumDouble <- map["enumDouble"] + enumDoubleOptional <- map["enumDoubleOpt"] + enumDoubleImplicitlyUnwrapped <- map["enumDoubleImp"] + enumFloat <- map["enumFloat"] + enumFloatOptional <- map["enumFloatOpt"] + enumFloatImplicitlyUnwrapped <- map["enumFloatImp"] + enumString <- map["enumString"] + enumStringOptional <- map["enumStringOpt"] + enumStringImplicitlyUnwrapped <- map["enumStringImp"] + + arrayEnumInt <- map["arrayEnumInt"] + arrayEnumIntOptional <- map["arrayEnumIntOpt"] + arrayEnumIntImplicitlyUnwrapped <- map["arrayEnumIntImp"] + + dictEnumInt <- map["dictEnumInt"] + dictEnumIntOptional <- map["dictEnumIntOpt"] + dictEnumIntImplicitlyUnwrapped <- map["dictEnumIntImp"] + } +} + +class TestCollectionOfPrimitives: Mappable { + var dictStringString: [String: String] = [:] + var dictStringInt: [String: Int] = [:] + var dictStringBool: [String: Bool] = [:] + var dictStringDouble: [String: Double] = [:] + var dictStringFloat: [String: Float] = [:] + + var arrayString: [String] = [] + var arrayInt: [Int] = [] + var arrayBool: [Bool] = [] + var arrayDouble: [Double] = [] + var arrayFloat: [Float] = [] + + init(){ + + } + + required init?(map: Map){ + if map["value"].value() == nil { + + } + if map.JSON["value"] == nil { + + } + } + + func mapping(map: Map) { + dictStringString <- map["dictStringString"] + dictStringBool <- map["dictStringBool"] + dictStringInt <- map["dictStringInt"] + dictStringDouble <- map["dictStringDouble"] + dictStringFloat <- map["dictStringFloat"] + arrayString <- map["arrayString"] + arrayInt <- map["arrayInt"] + arrayBool <- map["arrayBool"] + arrayDouble <- map["arrayDouble"] + arrayFloat <- map["arrayFloat"] + } +} diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/BasicTypesTestsFromJSON.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/BasicTypesTestsFromJSON.swift new file mode 100644 index 0000000..a3d9610 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/BasicTypesTestsFromJSON.swift @@ -0,0 +1,616 @@ +// +// BasicTypesFromJSON.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2015-02-17. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 +import XCTest +import ObjectMapper + +class BasicTypesTestsFromJSON: XCTestCase { + + let mapper = Mapper() + + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } + + // MARK: Test mapping to JSON and back (basic types: Bool, Int, Double, Float, String) + + func testMappingBoolFromJSON(){ + let value: Bool = true + let JSONString = "{\"bool\" : \(value), \"boolOpt\" : \(value), \"boolImp\" : \(value)}" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.bool, value) + XCTAssertEqual(mappedObject?.boolOptional, value) + XCTAssertEqual(mappedObject?.boolImplicityUnwrapped, value) + } + + /// - warning: This test doens't consider about integer overflow/underflow. + func testMappingIntegerFromJSON(){ + func parameterize(_ type: T.Type) { + let value: T = 123 + let json: [String: Any] = [ + "int": value, + "intOpt": value, + "intImp": value, + + "int8": value, + "int8Opt": value, + "int8Imp": value, + + "int16": value, + "int16Opt": value, + "int16Imp": value, + + "int32": value, + "int32Opt": value, + "int32Imp": value, + + "int64": value, + "int64Opt": value, + "int64Imp": value, + + "uint": value, + "uintOpt": value, + "uintImp": value, + + "uint8": value, + "uint8Opt": value, + "uint8Imp": value, + + "uint16": value, + "uint16Opt": value, + "uint16Imp": value, + + "uint32": value, + "uint32Opt": value, + "uint32Imp": value, + + "uint64": value, + "uint64Opt": value, + "uint64Imp": value, + ] + let mappedObject = mapper.map(JSON: json) + XCTAssertNotNil(mappedObject) + + XCTAssertEqual(mappedObject?.int, 123) + XCTAssertEqual(mappedObject?.intOptional, 123) + XCTAssertEqual(mappedObject?.intImplicityUnwrapped, 123) + + XCTAssertEqual(mappedObject?.int8, 123) + XCTAssertEqual(mappedObject?.int8Optional, 123) + XCTAssertEqual(mappedObject?.int8ImplicityUnwrapped, 123) + + XCTAssertEqual(mappedObject?.int16, 123) + XCTAssertEqual(mappedObject?.int16Optional, 123) + XCTAssertEqual(mappedObject?.int16ImplicityUnwrapped, 123) + + XCTAssertEqual(mappedObject?.int32, 123) + XCTAssertEqual(mappedObject?.int32Optional, 123) + XCTAssertEqual(mappedObject?.int32ImplicityUnwrapped, 123) + + XCTAssertEqual(mappedObject?.int64, 123) + XCTAssertEqual(mappedObject?.int64Optional, 123) + XCTAssertEqual(mappedObject?.int64ImplicityUnwrapped, 123) + + XCTAssertEqual(mappedObject?.uint, 123) + XCTAssertEqual(mappedObject?.uintOptional, 123) + XCTAssertEqual(mappedObject?.uintImplicityUnwrapped, 123) + + XCTAssertEqual(mappedObject?.uint8, 123) + XCTAssertEqual(mappedObject?.uint8Optional, 123) + XCTAssertEqual(mappedObject?.uint8ImplicityUnwrapped, 123) + + XCTAssertEqual(mappedObject?.uint16, 123) + XCTAssertEqual(mappedObject?.uint16Optional, 123) + XCTAssertEqual(mappedObject?.uint16ImplicityUnwrapped, 123) + + XCTAssertEqual(mappedObject?.uint32, 123) + XCTAssertEqual(mappedObject?.uint32Optional, 123) + XCTAssertEqual(mappedObject?.uint32ImplicityUnwrapped, 123) + + XCTAssertEqual(mappedObject?.uint64, 123) + XCTAssertEqual(mappedObject?.uint64Optional, 123) + XCTAssertEqual(mappedObject?.uint64ImplicityUnwrapped, 123) + } + + parameterize(Int.self) + parameterize(Int8.self) + parameterize(Int16.self) + parameterize(Int32.self) + parameterize(Int64.self) + + parameterize(UInt.self) + parameterize(UInt8.self) + parameterize(UInt16.self) + parameterize(UInt32.self) + parameterize(UInt64.self) + } + + func testMappingIntegerWithOverflowFromJSON(){ + let signedValue = Int.max + let unsignedValue = UInt.max + + let json: [String: Any] = [ + "int": signedValue, + "intOpt": signedValue, + "intImp": signedValue, + + "int8": signedValue, + "int8Opt": signedValue, + "int8Imp": signedValue, + + "int16": signedValue, + "int16Opt": signedValue, + "int16Imp": signedValue, + + "int32": signedValue, + "int32Opt": signedValue, + "int32Imp": signedValue, + + "int64": signedValue, + "int64Opt": signedValue, + "int64Imp": signedValue, + + "uint": unsignedValue, + "uintOpt": unsignedValue, + "uintImp": unsignedValue, + + "uint8": unsignedValue, + "uint8Opt": unsignedValue, + "uint8Imp": unsignedValue, + + "uint16": unsignedValue, + "uint16Opt": unsignedValue, + "uint16Imp": unsignedValue, + + "uint32": unsignedValue, + "uint32Opt": unsignedValue, + "uint32Imp": unsignedValue, + + "uint64": unsignedValue, + "uint64Opt": unsignedValue, + "uint64Imp": unsignedValue, + ] + let mappedObject = mapper.map(JSON: json) + XCTAssertNotNil(mappedObject) + + XCTAssertEqual(mappedObject?.int, Int.max) + XCTAssertEqual(mappedObject?.intOptional, Int.max) + XCTAssertEqual(mappedObject?.intImplicityUnwrapped, Int.max) + + XCTAssertEqual(mappedObject?.int8, 0) + XCTAssertEqual(mappedObject?.int8Optional, nil) + XCTAssertEqual(mappedObject?.int8ImplicityUnwrapped, nil) + + XCTAssertEqual(mappedObject?.int16, 0) + XCTAssertEqual(mappedObject?.int16Optional, nil) + XCTAssertEqual(mappedObject?.int16ImplicityUnwrapped, nil) + +#if arch(x86_64) || arch(arm64) + XCTAssertEqual(mappedObject?.int32, 0) + XCTAssertEqual(mappedObject?.int32Optional, nil) + XCTAssertEqual(mappedObject?.int32ImplicityUnwrapped, nil) + + XCTAssertEqual(mappedObject?.int64, Int64.max) + XCTAssertEqual(mappedObject?.int64Optional, Int64.max) + XCTAssertEqual(mappedObject?.int64ImplicityUnwrapped, Int64.max) +#else + XCTAssertEqual(mappedObject?.int32, Int32.max) + XCTAssertEqual(mappedObject?.int32Optional, Int32.max) + XCTAssertEqual(mappedObject?.int32ImplicityUnwrapped, Int32.max) + + XCTAssertEqual(mappedObject?.int64, Int64(Int32.max)) + XCTAssertEqual(mappedObject?.int64Optional, Int64(Int32.max)) + XCTAssertEqual(mappedObject?.int64ImplicityUnwrapped, Int64(Int32.max)) +#endif + + XCTAssertEqual(mappedObject?.uint, UInt.max) + XCTAssertEqual(mappedObject?.uintOptional, UInt.max) + XCTAssertEqual(mappedObject?.uintImplicityUnwrapped, UInt.max) + + XCTAssertEqual(mappedObject?.uint8, 0) + XCTAssertEqual(mappedObject?.uint8Optional, nil) + XCTAssertEqual(mappedObject?.uint8ImplicityUnwrapped, nil) + + XCTAssertEqual(mappedObject?.uint16, 0) + XCTAssertEqual(mappedObject?.uint16Optional, nil) + XCTAssertEqual(mappedObject?.uint16ImplicityUnwrapped, nil) + +#if arch(x86_64) || arch(arm64) + XCTAssertEqual(mappedObject?.uint32, 0) + XCTAssertEqual(mappedObject?.uint32Optional, nil) + XCTAssertEqual(mappedObject?.uint32ImplicityUnwrapped, nil) + + XCTAssertEqual(mappedObject?.uint64, UInt64.max) + XCTAssertEqual(mappedObject?.uint64Optional, UInt64.max) + XCTAssertEqual(mappedObject?.uint64ImplicityUnwrapped, UInt64.max) +#else + XCTAssertEqual(mappedObject?.uint32, UInt32.max) + XCTAssertEqual(mappedObject?.uint32Optional, UInt32.max) + XCTAssertEqual(mappedObject?.uint32ImplicityUnwrapped, UInt32.max) + + XCTAssertEqual(mappedObject?.uint64, UInt64(UInt32.max)) + XCTAssertEqual(mappedObject?.uint64Optional, UInt64(UInt32.max)) + XCTAssertEqual(mappedObject?.uint64ImplicityUnwrapped, UInt64(UInt32.max)) +#endif + } + + func testMappingDoubleFromJSON(){ + let value: Double = 11 + let JSONString = "{\"double\" : \(value), \"doubleOpt\" : \(value), \"doubleImp\" : \(value)}" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.double, value) + XCTAssertEqual(mappedObject?.doubleOptional, value) + XCTAssertEqual(mappedObject?.doubleImplicityUnwrapped, value) + } + + func testMappingFloatFromJSON(){ + let value: Float = 11 + let JSONString = "{\"float\" : \(value), \"floatOpt\" : \(value), \"floatImp\" : \(value)}" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.float, value) + XCTAssertEqual(mappedObject?.floatOptional, value) + XCTAssertEqual(mappedObject?.floatImplicityUnwrapped, value) + } + + func testMappingStringFromJSON(){ + let value: String = "STRINGNGNGG" + let JSONString = "{\"string\" : \"\(value)\", \"stringOpt\" : \"\(value)\", \"stringImp\" : \"\(value)\"}" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.string, value) + XCTAssertEqual(mappedObject?.stringOptional, value) + XCTAssertEqual(mappedObject?.stringImplicityUnwrapped, value) + } + + func testMappingAnyObjectFromJSON(){ + let value1 = "STRING" + let value2: Int = 1234 + let value3: Double = 11.11 + let JSONString = "{\"anyObject\" : \"\(value1)\", \"anyObjectOpt\" : \(value2), \"anyObjectImp\" : \(value3)}" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.anyObject as? String, value1) + XCTAssertEqual(mappedObject?.anyObjectOptional as? Int, value2) + XCTAssertEqual(mappedObject?.anyObjectImplicitlyUnwrapped as? Double, value3) + } + + func testMappingStringFromNSStringJSON(){ + let value: String = "STRINGNGNGG" + let JSONNSString : NSString = "{\"string\" : \"\(value)\", \"stringOpt\" : \"\(value)\", \"stringImp\" : \"\(value)\"}" as NSString + + let mappedObject = mapper.map(JSONString: JSONNSString as String) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.string, value) + XCTAssertEqual(mappedObject?.stringOptional, value) + XCTAssertEqual(mappedObject?.stringImplicityUnwrapped, value) + } + + // MARK: Test mapping Arrays to JSON and back (with basic types in them Bool, Int, Double, Float, String) + + func testMappingBoolArrayFromJSON(){ + let value: Bool = true + let JSONString = "{\"arrayBool\" : [\(value)], \"arrayBoolOpt\" : [\(value)], \"arrayBoolImp\" : [\(value)] }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.arrayBool.first, value) + XCTAssertEqual(mappedObject?.arrayBoolOptional?.first, value) + XCTAssertEqual(mappedObject?.arrayBoolImplicityUnwrapped.first, value) + } + + func testMappingIntArrayFromJSON(){ + let value: Int = 1 + let JSONString = "{\"arrayInt\" : [\(value)], \"arrayIntOpt\" : [\(value)], \"arrayIntImp\" : [\(value)] }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.arrayInt.first, value) + XCTAssertEqual(mappedObject?.arrayIntOptional?.first, value) + XCTAssertEqual(mappedObject?.arrayIntImplicityUnwrapped.first, value) + } + + func testMappingDoubleArrayFromJSON(){ + let value: Double = 1.0 + let JSONString = "{\"arrayDouble\" : [\(value)], \"arrayDoubleOpt\" : [\(value)], \"arrayDoubleImp\" : [\(value)] }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.arrayDouble.first, value) + XCTAssertEqual(mappedObject?.arrayDoubleOptional?.first, value) + XCTAssertEqual(mappedObject?.arrayDoubleImplicityUnwrapped.first, value) + } + + func testMappingFloatArrayFromJSON(){ + let value: Float = 1.001 + let JSONString = "{\"arrayFloat\" : [\(value)], \"arrayFloatOpt\" : [\(value)], \"arrayFloatImp\" : [\(value)] }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.arrayFloat.first, value) + XCTAssertEqual(mappedObject?.arrayFloatOptional?.first, value) + XCTAssertEqual(mappedObject?.arrayFloatImplicityUnwrapped.first, value) + } + + func testMappingStringArrayFromJSON(){ + let value: String = "Stringgggg" + let JSONString = "{\"arrayString\" : [\"\(value)\"], \"arrayStringOpt\" : [\"\(value)\"], \"arrayStringImp\" : [\"\(value)\"] }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.arrayString.first, value) + XCTAssertEqual(mappedObject?.arrayStringOptional?.first, value) + XCTAssertEqual(mappedObject?.arrayStringImplicityUnwrapped.first, value) + } + + func testMappingAnyObjectArrayFromJSON(){ + let value1 = "STRING" + let value2: Int = 1234 + let value3: Double = 11.11 + let JSONString = "{\"arrayAnyObject\" : [\"\(value1)\"], \"arrayAnyObjectOpt\" : [\(value2)], \"arrayAnyObjectImp\" : [\(value3)] }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.arrayAnyObject.first as? String, value1) + XCTAssertEqual(mappedObject?.arrayAnyObjectOptional?.first as? Int, value2) + XCTAssertEqual(mappedObject?.arrayAnyObjectImplicitlyUnwrapped.first as? Double, value3) + } + + // MARK: Test mapping Dictionaries to JSON and back (with basic types in them Bool, Int, Double, Float, String) + + func testMappingBoolDictionaryFromJSON(){ + let key = "key" + let value: Bool = true + let JSONString = "{\"dictBool\" : { \"\(key)\" : \(value)}, \"dictBoolOpt\" : { \"\(key)\" : \(value)}, \"dictBoolImp\" : { \"\(key)\" : \(value)} }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.dictBool[key], value) + XCTAssertEqual(mappedObject?.dictBoolOptional?[key], value) + XCTAssertEqual(mappedObject?.dictBoolImplicityUnwrapped[key], value) + } + + func testMappingIntDictionaryFromJSON(){ + let key = "key" + let value: Int = 11 + let JSONString = "{\"dictInt\" : { \"\(key)\" : \(value)}, \"dictIntOpt\" : { \"\(key)\" : \(value)}, \"dictIntImp\" : { \"\(key)\" : \(value)} }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.dictInt[key], value) + XCTAssertEqual(mappedObject?.dictIntOptional?[key], value) + XCTAssertEqual(mappedObject?.dictIntImplicityUnwrapped[key], value) + } + + func testMappingDoubleDictionaryFromJSON(){ + let key = "key" + let value: Double = 11 + let JSONString = "{\"dictDouble\" : { \"\(key)\" : \(value)}, \"dictDoubleOpt\" : { \"\(key)\" : \(value)}, \"dictDoubleImp\" : { \"\(key)\" : \(value)} }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.dictDouble[key], value) + XCTAssertEqual(mappedObject?.dictDoubleOptional?[key], value) + XCTAssertEqual(mappedObject?.dictDoubleImplicityUnwrapped[key], value) + } + + func testMappingFloatDictionaryFromJSON(){ + let key = "key" + let value: Float = 111.1 + let JSONString = "{\"dictFloat\" : { \"\(key)\" : \(value)}, \"dictFloatOpt\" : { \"\(key)\" : \(value)}, \"dictFloatImp\" : { \"\(key)\" : \(value)} }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.dictFloat[key], value) + XCTAssertEqual(mappedObject?.dictFloatOptional?[key], value) + XCTAssertEqual(mappedObject?.dictFloatImplicityUnwrapped[key], value) + } + + func testMappingStringDictionaryFromJSON(){ + let key = "key" + let value = "value" + let JSONString = "{\"dictString\" : { \"\(key)\" : \"\(value)\"}, \"dictStringOpt\" : { \"\(key)\" : \"\(value)\"}, \"dictStringImp\" : { \"\(key)\" : \"\(value)\"} }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.dictString[key], value) + XCTAssertEqual(mappedObject?.dictStringOptional?[key], value) + XCTAssertEqual(mappedObject?.dictStringImplicityUnwrapped[key], value) + } + + func testMappingAnyObjectDictionaryFromJSON(){ + let key = "key" + let value1 = "STRING" + let value2: Int = 1234 + let value3: Double = 11.11 + let JSONString = "{\"dictAnyObject\" : { \"\(key)\" : \"\(value1)\"}, \"dictAnyObjectOpt\" : { \"\(key)\" : \(value2)}, \"dictAnyObjectImp\" : { \"\(key)\" : \(value3)} }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.dictAnyObject[key] as? String, value1) + XCTAssertEqual(mappedObject?.dictAnyObjectOptional?[key] as? Int, value2) + XCTAssertEqual(mappedObject?.dictAnyObjectImplicitlyUnwrapped[key] as? Double, value3) + } + + func testMappingIntEnumFromJSON(){ + let value: BasicTypes.EnumInt = .Another + let JSONString = "{\"enumInt\" : \(value.rawValue), \"enumIntOpt\" : \(value.rawValue), \"enumIntImp\" : \(value.rawValue) }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.enumInt, value) + XCTAssertEqual(mappedObject?.enumIntOptional, value) + XCTAssertEqual(mappedObject?.enumIntImplicitlyUnwrapped, value) + } + + func testMappingIntEnumFromJSONShouldNotCrashWithNonDefinedvalue() { + let value = Int.min + let JSONString = "{\"enumInt\" : \(value), \"enumIntOpt\" : \(value), \"enumIntImp\" : \(value) }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.enumInt, BasicTypes.EnumInt.Default) + XCTAssertNil(mappedObject?.enumIntOptional) + XCTAssertNil(mappedObject?.enumIntImplicitlyUnwrapped) + } + + func testMappingDoubleEnumFromJSON(){ + let value: BasicTypes.EnumDouble = .Another + let JSONString = "{\"enumDouble\" : \(value.rawValue), \"enumDoubleOpt\" : \(value.rawValue), \"enumDoubleImp\" : \(value.rawValue) }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.enumDouble, value) + XCTAssertEqual(mappedObject?.enumDoubleOptional, value) + XCTAssertEqual(mappedObject?.enumDoubleImplicitlyUnwrapped, value) + } + + func testMappingFloatEnumFromJSON(){ + let value: BasicTypes.EnumFloat = .Another + let JSONString = "{\"enumFloat\" : \(value.rawValue), \"enumFloatOpt\" : \(value.rawValue), \"enumFloatImp\" : \(value.rawValue) }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.enumFloat, value) + XCTAssertEqual(mappedObject?.enumFloatOptional, value) + XCTAssertEqual(mappedObject?.enumFloatImplicitlyUnwrapped, value) + } + + func testMappingStringEnumFromJSON(){ + let value: BasicTypes.EnumString = .Another + let JSONString = "{\"enumString\" : \"\(value.rawValue)\", \"enumStringOpt\" : \"\(value.rawValue)\", \"enumStringImp\" : \"\(value.rawValue)\" }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.enumString, value) + XCTAssertEqual(mappedObject?.enumStringOptional, value) + XCTAssertEqual(mappedObject?.enumStringImplicitlyUnwrapped, value) + } + + func testMappingEnumIntArrayFromJSON(){ + let value: BasicTypes.EnumInt = .Another + let JSONString = "{ \"arrayEnumInt\" : [\(value.rawValue)], \"arrayEnumIntOpt\" : [\(value.rawValue)], \"arrayEnumIntImp\" : [\(value.rawValue)] }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.arrayEnumInt.first, value) + XCTAssertEqual(mappedObject?.arrayEnumIntOptional?.first, value) + XCTAssertEqual(mappedObject?.arrayEnumIntImplicitlyUnwrapped.first, value) + } + + func testMappingEnumIntArrayFromJSONShouldNotCrashWithNonDefinedvalue() { + let value = Int.min + let JSONString = "{ \"arrayEnumInt\" : [\(value)], \"arrayEnumIntOpt\" : [\(value)], \"arrayEnumIntImp\" : [\(value)] }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertNil(mappedObject?.arrayEnumInt.first) + XCTAssertNil(mappedObject?.arrayEnumIntOptional?.first) + XCTAssertNil(mappedObject?.arrayEnumIntImplicitlyUnwrapped.first) + } + + func testMappingEnumIntDictionaryFromJSON(){ + let key = "key" + let value: BasicTypes.EnumInt = .Another + let JSONString = "{ \"dictEnumInt\" : { \"\(key)\" : \(value.rawValue) }, \"dictEnumIntOpt\" : { \"\(key)\" : \(value.rawValue) }, \"dictEnumIntImp\" : { \"\(key)\" : \(value.rawValue) } }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.dictEnumInt[key], value) + XCTAssertEqual(mappedObject?.dictEnumIntOptional?[key], value) + XCTAssertEqual(mappedObject?.dictEnumIntImplicitlyUnwrapped[key], value) + } + + func testMappingEnumIntDictionaryFromJSONShouldNotCrashWithNonDefinedvalue() { + let key = "key" + let value = Int.min + let JSONString = "{ \"dictEnumInt\" : { \"\(key)\" : \(value) }, \"dictEnumIntOpt\" : { \"\(key)\" : \(value) }, \"dictEnumIntImp\" : { \"\(key)\" : \(value) } }" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertNil(mappedObject?.dictEnumInt[key]) + XCTAssertNil(mappedObject?.dictEnumIntOptional?[key]) + XCTAssertNil(mappedObject?.dictEnumIntImplicitlyUnwrapped[key]) + } + + func testObjectModelOptionalDictionnaryOfPrimitives() { + let JSON: [String: [String: Any]] = ["dictStringString":["string": "string"], "dictStringBool":["string": false], "dictStringInt":["string": 1], "dictStringDouble":["string": 1.1], "dictStringFloat":["string": Float(1.2)]] + + let mapper = Mapper() + let testSet: TestCollectionOfPrimitives! = mapper.map(JSON: JSON) + + XCTAssertNotNil(testSet) + + XCTAssertTrue(testSet.dictStringString.count > 0) + XCTAssertTrue(testSet.dictStringInt.count > 0) + XCTAssertTrue(testSet.dictStringBool.count > 0) + XCTAssertTrue(testSet.dictStringDouble.count > 0) + XCTAssertTrue(testSet.dictStringFloat.count > 0) + } +} diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/BasicTypesTestsToJSON.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/BasicTypesTestsToJSON.swift new file mode 100644 index 0000000..74bb702 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/BasicTypesTestsToJSON.swift @@ -0,0 +1,576 @@ +// +// BasicTypesTests.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-12-04. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 +import XCTest +import ObjectMapper + +class BasicTypesTestsToJSON: XCTestCase { + + let mapper = Mapper() + + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } + + // MARK: Test mapping to JSON and back (basic types: Bool, Int, Double, Float, String) + + func testShouldIncludeNilValues(){ + let object = BasicTypes() + + let JSONWithNil = Mapper(shouldIncludeNilValues: true).toJSONString(object, prettyPrint: true) + let JSONWithoutNil = Mapper(shouldIncludeNilValues: false).toJSONString(object, prettyPrint: true) + + //TODO This test could be improved + XCTAssertNotNil(JSONWithNil) + XCTAssertTrue((JSONWithNil!.characters.count) > 5) + XCTAssertTrue((JSONWithNil!.characters.count) != (JSONWithoutNil!.characters.count)) + } + + func testMappingBoolToJSON(){ + let value: Bool = true + let object = BasicTypes() + object.bool = value + object.boolOptional = value + object.boolImplicityUnwrapped = value + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.bool, value) + XCTAssertEqual(mappedObject?.boolOptional, value) + XCTAssertEqual(mappedObject?.boolImplicityUnwrapped, value) + } + + func testMappingIntegerToJSON(){ + let object = BasicTypes() + + object.int = 123 + object.intOptional = 123 + object.intImplicityUnwrapped = 123 + + object.int8 = 123 + object.int8Optional = 123 + object.int8ImplicityUnwrapped = 123 + + object.int16 = 123 + object.int16Optional = 123 + object.int16ImplicityUnwrapped = 123 + + object.int32 = 123 + object.int32Optional = 123 + object.int32ImplicityUnwrapped = 123 + + object.int64 = 123 + object.int64Optional = 123 + object.int64ImplicityUnwrapped = 123 + + object.uint = 123 + object.uintOptional = 123 + object.uintImplicityUnwrapped = 123 + + object.uint8 = 123 + object.uint8Optional = 123 + object.uint8ImplicityUnwrapped = 123 + + object.uint16 = 123 + object.uint16Optional = 123 + object.uint16ImplicityUnwrapped = 123 + + object.uint32 = 123 + object.uint32Optional = 123 + object.uint32ImplicityUnwrapped = 123 + + object.uint64 = 123 + object.uint64Optional = 123 + object.uint64ImplicityUnwrapped = 123 + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + + XCTAssertEqual(mappedObject?.int, 123) + XCTAssertEqual(mappedObject?.intOptional, 123) + XCTAssertEqual(mappedObject?.intImplicityUnwrapped, 123) + + XCTAssertEqual(mappedObject?.int8, 123) + XCTAssertEqual(mappedObject?.int8Optional, 123) + XCTAssertEqual(mappedObject?.int8ImplicityUnwrapped, 123) + + XCTAssertEqual(mappedObject?.int16, 123) + XCTAssertEqual(mappedObject?.int16Optional, 123) + XCTAssertEqual(mappedObject?.int16ImplicityUnwrapped, 123) + + XCTAssertEqual(mappedObject?.int32, 123) + XCTAssertEqual(mappedObject?.int32Optional, 123) + XCTAssertEqual(mappedObject?.int32ImplicityUnwrapped, 123) + + XCTAssertEqual(mappedObject?.int64, 123) + XCTAssertEqual(mappedObject?.int64Optional, 123) + XCTAssertEqual(mappedObject?.int64ImplicityUnwrapped, 123) + + XCTAssertEqual(mappedObject?.uint, 123) + XCTAssertEqual(mappedObject?.uintOptional, 123) + XCTAssertEqual(mappedObject?.uintImplicityUnwrapped, 123) + + XCTAssertEqual(mappedObject?.uint8, 123) + XCTAssertEqual(mappedObject?.uint8Optional, 123) + XCTAssertEqual(mappedObject?.uint8ImplicityUnwrapped, 123) + + XCTAssertEqual(mappedObject?.uint16, 123) + XCTAssertEqual(mappedObject?.uint16Optional, 123) + XCTAssertEqual(mappedObject?.uint16ImplicityUnwrapped, 123) + + XCTAssertEqual(mappedObject?.uint32, 123) + XCTAssertEqual(mappedObject?.uint32Optional, 123) + XCTAssertEqual(mappedObject?.uint32ImplicityUnwrapped, 123) + + XCTAssertEqual(mappedObject?.uint64, 123) + XCTAssertEqual(mappedObject?.uint64Optional, 123) + XCTAssertEqual(mappedObject?.uint64ImplicityUnwrapped, 123) + } + + func testMappingDoubleToJSON(){ + let value: Double = 11 + let object = BasicTypes() + object.double = value + object.doubleOptional = value + object.doubleImplicityUnwrapped = value + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.double, value) + XCTAssertEqual(mappedObject?.doubleOptional, value) + XCTAssertEqual(mappedObject?.doubleImplicityUnwrapped, value) + } + + func testMappingFloatToJSON(){ + let value: Float = 11 + let object = BasicTypes() + object.float = value + object.floatOptional = value + object.floatImplicityUnwrapped = value + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.float, value) + XCTAssertEqual(mappedObject?.floatOptional, value) + XCTAssertEqual(mappedObject?.floatImplicityUnwrapped, value) + } + + func testMappingStringToJSON(){ + let value: String = "STRINGNGNGG" + let object = BasicTypes() + object.string = value + object.stringOptional = value + object.stringImplicityUnwrapped = value + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.string, value) + XCTAssertEqual(mappedObject?.stringOptional, value) + XCTAssertEqual(mappedObject?.stringImplicityUnwrapped, value) + } + + func testMappingAnyObjectToJSON(){ + let value: String = "STRINGNGNGG" + let object = BasicTypes() + object.anyObject = value + object.anyObjectOptional = value + object.anyObjectImplicitlyUnwrapped = value + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.anyObject as? String, value) + XCTAssertEqual(mappedObject?.anyObjectOptional as? String, value) + XCTAssertEqual(mappedObject?.anyObjectImplicitlyUnwrapped as? String, value) + } + + // MARK: Test mapping Arrays to JSON and back (with basic types in them Bool, Int, Double, Float, String) + + func testMappingEmptyArrayToJSON(){ + let object = BasicTypes() + object.arrayBool = [] + object.arrayBoolOptional = [] + object.arrayBoolImplicityUnwrapped = [] + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject!.arrayBool, []) + XCTAssertEqual(mappedObject!.arrayBoolOptional!, []) + XCTAssertEqual(mappedObject!.arrayBoolImplicityUnwrapped, []) + } + + func testMappingBoolArrayToJSON(){ + let value: Bool = true + let object = BasicTypes() + object.arrayBool = [value] + object.arrayBoolOptional = [value] + object.arrayBoolImplicityUnwrapped = [value] + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.arrayBool.first, value) + XCTAssertEqual(mappedObject?.arrayBoolOptional?.first, value) + XCTAssertEqual(mappedObject?.arrayBoolImplicityUnwrapped.first, value) + } + + func testMappingIntArrayToJSON(){ + let value: Int = 1 + let object = BasicTypes() + object.arrayInt = [value] + object.arrayIntOptional = [value] + object.arrayIntImplicityUnwrapped = [value] + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.arrayInt.first, value) + XCTAssertEqual(mappedObject?.arrayIntOptional?.first, value) + XCTAssertEqual(mappedObject?.arrayIntImplicityUnwrapped.first, value) + } + + func testMappingDoubleArrayToJSON(){ + let value: Double = 1.0 + let object = BasicTypes() + object.arrayDouble = [value] + object.arrayDoubleOptional = [value] + object.arrayDoubleImplicityUnwrapped = [value] + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.arrayDouble.first, value) + XCTAssertEqual(mappedObject?.arrayDoubleOptional?.first, value) + XCTAssertEqual(mappedObject?.arrayDoubleImplicityUnwrapped.first, value) + } + + func testMappingFloatArrayToJSON(){ + let value: Float = 1.001 + let object = BasicTypes() + object.arrayFloat = [value] + object.arrayFloatOptional = [value] + object.arrayFloatImplicityUnwrapped = [value] + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.arrayFloat.first, value) + XCTAssertEqual(mappedObject?.arrayFloatOptional?.first, value) + XCTAssertEqual(mappedObject?.arrayFloatImplicityUnwrapped.first, value) + } + + func testMappingStringArrayToJSON(){ + let value: String = "Stringgggg" + let object = BasicTypes() + object.arrayString = [value] + object.arrayStringOptional = [value] + object.arrayStringImplicityUnwrapped = [value] + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.arrayString.first, value) + XCTAssertEqual(mappedObject?.arrayStringOptional?.first, value) + XCTAssertEqual(mappedObject?.arrayStringImplicityUnwrapped.first, value) + } + + func testMappingAnyObjectArrayToJSON(){ + let value: String = "Stringgggg" + let object = BasicTypes() + object.arrayAnyObject = [value] + object.arrayAnyObjectOptional = [value] + object.arrayAnyObjectImplicitlyUnwrapped = [value] + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.arrayAnyObject.first as? String, value) + XCTAssertEqual(mappedObject?.arrayAnyObjectOptional?.first as? String, value) + XCTAssertEqual(mappedObject?.arrayAnyObjectImplicitlyUnwrapped.first as? String, value) + } + + // MARK: Test mapping Dictionaries to JSON and back (with basic types in them Bool, Int, Double, Float, String) + + func testMappingEmptyDictionaryToJSON(){ + let object = BasicTypes() + object.dictBool = [:] + object.dictBoolOptional = [:] + object.dictBoolImplicityUnwrapped = [:] + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject!.dictBool, [:]) + XCTAssertEqual(mappedObject!.dictBoolOptional!, [:]) + XCTAssertEqual(mappedObject!.dictBoolImplicityUnwrapped, [:]) + } + + func testMappingBoolDictionaryToJSON(){ + let key = "key" + let value: Bool = true + let object = BasicTypes() + object.dictBool = [key:value] + object.dictBoolOptional = [key:value] + object.dictBoolImplicityUnwrapped = [key:value] + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.dictBool[key], value) + XCTAssertEqual(mappedObject?.dictBoolOptional?[key], value) + XCTAssertEqual(mappedObject?.dictBoolImplicityUnwrapped[key], value) + } + + func testMappingIntDictionaryToJSON(){ + let key = "key" + let value: Int = 11 + let object = BasicTypes() + object.dictInt = [key:value] + object.dictIntOptional = [key:value] + object.dictIntImplicityUnwrapped = [key:value] + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.dictInt[key], value) + XCTAssertEqual(mappedObject?.dictIntOptional?[key], value) + XCTAssertEqual(mappedObject?.dictIntImplicityUnwrapped[key], value) + } + + func testMappingDoubleDictionaryToJSON(){ + let key = "key" + let value: Double = 11 + let object = BasicTypes() + object.dictDouble = [key:value] + object.dictDoubleOptional = [key:value] + object.dictDoubleImplicityUnwrapped = [key:value] + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.dictDouble[key], value) + XCTAssertEqual(mappedObject?.dictDoubleOptional?[key], value) + XCTAssertEqual(mappedObject?.dictDoubleImplicityUnwrapped[key], value) + } + + func testMappingFloatDictionaryToJSON(){ + let key = "key" + let value: Float = 11 + let object = BasicTypes() + object.dictFloat = [key:value] + object.dictFloatOptional = [key:value] + object.dictFloatImplicityUnwrapped = [key:value] + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.dictFloat[key], value) + XCTAssertEqual(mappedObject?.dictFloatOptional?[key], value) + XCTAssertEqual(mappedObject?.dictFloatImplicityUnwrapped[key], value) + } + + func testMappingStringDictionaryToJSON(){ + let key = "key" + let value = "value" + let object = BasicTypes() + object.dictString = [key:value] + object.dictStringOptional = [key:value] + object.dictStringImplicityUnwrapped = [key:value] + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.dictString[key], value) + XCTAssertEqual(mappedObject?.dictStringOptional?[key], value) + XCTAssertEqual(mappedObject?.dictStringImplicityUnwrapped[key], value) + } + + func testMappingAnyObjectDictionaryToJSON(){ + let key = "key" + let value = "value" + let object = BasicTypes() + object.dictAnyObject = [key:value] + object.dictAnyObjectOptional = [key:value] + object.dictAnyObjectImplicitlyUnwrapped = [key:value] + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.dictAnyObject[key] as? String, value) + XCTAssertEqual(mappedObject?.dictAnyObjectOptional?[key] as? String, value) + XCTAssertEqual(mappedObject?.dictAnyObjectImplicitlyUnwrapped[key] as? String, value) + } + + func testMappingIntEnumToJSON(){ + let value = BasicTypes.EnumInt.Another + let object = BasicTypes() + object.enumInt = value + object.enumIntOptional = value + object.enumIntImplicitlyUnwrapped = value + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.enumInt, value) + XCTAssertEqual(mappedObject?.enumIntOptional, value) + XCTAssertEqual(mappedObject?.enumIntImplicitlyUnwrapped, value) + } + + func testMappingDoubleEnumToJSON(){ + let value = BasicTypes.EnumDouble.Another + let object = BasicTypes() + object.enumDouble = value + object.enumDoubleOptional = value + object.enumDoubleImplicitlyUnwrapped = value + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.enumDouble, value) + XCTAssertEqual(mappedObject?.enumDoubleOptional, value) + XCTAssertEqual(mappedObject?.enumDoubleImplicitlyUnwrapped, value) + } + + func testMappingFloatEnumToJSON(){ + let value = BasicTypes.EnumFloat.Another + let object = BasicTypes() + object.enumFloat = value + object.enumFloatOptional = value + object.enumFloatImplicitlyUnwrapped = value + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.enumFloat, value) + XCTAssertEqual(mappedObject?.enumFloatOptional, value) + XCTAssertEqual(mappedObject?.enumFloatImplicitlyUnwrapped, value) + } + + func testMappingStringEnumToJSON(){ + let value = BasicTypes.EnumString.Another + let object = BasicTypes() + object.enumString = value + object.enumStringOptional = value + object.enumStringImplicitlyUnwrapped = value + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.enumString, value) + XCTAssertEqual(mappedObject?.enumStringOptional, value) + XCTAssertEqual(mappedObject?.enumStringImplicitlyUnwrapped, value) + } + + func testMappingEnumIntArrayToJSON(){ + let value = BasicTypes.EnumInt.Another + let object = BasicTypes() + object.arrayEnumInt = [value] + object.arrayEnumIntOptional = [value] + object.arrayEnumIntImplicitlyUnwrapped = [value] + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.arrayEnumInt.first, value) + XCTAssertEqual(mappedObject?.arrayEnumIntOptional?.first, value) + XCTAssertEqual(mappedObject?.arrayEnumIntImplicitlyUnwrapped.first, value) + } + + func testMappingEnumIntDictionaryToJSON(){ + let key = "key" + let value = BasicTypes.EnumInt.Another + let object = BasicTypes() + object.dictEnumInt = [key: value] + object.dictEnumIntOptional = [key: value] + object.dictEnumIntImplicitlyUnwrapped = [key: value] + + let JSONString = Mapper().toJSONString(object, prettyPrint: true) + let mappedObject = mapper.map(JSONString: JSONString!) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.dictEnumInt[key], value) + XCTAssertEqual(mappedObject?.dictEnumIntOptional?[key], value) + XCTAssertEqual(mappedObject?.dictEnumIntImplicitlyUnwrapped[key], value) + } + + func testObjectToModelDictionnaryOfPrimitives() { + let object = TestCollectionOfPrimitives() + object.dictStringString = ["string": "string"] + object.dictStringBool = ["string": false] + object.dictStringInt = ["string": 1] + object.dictStringDouble = ["string": 1.2] + object.dictStringFloat = ["string": 1.3] + + let json = Mapper().toJSON(object) + + XCTAssertTrue((json["dictStringString"] as? [String:String])?.count ?? 0 > 0) + XCTAssertTrue((json["dictStringBool"] as? [String:Bool])?.count ?? 0 > 0) + XCTAssertTrue((json["dictStringInt"] as? [String:Int])?.count ?? 0 > 0) + XCTAssertTrue((json["dictStringDouble"] as? [String:Double])?.count ?? 0 > 0) + XCTAssertTrue((json["dictStringFloat"] as? [String:Float])?.count ?? 0 > 0) + XCTAssertEqual((json["dictStringString"] as? [String:String])?["string"], "string") + } +} diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/ClassClusterTests.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/ClassClusterTests.swift new file mode 100644 index 0000000..680a5c7 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/ClassClusterTests.swift @@ -0,0 +1,128 @@ +// +// ClassClusterTests.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2015-09-18. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 +import XCTest +import ObjectMapper + +class ClassClusterTests: XCTestCase { + + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } + + func testClassClusters() { + let carName = "Honda" + let JSON = ["name": carName, "type": "car"] + + if let vehicle = Mapper().map(JSON: JSON){ + XCTAssertNotNil(vehicle) + XCTAssertNotNil(vehicle as? Car) + XCTAssertEqual((vehicle as? Car)?.name, carName) + } + } + + func testClassClustersFromJSONString() { + let carName = "Honda" + let JSON = "{\"name\": \"\(carName)\", \"type\": \"car\"}" + + if let vehicle = Mapper().map(JSONString: JSON){ + XCTAssertNotNil(vehicle) + XCTAssertNotNil(vehicle as? Car) + XCTAssertEqual((vehicle as? Car)?.name, carName) + } + } + + func testClassClusterArray() { + let carName = "Honda" + let JSON = [["name": carName, "type": "car"], ["type": "bus"], ["type": "vehicle"]] + + let vehicles = Mapper().mapArray(JSONArray: JSON) + XCTAssertNotNil(vehicles) + XCTAssertTrue(vehicles.count == 3) + XCTAssertNotNil(vehicles[0] as? Car) + XCTAssertNotNil(vehicles[1] as? Bus) + XCTAssertNotNil(vehicles[2]) + XCTAssertEqual((vehicles[0] as? Car)?.name, carName) + } +} + +class Vehicle: StaticMappable { + + var type: String? + + class func objectForMapping(map: Map) -> BaseMappable? { + if let type: String = map["type"].value() { + switch type { + case "car": + return Car() + case "bus": + return Bus() + default: + return Vehicle() + } + } + return nil + } + + init(){ + + } + + func mapping(map: Map) { + type <- map["type"] + } +} + +class Car: Vehicle { + + var name: String? + + override class func objectForMapping(map: Map) -> BaseMappable? { + return nil + } + + override func mapping(map: Map) { + super.mapping(map: map) + + name <- map["name"] + } +} + +class Bus: Vehicle { + + override func mapping(map: Map) { + super.mapping(map: map) + } +} diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/CustomTransformTests.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/CustomTransformTests.swift new file mode 100644 index 0000000..d86fe2c --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/CustomTransformTests.swift @@ -0,0 +1,253 @@ +// +// CustomTransformTests.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2015-03-09. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 +import XCTest +import ObjectMapper + +#if os(iOS) || os(tvOS) || os(watchOS) + typealias TestHexColor = UIColor +#else + typealias TestHexColor = NSColor +#endif + +class CustomTransformTests: XCTestCase { + + let mapper = Mapper() + + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } + + func testDateTransform() { + let transforms = Transforms() + transforms.date = Date(timeIntervalSince1970: 946684800) + transforms.dateOpt = Date(timeIntervalSince1970: 946684912) + + let JSON = mapper.toJSON(transforms) + let parsedTransforms = mapper.map(JSON: JSON) + XCTAssertNotNil(parsedTransforms) + XCTAssertEqual(parsedTransforms?.date, transforms.date) + XCTAssertEqual(parsedTransforms?.dateOpt, transforms.dateOpt) + + let JSONDateString: [String: Any] = ["date": "946684800", "dateOpt": "946684912"] + let parsedTransformsDateString = mapper.map(JSON: JSONDateString) + + XCTAssertNotNil(parsedTransformsDateString) + XCTAssertEqual(parsedTransforms?.date, parsedTransformsDateString?.date) + XCTAssertEqual(parsedTransforms?.dateOpt, parsedTransformsDateString?.dateOpt) + + } + + func testISO8601DateTransform() { + let transforms = Transforms() + transforms.ISO8601Date = Date(timeIntervalSince1970: 1398956159) + transforms.ISO8601DateOpt = Date(timeIntervalSince1970: 1398956159) + let JSON = mapper.toJSON(transforms) + + let parsedTransforms = mapper.map(JSON: JSON) + XCTAssertNotNil(parsedTransforms) + XCTAssertEqual(parsedTransforms?.ISO8601Date, transforms.ISO8601Date) + XCTAssertEqual(parsedTransforms?.ISO8601DateOpt, transforms.ISO8601DateOpt) + } + + func testISO8601DateTransformWithInvalidInput() { + var JSON: [String: Any] = ["ISO8601Date": ""] + let transforms = mapper.map(JSON: JSON) + + XCTAssertNil(transforms?.ISO8601DateOpt) + + JSON["ISO8601Date"] = "incorrect format" + + let transforms2 = mapper.map(JSON: JSON) + + XCTAssertNil(transforms2?.ISO8601DateOpt) + } + + func testCustomFormatDateTransform(){ + let dateString = "2015-03-03T02:36:44" + let JSON: [String: Any] = ["customFormateDate": dateString] + let transform: Transforms! = mapper.map(JSON: JSON) + XCTAssertNotNil(transform) + + let JSONOutput = mapper.toJSON(transform) + + XCTAssertEqual(JSONOutput["customFormateDate"] as? String, dateString) + } + + func testIntToStringTransformOf() { + let intValue = 12345 + let JSON: [String: Any] = ["intWithString": "\(intValue)"] + let transforms = mapper.map(JSON: JSON) + + XCTAssertEqual(transforms?.intWithString, intValue) + } + + func testInt64MaxValue() { + let transforms = Transforms() + transforms.int64Value = INT64_MAX + + let JSON = mapper.toJSON(transforms) + + let parsedTransforms = mapper.map(JSON: JSON) + XCTAssertNotNil(parsedTransforms) + XCTAssertEqual(parsedTransforms?.int64Value, transforms.int64Value) + } + + func testURLTranform() { + let transforms = Transforms() + transforms.URL = URL(string: "http://google.com/image/1234")! + transforms.URLOpt = URL(string: "http://google.com/image/1234") + transforms.URLWithoutEncoding = URL(string: "http://google.com/image/1234#fragment")! + + let JSON = mapper.toJSON(transforms) + + let parsedTransforms = mapper.map(JSON: JSON) + + XCTAssertNotNil(parsedTransforms) + XCTAssertEqual(parsedTransforms?.URL, transforms.URL) + XCTAssertEqual(parsedTransforms?.URLOpt, transforms.URLOpt) + XCTAssertEqual(parsedTransforms?.URLWithoutEncoding, transforms.URLWithoutEncoding) + } + + func testEnumTransform() { + let JSON: [String: Any] = ["firstImageType": "cover", "secondImageType": "thumbnail"] + let transforms = mapper.map(JSON: JSON) + + let imageType = Transforms.ImageType.self + XCTAssertEqual(transforms?.firstImageType, imageType.Cover) + XCTAssertEqual(transforms?.secondImageType, imageType.Thumbnail) + } + + func testHexColorTransform() { + let JSON: [String: Any] = [ + "colorRed": "#FF0000", + "colorGreenLowercase": "#00FF00", + "colorBlueWithoutHash": "0000FF", + "color3lenght": "F00", + "color4lenght": "F00f", + "color8lenght": "ff0000ff" + ] + + let transform = mapper.map(JSON: JSON) + + XCTAssertEqual(transform?.colorRed, TestHexColor.red) + XCTAssertEqual(transform?.colorGreenLowercase, TestHexColor.green) + XCTAssertEqual(transform?.colorBlueWithoutHash, TestHexColor.blue) + XCTAssertEqual(transform?.color3lenght, TestHexColor.red) + XCTAssertEqual(transform?.color4lenght, TestHexColor.red) + XCTAssertEqual(transform?.color8lenght, TestHexColor.red) + + let JSONOutput = mapper.toJSON(transform!) + + XCTAssertEqual(JSONOutput["colorRed"] as? String, "FF0000") + XCTAssertEqual(JSONOutput["colorGreenLowercase"] as? String, "00FF00") + XCTAssertEqual(JSONOutput["colorBlueWithoutHash"] as? String, "#0000FF") // prefixToJSON = true + XCTAssertEqual(JSONOutput["color3lenght"] as? String, "FF0000") + XCTAssertEqual(JSONOutput["color4lenght"] as? String, "FF0000") + XCTAssertEqual(JSONOutput["color8lenght"] as? String, "FF0000FF") // alphaToJSON = true + } +} + +class Transforms: Mappable { + + internal enum ImageType: String { + case Cover = "cover" + case Thumbnail = "thumbnail" + } + + var date = Date() + var dateOpt: Date? + + var ISO8601Date: Date = Date() + var ISO8601DateOpt: Date? + + var customFormatDate = Date() + var customFormatDateOpt: Date? + + var URL = Foundation.URL(string: "") + var URLOpt: Foundation.URL? + var URLWithoutEncoding = Foundation.URL(string: "") + + var intWithString: Int = 0 + + var int64Value: Int64 = 0 + + var firstImageType: ImageType? + var secondImageType: ImageType? + + var colorRed: TestHexColor? + var colorGreenLowercase: TestHexColor? + var colorBlueWithoutHash: TestHexColor? + var color3lenght: TestHexColor? + var color4lenght: TestHexColor? + var color8lenght: TestHexColor? + + init(){ + + } + + required init?(map: Map){ + + } + + func mapping(map: Map) { + date <- (map["date"], DateTransform()) + dateOpt <- (map["dateOpt"], DateTransform()) + + ISO8601Date <- (map["ISO8601Date"], ISO8601DateTransform()) + ISO8601DateOpt <- (map["ISO8601DateOpt"], ISO8601DateTransform()) + + customFormatDate <- (map["customFormateDate"], CustomDateFormatTransform(formatString: "yyyy-MM-dd'T'HH:mm:ss")) + customFormatDateOpt <- (map["customFormateDateOpt"], CustomDateFormatTransform(formatString: "yyyy-MM-dd'T'HH:mm:ss")) + + URL <- (map["URL"], URLTransform()) + URLOpt <- (map["URLOpt"], URLTransform()) + URLWithoutEncoding <- (map["URLWithoutEncoding"], URLTransform(shouldEncodeURLString: false)) + + intWithString <- (map["intWithString"], TransformOf(fromJSON: { $0 == nil ? nil : Int($0!) }, toJSON: { $0.map { String($0) } })) + int64Value <- (map["int64Value"], TransformOf(fromJSON: { $0?.int64Value }, toJSON: { $0.map { NSNumber(value: $0) } })) + + firstImageType <- (map["firstImageType"], EnumTransform()) + secondImageType <- (map["secondImageType"], EnumTransform()) + + colorRed <- (map["colorRed"], HexColorTransform()) + colorGreenLowercase <- (map["colorGreenLowercase"], HexColorTransform()) + colorBlueWithoutHash <- (map["colorBlueWithoutHash"], HexColorTransform(prefixToJSON: true)) + color3lenght <- (map["color3lenght"], HexColorTransform()) + color4lenght <- (map["color4lenght"], HexColorTransform()) + color8lenght <- (map["color8lenght"], HexColorTransform(alphaToJSON: true)) + } +} + diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/DataTransformTests.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/DataTransformTests.swift new file mode 100644 index 0000000..51abbde --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/DataTransformTests.swift @@ -0,0 +1,71 @@ +// +// NSDataTransformTests.swift +// ObjectMapper +// +// Created by Yagrushkin, Evgeny on 8/30/16. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 XCTest +import ObjectMapper + +class DataTransformTests: XCTestCase { + + let mapper = Mapper() + + func testDataTransform() { + + let dataLength = 20 + let bytes = malloc(dataLength) + + let data = Data(bytes: bytes!, count: dataLength) + let dataString = data.base64EncodedString() + let JSONString = "{\"data\" : \"\(dataString)\"}" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.stringData, dataString) + XCTAssertEqual(mappedObject?.data, data) + } + +} + +class DataType: Mappable { + + var data: Data? + var stringData: String? + + init(){ + + } + + required init?(map: Map){ + + } + + func mapping(map: Map) { + stringData <- map["data"] + data <- (map["data"], DataTransform()) + } +} diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/DictionaryTransformTests.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/DictionaryTransformTests.swift new file mode 100644 index 0000000..e3beb42 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/DictionaryTransformTests.swift @@ -0,0 +1,110 @@ +// +// DictionaryTransformTests.swift +// ObjectMapper +// +// Created by Milen Halachev on 7/20/16. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 +import XCTest +import ObjectMapper + +class DictionaryTransformTests: XCTestCase { + + func testDictionaryTransform() { + + let JSON = "{\"dictionary\":{\"1\":{\"foo\":\"uno\",\"bar\":1},\"two\":{\"foo\":\"dve\",\"bar\":2},\"bar\":{\"foo\":\"bar\",\"bar\":777}}}" + + guard let result = DictionaryTransformTestsObject(JSONString: JSON) else { + + XCTFail("Unable to parse the JSON") + return + } + + XCTAssertEqual(result.dictionary.count, 3) + + XCTAssertEqual(result.dictionary[.One]?.foo, "uno") + XCTAssertEqual(result.dictionary[.One]?.bar, 1) + + XCTAssertEqual(result.dictionary[.Two]?.foo, "dve") + XCTAssertEqual(result.dictionary[.Two]?.bar, 2) + + XCTAssertEqual(result.dictionary[.Foo]?.foo, "bar") + XCTAssertEqual(result.dictionary[.Foo]?.bar, 777) + } +} + +class DictionaryTransformTestsObject: Mappable { + + var dictionary: [MyKey: MyValue] = [:] + + required init?(map: Map) { + + + } + + func mapping(map: Map) { + + self.dictionary <- (map["dictionary"], DictionaryTransform()) + } +} + +extension DictionaryTransformTestsObject { + + enum MyKey: String { + + case One = "1" + case Two = "two" + case Foo = "bar" + } +} + +extension DictionaryTransformTestsObject { + + class MyValue: Mappable { + + var foo: String + var bar: Int + + required init?(map: Map) { + + self.foo = "__foo" + self.bar = self.foo.hash + + self.mapping(map: map) + + guard self.foo != "__foo" && self.bar != self.foo.hash else { + + return nil + } + } + + func mapping(map: Map) { + + self.foo <- map["foo"] + self.bar <- map["bar"] + } + } +} + diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/GenericObjectsTests.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/GenericObjectsTests.swift new file mode 100644 index 0000000..787a529 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/GenericObjectsTests.swift @@ -0,0 +1,204 @@ +// +// GenericObjectsTests.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2016-09-26. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 XCTest +import ObjectMapper + +class GenericObjectsTests: XCTestCase { + + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } + + func testSubclass() { + let object = Subclass() + object.base = "base var" + object.sub = "sub var" + + let json = Mapper().toJSON(object) + let parsedObject = Mapper().map(JSON: json) + + XCTAssertEqual(object.base, parsedObject?.base) + XCTAssertEqual(object.sub, parsedObject?.sub) + } + + func testGenericSubclass() { + let object = GenericSubclass() + object.base = "base var" + object.sub = "sub var" + + let json = Mapper().toJSON(object) + let parsedObject = Mapper>().map(JSON: json) + + XCTAssertEqual(object.base, parsedObject?.base) + XCTAssertEqual(object.sub, parsedObject?.sub) + } + + func testSubclassWithGenericArrayInSuperclass() { + let JSONString = "{\"genericItems\":[{\"value\":\"value0\"}, {\"value\":\"value1\"}]}" + + let parsedObject = Mapper>().map(JSONString: JSONString) + + let genericItems = parsedObject?.genericItems + + XCTAssertNotNil(genericItems) + XCTAssertEqual(genericItems?[0].value, "value0") + XCTAssertEqual(genericItems?[1].value, "value1") + } + + + func testMappingAGenericObject(){ + let code: Int = 22 + let JSONString = "{\"result\":{\"code\":\(code)}}" + + let response = Mapper>().map(JSONString: JSONString) + + let status = response?.result?.status + + XCTAssertNotNil(status) + XCTAssertEqual(status, code) + } + + + func testMappingAGenericObjectViaMappableExtension(){ + let code: Int = 22 + let JSONString = "{\"result\":{\"code\":\(code)}}" + + let response = Response(JSONString: JSONString) + + let status = response?.result?.status + + XCTAssertNotNil(status) + XCTAssertEqual(status, code) + } + +} + +class Base: Mappable { + + var base: String? + + init(){ + + } + + required init?(map: Map){ + + } + + func mapping(map: Map) { + base <- map["base"] + } +} + +class Subclass: Base { + + var sub: String? + + override init(){ + super.init() + } + + required init?(map: Map){ + super.init(map: map) + } + + override func mapping(map: Map) { + super.mapping(map: map) + + sub <- map["sub"] + } +} + + +class GenericSubclass: Base { + + var sub: String? + + override init(){ + super.init() + } + + required init?(map: Map){ + super.init(map: map) + } + + override func mapping(map: Map) { + super.mapping(map: map) + + sub <- map["sub"] + } +} + +class WithGenericArray: Mappable { + var genericItems: [T]? + + required init?(map: Map){ + + } + + func mapping(map: Map) { + genericItems <- map["genericItems"] + } +} + +class ConcreteItem: Mappable { + var value: String? + + required init?(map: Map){ + + } + + func mapping(map: Map) { + value <- map["value"] + } +} + +class SubclassWithGenericArrayInSuperclass: WithGenericArray { + required init?(map: Map){ + super.init(map: map) + } +} + +class Response: Mappable { + var result: T? + + required init?(map: Map){ + + } + + func mapping(map: Map) { + result <- map["result"] + } +} diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/IgnoreNilTests.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/IgnoreNilTests.swift new file mode 100644 index 0000000..4db6ae2 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/IgnoreNilTests.swift @@ -0,0 +1,79 @@ +// +// IgnoreNilTests.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2016-06-06. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 XCTest +import ObjectMapper + +class IgnoreNilTests: XCTestCase { + + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } + + func testIgnoreNullField(){ + let name = "Tristan" + var user = User() + user.name = name + + let JSON = "{\"name\" : null}" + user = Mapper().map(JSONString: JSON, toObject: user) + + XCTAssertEqual(user.name, name) + } + + func testIgnoreNilField(){ + let name = "Tristan" + var user = User() + user.name = name + + let JSON = "{\"name\" : nil}" + user = Mapper().map(JSONString: JSON, toObject: user) + + XCTAssertEqual(user.name, name) + } + + private class User: Mappable { + var name: String? + + init(){} + + required init?(map: Map){ + + } + + func mapping(map: Map){ + name <- map["name", ignoreNil: true] + } + } +} diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/ImmutableTests.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/ImmutableTests.swift new file mode 100644 index 0000000..6d87935 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/ImmutableTests.swift @@ -0,0 +1,607 @@ +// +// ImmutableTests.swift +// ObjectMapper +// +// Created by Suyeol Jeon on 23/09/2016. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 +import XCTest +import ObjectMapper + +class ImmutableObjectTests: XCTestCase { + let JSON: [String: Any] = [ + + // Basic types + "prop1": "Immutable!", + "prop2": 255, + "prop3": true, + // prop4 has a default value + + // String + "prop5": "prop5", + "prop6": "prop6", + "prop7": "prop7", + + // [String] + "prop8": ["prop8"], + "prop9": ["prop9"], + "prop10": ["prop10"], + + // [String: String] + "prop11": ["key": "prop11"], + "prop12": ["key": "prop12"], + "prop13": ["key": "prop13"], + + // Base + "prop14": ["base": "prop14"], + "prop15": ["base": "prop15"], + "prop16": ["base": "prop16"], + + // [Base] + "prop17": [["base": "prop17"]], + "prop18": [["base": "prop18"]], + "prop19": [["base": "prop19"]], + + // [String: Base] + "prop20": ["key": ["base": "prop20"]], + "prop21": ["key": ["base": "prop21"]], + "prop22": ["key": ["base": "prop22"]], + + // Optional with immutables + "prop23": "Optional", + "prop24": 255, + "prop25": true, + "prop26": 255.0, + + // RawRepresentable + "prop27a": NSNumber(value: 0), + "prop27b": NSNumber(value: 1000), + "prop27c": [NSNumber(value: 0), NSNumber(value: 1000)], + + "prop28a": Int(0), + "prop28b": Int(255), + "prop28c": [Int(0), Int(255)], + + "prop29a": Double(0), + "prop29b": Double(100), + "prop29c": [Double(0), Double(100)], + + "prop30a": Float(0), + "prop30b": Float(100), + "prop30c": [Float(0), Float(100)], + + "prop31a": "String A", + "prop31b": "String B", + "prop31c": ["String A", "String B"], + + // [[String]] + "prop32": [["prop32"]], + "prop33": [["prop33"]], + "prop34": [["prop34"]], + + // [[Base]] + "prop35": [[["base": "prop35"]]], + "prop36": [[["base": "prop36"]]], + "prop37": [[["base": "prop37"]]], + + "non.nested->key": "string", + "nested": [ + "int": 123, + "string": "hello", + "array": ["a", "b", "c"], + "dictionary": ["a": 10, "b": 20, "c": 30], + ], + "com.hearst.ObjectMapper.nested": [ + "com.hearst.ObjectMapper.int": 123, + "com.hearst.ObjectMapper.string": "hello", + "array": ["a", "b", "c"], + "dictionary": ["a": 10, "b": 20, "c": 30], + ] + ] + + func testImmutableMappable() { + let mapper = Mapper() + + + let immutable: Struct = try! mapper.map(JSON: JSON) + XCTAssertNotNil(immutable) + XCTAssertEqual(immutable.prop1, "Immutable!") + XCTAssertEqual(immutable.prop2, 255) + XCTAssertEqual(immutable.prop3, true) + XCTAssertEqual(immutable.prop4, .greatestFiniteMagnitude) + + XCTAssertEqual(immutable.prop5, "prop5_TRANSFORMED") + XCTAssertEqual(immutable.prop6, "prop6_TRANSFORMED") + XCTAssertEqual(immutable.prop7, "prop7_TRANSFORMED") + + XCTAssertEqual(immutable.prop8, ["prop8_TRANSFORMED"]) + XCTAssertEqual(immutable.prop9!, ["prop9_TRANSFORMED"]) + XCTAssertEqual(immutable.prop10, ["prop10_TRANSFORMED"]) + + XCTAssertEqual(immutable.prop11, ["key": "prop11_TRANSFORMED"]) + XCTAssertEqual(immutable.prop12!, ["key": "prop12_TRANSFORMED"]) + XCTAssertEqual(immutable.prop13, ["key": "prop13_TRANSFORMED"]) + + XCTAssertEqual(immutable.prop14.base, "prop14") + XCTAssertEqual(immutable.prop15?.base, "prop15") + XCTAssertEqual(immutable.prop16.base, "prop16") + + XCTAssertEqual(immutable.prop17[0].base, "prop17") + XCTAssertEqual(immutable.prop18![0].base, "prop18") + XCTAssertEqual(immutable.prop19[0].base, "prop19") + + XCTAssertEqual(immutable.prop20["key"]!.base, "prop20") + XCTAssertEqual(immutable.prop21!["key"]!.base, "prop21") + XCTAssertEqual(immutable.prop22["key"]!.base, "prop22") + + XCTAssertEqual(immutable.prop23!, "Optional") + XCTAssertEqual(immutable.prop24!, 255) + XCTAssertEqual(immutable.prop25!, true) + XCTAssertEqual(immutable.prop26!, 255.0) + + XCTAssertEqual(immutable.prop27a.rawValue, Int64Enum.a.rawValue) + XCTAssertEqual(immutable.prop27b.rawValue, Int64Enum.b.rawValue) + XCTAssertEqual(immutable.prop27c, [Int64Enum.a, Int64Enum.b]) + + XCTAssertEqual(immutable.prop28a.rawValue, IntEnum.a.rawValue) + XCTAssertEqual(immutable.prop28b.rawValue, IntEnum.b.rawValue) + XCTAssertEqual(immutable.prop28c, [IntEnum.a, IntEnum.b]) + + XCTAssertEqual(immutable.prop29a.rawValue, DoubleEnum.a.rawValue) + XCTAssertEqual(immutable.prop29b.rawValue, DoubleEnum.b.rawValue) + XCTAssertEqual(immutable.prop29c, [DoubleEnum.a, DoubleEnum.b]) + + XCTAssertEqual(immutable.prop30a.rawValue, FloatEnum.a.rawValue) + XCTAssertEqual(immutable.prop30b.rawValue, FloatEnum.b.rawValue) + XCTAssertEqual(immutable.prop30c, [FloatEnum.a, FloatEnum.b]) + + XCTAssertEqual(immutable.prop31a.rawValue, StringEnum.A.rawValue) + XCTAssertEqual(immutable.prop31b.rawValue, StringEnum.B.rawValue) + XCTAssertEqual(immutable.prop31c, [StringEnum.A, StringEnum.B]) + + XCTAssertEqual(immutable.prop32[0][0], "prop32_TRANSFORMED") + XCTAssertEqual(immutable.prop33![0][0], "prop33_TRANSFORMED") + XCTAssertEqual(immutable.prop34[0][0], "prop34_TRANSFORMED") + + XCTAssertEqual(immutable.prop35[0][0].base, "prop35") + XCTAssertEqual(immutable.prop36![0][0].base, "prop36") + XCTAssertEqual(immutable.prop37[0][0].base, "prop37") + + XCTAssertEqual(immutable.nonnestedString, "string") + + XCTAssertEqual(immutable.nestedInt, 123) + XCTAssertEqual(immutable.nestedString, "hello") + XCTAssertEqual(immutable.nestedArray, ["a", "b", "c"]) + XCTAssertEqual(immutable.nestedDictionary, ["a": 10, "b": 20, "c": 30]) + + XCTAssertEqual(immutable.delimiterNestedInt, 123) + XCTAssertEqual(immutable.delimiterNestedString, "hello") + XCTAssertEqual(immutable.delimiterNestedArray, ["a", "b", "c"]) + XCTAssertEqual(immutable.delimiterNestedDictionary, ["a": 10, "b": 20, "c": 30]) + + let JSON2: [String: Any] = [ "prop1": "prop1", "prop2": NSNull() ] + let immutable2 = try? mapper.map(JSON: JSON2) + XCTAssertNil(immutable2) + + // TODO: ImmutableMappable to JSON + let JSONFromObject = mapper.toJSON(immutable) + let objectFromJSON = try? mapper.map(JSON: JSONFromObject) + XCTAssertNotNil(objectFromJSON) + assertImmutableObjectsEqual(objectFromJSON!, immutable) + } + + func testMappingFromArray() { + let JSONArray: [[String: Any]] = [JSON] + + let array: [Struct] = try! Mapper().mapArray(JSONArray: JSONArray) + XCTAssertNotNil(array.first) + } + + func testMappingFromDictionary() { + let JSONDictionary: [String: [String: Any]] = [ + "key1": JSON, + "key2": JSON, + ] + + let dictionary: [String: Struct] = try! Mapper().mapDictionary(JSON: JSONDictionary) + XCTAssertNotNil(dictionary.first) + XCTAssertEqual(dictionary.count, 2) + XCTAssertEqual(Set(dictionary.keys), Set(["key1", "key2"])) + } + + func testMappingFromDictionary_empty() { + let JSONDictionary: [String: [String: Any]] = [:] + + let dictionary: [String: Struct] = try! Mapper().mapDictionary(JSON: JSONDictionary) + XCTAssertTrue(dictionary.isEmpty) + } + + func testMappingFromDictionary_throws() { + let JSONDictionary: [String: [String: Any]] = [ + "key1": JSON, + "key2": ["invalid": "dictionary"], + ] + + XCTAssertThrowsError(try Mapper().mapDictionary(JSON: JSONDictionary)) + } + + func testMappingFromDictionaryOfArrays() { + let JSONDictionary: [String: [[String: Any]]] = [ + "key1": [JSON, JSON], + "key2": [JSON], + "key3": [], + ] + + let dictionary: [String: [Struct]] = try! Mapper().mapDictionaryOfArrays(JSON: JSONDictionary) + XCTAssertNotNil(dictionary.first) + XCTAssertEqual(dictionary.count, 3) + XCTAssertEqual(Set(dictionary.keys), Set(["key1", "key2", "key3"])) + XCTAssertEqual(dictionary["key1"]?.count, 2) + XCTAssertEqual(dictionary["key2"]?.count, 1) + XCTAssertEqual(dictionary["key3"]?.count, 0) + } + + func testMappingFromDictionaryOfArrays_empty() { + let JSONDictionary: [String: [[String: Any]]] = [:] + + let dictionary: [String: [Struct]] = try! Mapper().mapDictionaryOfArrays(JSON: JSONDictionary) + XCTAssertTrue(dictionary.isEmpty) + } + + func testMappingFromDictionaryOfArrays_throws() { + let JSONDictionary: [String: [[String: Any]]] = [ + "key1": [JSON], + "key2": [["invalid": "dictionary"]], + ] + + XCTAssertThrowsError(try Mapper().mapDictionaryOfArrays(JSON: JSONDictionary)) + } + + func testMappingArrayOfArrays() { + let JSONArray: [[[String: Any]]] = [ + [JSON, JSON], + [JSON], + [], + ] + let array: [[Struct]] = try! Mapper().mapArrayOfArrays(JSONObject: JSONArray) + XCTAssertNotNil(array.first) + XCTAssertEqual(array.count, 3) + XCTAssertEqual(array[0].count, 2) + XCTAssertEqual(array[1].count, 1) + XCTAssertEqual(array[2].count, 0) + } + + func testMappingArrayOfArrays_empty() { + let JSONArray: [[[String: Any]]] = [] + let array: [[Struct]] = try! Mapper().mapArrayOfArrays(JSONObject: JSONArray) + XCTAssertTrue(array.isEmpty) + } + + func testMappingArrayOfArrays_throws() { + let JSONArray: [[[String: Any]]] = [ + [JSON], + [["invalid": "dictionary"]], + ] + XCTAssertThrowsError(try Mapper().mapArrayOfArrays(JSONObject: JSONArray)) + } + + func testAsPropertyOfMappable() { + struct ImmutableObject: ImmutableMappable { + let value: String + init(map: Map) throws { + self.value = try map.value("value") + } + } + + struct Object: Mappable { + var immutable: ImmutableObject! + init?(map: Map) {} + mutating func mapping(map: Map) { + self.immutable <- map["immutable"] + } + } + + let json: [String: Any] = [ + "immutable": [ + "value": "Hello" + ] + ] + let object = Mapper().map(JSON: json) + XCTAssertEqual(object?.immutable?.value, "Hello") + } + +} + +struct Struct { + let prop1: String + let prop2: Int + let prop3: Bool + let prop4: Double + + let prop5: String + let prop6: String? + let prop7: String! + + let prop8: [String] + let prop9: [String]? + let prop10: [String]! + + let prop11: [String: String] + let prop12: [String: String]? + let prop13: [String: String]! + + let prop14: Base + let prop15: Base? + let prop16: Base! + + let prop17: [Base] + let prop18: [Base]? + let prop19: [Base]! + + let prop20: [String: Base] + let prop21: [String: Base]? + let prop22: [String: Base]! + + // Optionals + var prop23: String? + var prop24: Int? + var prop25: Bool? + var prop26: Double? + + // RawRepresentable + let prop27a: Int64Enum + let prop27b: Int64Enum + let prop27c: [Int64Enum] + + let prop28a: IntEnum + let prop28b: IntEnum + let prop28c: [IntEnum] + + let prop29a: DoubleEnum + let prop29b: DoubleEnum + let prop29c: [DoubleEnum] + + let prop30a: FloatEnum + let prop30b: FloatEnum + let prop30c: [FloatEnum] + + let prop31a: StringEnum + let prop31b: StringEnum + let prop31c: [StringEnum] + + let prop32: [[String]] + let prop33: [[String]]? + let prop34: [[String]]! + + let prop35: [[Base]] + let prop36: [[Base]]? + let prop37: [[Base]]! + + var nonnestedString: String + var nestedInt: Int + var nestedString: String + var nestedArray: [String] + var nestedDictionary: [String: Int] + + var delimiterNestedInt: Int + var delimiterNestedString: String + var delimiterNestedArray: [String] + var delimiterNestedDictionary: [String: Int] +} + +extension Struct: ImmutableMappable { + init(map: Map) throws { + prop1 = try map.value("prop1") + prop2 = try map.value("prop2") + prop3 = try map.value("prop3") + prop4 = (try? map.value("prop4")) ?? .greatestFiniteMagnitude + + prop5 = try map.value("prop5", using: stringTransform) + prop6 = try? map.value("prop6", using: stringTransform) + prop7 = try? map.value("prop7", using: stringTransform) + + prop8 = try map.value("prop8", using: stringTransform) + prop9 = try? map.value("prop9", using: stringTransform) + prop10 = try? map.value("prop10", using: stringTransform) + + prop11 = try map.value("prop11", using: stringTransform) + prop12 = try? map.value("prop12", using: stringTransform) + prop13 = try? map.value("prop13", using: stringTransform) + + prop14 = try map.value("prop14") + prop15 = try? map.value("prop15") + prop16 = try? map.value("prop16") + + prop17 = try map.value("prop17") + prop18 = try? map.value("prop18") + prop19 = try? map.value("prop19") + + prop20 = try map.value("prop20") + prop21 = try? map.value("prop21") + prop22 = try? map.value("prop22") + + prop27a = try map.value("prop27a") + prop27b = try map.value("prop27b") + prop27c = try map.value("prop27c") + + prop28a = try map.value("prop28a") + prop28b = try map.value("prop28b") + prop28c = try map.value("prop28c") + + prop29a = try map.value("prop29a") + prop29b = try map.value("prop29b") + prop29c = try map.value("prop29c") + + prop30a = try map.value("prop30a") + prop30b = try map.value("prop30b") + prop30c = try map.value("prop30c") + + prop31a = try map.value("prop31a") + prop31b = try map.value("prop31b") + prop31c = try map.value("prop31c") + + prop32 = try map.value("prop32", using: stringTransform) + prop33 = try? map.value("prop33", using: stringTransform) + prop34 = try? map.value("prop34", using: stringTransform) + + prop35 = try map.value("prop35") + prop36 = try? map.value("prop36") + prop37 = try? map.value("prop37") + + nonnestedString = try map.value("non.nested->key", nested: false) + + nestedInt = try map.value("nested.int") + nestedString = try map.value("nested.string") + nestedArray = try map.value("nested.array") + nestedDictionary = try map.value("nested.dictionary") + + delimiterNestedInt = try map.value("com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.int", delimiter: "->") + delimiterNestedString = try map.value("com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.string", delimiter: "->") + delimiterNestedArray = try map.value("com.hearst.ObjectMapper.nested->array", delimiter: "->") + delimiterNestedDictionary = try map.value("com.hearst.ObjectMapper.nested->dictionary", delimiter: "->") + } + + mutating func mapping(map: Map) { + prop23 <- map["prop23"] + prop24 <- map["prop24"] + prop25 <- map["prop25"] + prop26 <- map["prop26"] + + prop1 >>> map["prop1"] + prop2 >>> map["prop2"] + prop3 >>> map["prop3"] + prop4 >>> map["prop4"] + + prop5 >>> (map["prop5"], stringTransform) + prop6 >>> (map["prop6"], stringTransform) + prop7 >>> (map["prop7"], stringTransform) + + prop8 >>> (map["prop8"], stringTransform) + prop9 >>> (map["prop9"], stringTransform) + prop10 >>> (map["prop10"], stringTransform) + + prop11 >>> (map["prop11"], stringTransform) + prop12 >>> (map["prop12"], stringTransform) + prop13 >>> (map["prop13"], stringTransform) + + prop14 >>> map["prop14"] + prop15 >>> map["prop15"] + prop16 >>> map["prop16"] + + prop17 >>> map["prop17"] + prop18 >>> map["prop18"] + prop19 >>> map["prop19"] + + prop20 >>> map["prop20"] + prop21 >>> map["prop21"] + prop22 >>> map["prop22"] + + prop27a >>> map["prop27a"] + prop27b >>> map["prop27b"] + prop27c >>> map["prop27c"] + + prop28a >>> map["prop28a"] + prop28b >>> map["prop28b"] + prop28c >>> map["prop28c"] + + prop29a >>> map["prop29a"] + prop29b >>> map["prop29b"] + prop29c >>> map["prop29c"] + + prop30a >>> map["prop30a"] + prop30b >>> map["prop30b"] + prop30c >>> map["prop30c"] + + prop31a >>> map["prop31a"] + prop31b >>> map["prop31b"] + prop31c >>> map["prop31c"] + + prop32 >>> (map["prop32"], stringTransform) + prop33 >>> (map["prop33"], stringTransform) + prop34 >>> (map["prop34"], stringTransform) + + prop35 >>> map["prop35"] + prop36 >>> map["prop36"] + prop37 >>> map["prop37"] + + nonnestedString >>> map["non.nested->key", nested: false] + + nestedInt >>> map["nested.int"] + nestedString >>> map["nested.string"] + nestedArray >>> map["nested.array"] + nestedDictionary >>> map["nested.dictionary"] + + delimiterNestedInt >>> map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.int", delimiter: "->"] + delimiterNestedString >>> map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.string", delimiter: "->"] + delimiterNestedArray >>> map["com.hearst.ObjectMapper.nested->array", delimiter: "->"] + delimiterNestedDictionary >>> map["com.hearst.ObjectMapper.nested->dictionary", delimiter: "->"] + } +} + +let stringTransform = TransformOf( + fromJSON: { (str: String?) -> String? in + guard let str = str else { + return nil + } + return "\(str)_TRANSFORMED" + }, + toJSON: { (str: String?) -> String? in + return str?.replacingOccurrences(of: "_TRANSFORMED", with: "") + } +) + +private func assertImmutableObjectsEqual(_ lhs: Struct, _ rhs: Struct) { + XCTAssertEqual(lhs.prop1, rhs.prop1) + XCTAssertEqual(lhs.prop2, rhs.prop2) + XCTAssertEqual(lhs.prop3, rhs.prop3) + XCTAssertEqual(lhs.prop4, rhs.prop4) + XCTAssertEqual(lhs.prop5, rhs.prop5) + XCTAssertEqual(lhs.prop6, rhs.prop6) + XCTAssertEqual(lhs.prop7, rhs.prop7) + XCTAssertEqual(lhs.prop8, rhs.prop8) + XCTAssertEqual(lhs.prop23, rhs.prop23) + + // @hack: compare arrays and objects with their string representation. + XCTAssertEqual("\(lhs.prop9 as Optional)", "\(rhs.prop9 as Optional)") + XCTAssertEqual("\(lhs.prop10)", "\(rhs.prop10)") + XCTAssertEqual("\(lhs.prop11)", "\(rhs.prop11)") + XCTAssertEqual("\(lhs.prop12 as Optional)", "\(rhs.prop12 as Optional)") + XCTAssertEqual("\(lhs.prop13)", "\(rhs.prop13)") + XCTAssertEqual("\(lhs.prop14)", "\(rhs.prop14)") + XCTAssertEqual("\(lhs.prop15 as Optional)", "\(rhs.prop15 as Optional)") + XCTAssertEqual("\(lhs.prop16)", "\(rhs.prop16)") + XCTAssertEqual("\(lhs.prop17)", "\(rhs.prop17)") + XCTAssertEqual("\(lhs.prop18 as Optional)", "\(rhs.prop18 as Optional)") + XCTAssertEqual("\(lhs.prop19)", "\(rhs.prop19)") + XCTAssertEqual("\(lhs.prop20)", "\(rhs.prop20)") + XCTAssertEqual("\(lhs.prop21 as Optional)", "\(rhs.prop21 as Optional)") + XCTAssertEqual("\(lhs.prop22)", "\(rhs.prop22)") + XCTAssertEqual("\(lhs.prop32)", "\(rhs.prop32)") + XCTAssertEqual("\(lhs.prop33 as Optional)", "\(rhs.prop33 as Optional)") + XCTAssertEqual("\(lhs.prop34)", "\(rhs.prop34)") + XCTAssertEqual("\(lhs.prop35)", "\(rhs.prop35)") + XCTAssertEqual("\(lhs.prop36 as Optional)", "\(rhs.prop36 as Optional)") + XCTAssertEqual("\(lhs.prop37)", "\(rhs.prop37)") +} diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/MapContextTests.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/MapContextTests.swift new file mode 100644 index 0000000..28eb14e --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/MapContextTests.swift @@ -0,0 +1,336 @@ +// +// MapContextTests.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2016-05-10. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 XCTest +import ObjectMapper + +class MapContextTests: XCTestCase { + + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } + + // MARK: - BaseMappable + // MARK: Single + func testMappingWithContext() { + let JSON = ["name": "Tristan"] + let context = Context(shouldMap: true) + + let person = Mapper(context: context).map(JSON: JSON) + + XCTAssertNotNil(person) + XCTAssertNotNil(person?.name) + } + + func testMappingWithContextViaMappableExtension() { + let JSON = ["name": "Tristan"] + let context = Context(shouldMap: true) + + let person = Person(JSON: JSON, context: context) + + XCTAssertNotNil(person) + XCTAssertNotNil(person?.name) + } + + func testMappingWithoutContext() { + let JSON = ["name": "Tristan"] + + let person = Mapper().map(JSON: JSON) + + XCTAssertNotNil(person) + XCTAssertNil(person?.name) + } + + // MARK: Nested + func testNestedMappingWithContext() { + let JSON = ["person": ["name": "Tristan"]] + let context = Context(shouldMap: true) + + let nestedPerson = Mapper(context: context).map(JSON: JSON) + + XCTAssertNotNil(nestedPerson) + XCTAssertNotNil(nestedPerson?.person?.name) + } + + func testNestedMappingWithContextViaMappableExtension() { + let JSON = ["person": ["name": "Tristan"]] + let context = Context(shouldMap: true) + + let nestedPerson = NestedPerson(JSON: JSON, context: context) + + XCTAssertNotNil(nestedPerson) + XCTAssertNotNil(nestedPerson?.person?.name) + } + + func testNestedMappingWithoutContext() { + let JSON = ["person": ["name": "Tristan"]] + + let nestedPerson = Mapper().map(JSON: JSON) + + XCTAssertNotNil(nestedPerson) + XCTAssertNil(nestedPerson?.person?.name) + } + + // MARK: Array + func testArrayMappingWithContext() { + let JSON = ["persons": [["name": "Tristan"], ["name": "Anton"]]] + let context = Context(shouldMap: true) + + let person = Mapper(context: context).map(JSON: JSON) + + XCTAssertNotNil(person) + XCTAssertNotNil(person?.persons) + } + + func testArrayMappingWithContextViaMappableExtension() { + let JSON = ["persons": [["name": "Tristan"], ["name": "Anton"]]] + let context = Context(shouldMap: true) + + let person = PersonList(JSON: JSON, context: context) + + XCTAssertNotNil(person) + XCTAssertNotNil(person?.persons) + } + + func testArrayMappingWithoutContext() { + let JSON = ["persons": [["name": "Tristan"], ["name": "Anton"]]] + + let person = Mapper().map(JSON: JSON) + + XCTAssertNotNil(person) + XCTAssertNil(person?.persons) + } + + // MARK: ImmutableMappable + // MARK: Single + func testImmatableMappingWithContext() { + let JSON = ["name": "Anton"] + let context = ImmutableContext(isDeveloper: true) + + let person = try? Mapper(context: context).map(JSON: JSON) + + XCTAssertNotNil(person) + + XCTAssertEqual(person?.isDeveloper ?? !context.isDeveloper, context.isDeveloper) + } + + func testImmatableMappingWithContextViaMappableExtension() { + let JSON = ["name": "Anton"] + let context = ImmutableContext(isDeveloper: true) + + let person = try? ImmutablePerson(JSON: JSON, context: context) + + XCTAssertNotNil(person) + XCTAssertEqual(person?.isDeveloper ?? !context.isDeveloper, context.isDeveloper) + } + + func testImmatableMappingWithoutContext() { + let JSON = ["name": "Anton"] + + do { + let _ = try Mapper().map(JSON: JSON) + } catch ImmutablePersonMappingError.contextAbsense { + // Empty + } catch { + XCTFail() + } + } + + // MARK: Nested + func testNestedImmutableMappingWithContext() { + let JSON = ["person": ["name": "Anton"]] + let context = ImmutableContext(isDeveloper: true) + + let nestedPerson = try? Mapper(context: context).map(JSON: JSON) + + XCTAssertNotNil(nestedPerson) + XCTAssertEqual(nestedPerson?.person.isDeveloper ?? !context.isDeveloper, context.isDeveloper) + } + + func testNestedImmutableMappingWithContextViaMappableExtension() { + let JSON = ["person": ["name": "Anton"]] + let context = ImmutableContext(isDeveloper: true) + + let nestedPerson = try? ImmutableNestedPerson(JSON: JSON, context: context) + + XCTAssertNotNil(nestedPerson) + XCTAssertEqual(nestedPerson?.person.isDeveloper ?? !context.isDeveloper, context.isDeveloper) + } + + func testNestedImmutableMappingWithoutContext() { + let JSON = ["person": ["name": "Anton"]] + + do { + let _ = try Mapper().map(JSON: JSON) + } catch ImmutablePersonMappingError.contextAbsense { + return + } catch { + XCTFail() + } + + XCTFail() + } + + // MARK: Array + func testArrayImmutableMappingWithContext() { + let JSON = ["persons": [["name": "Tristan"], ["name": "Anton"]]] + let context = ImmutableContext(isDeveloper: true) + + let personList = try? Mapper(context: context).map(JSON: JSON) + + XCTAssertNotNil(personList) + + personList?.persons.forEach { person in + XCTAssertEqual(person.isDeveloper, context.isDeveloper) + } + } + + func testArrayImmutableMappingWithContextViaMappableExtension() { + let JSON = ["persons": [["name": "Tristan"], ["name": "Anton"]]] + let context = ImmutableContext(isDeveloper: true) + + let personList = try? ImmutablePersonList(JSON: JSON, context: context) + + XCTAssertNotNil(personList) + + personList?.persons.forEach { person in + XCTAssertEqual(person.isDeveloper, context.isDeveloper) + } + } + + func testArrayImmutableMappingWithoutContext() { + let JSON = ["persons": [["name": "Tristan"], ["name": "Anton"]]] + + do { + let _ = try Mapper().map(JSON: JSON) + } catch ImmutablePersonMappingError.contextAbsense { + return + } catch { + XCTFail() + } + + XCTFail() + } + + // MARK: - Nested Types + // MARK: BaseMappable + struct Context: MapContext { + var shouldMap = false + + init(shouldMap: Bool){ + self.shouldMap = shouldMap + } + } + + class Person: Mappable { + var name: String? + + required init?(map: Map){ + + } + + func mapping(map: Map) { + if (map.context as? Context)?.shouldMap == true { + name <- map["name"] + } + } + } + + class NestedPerson: Mappable { + var person: Person? + + required init?(map: Map){ + + } + + func mapping(map: Map) { + if (map.context as? Context)?.shouldMap == true { + person <- map["person"] + } + } + } + + class PersonList: Mappable { + var persons: [Person]? + + required init?(map: Map){ + + } + + func mapping(map: Map) { + if (map.context as? Context)?.shouldMap == true { + persons <- map["persons"] + } + } + } + + // MARK: ImmutableMappable + struct ImmutableContext: MapContext { + let isDeveloper: Bool + } + + enum ImmutablePersonMappingError: Error { + case contextAbsense + } + + struct ImmutablePerson: ImmutableMappable { + let name: String + let isDeveloper: Bool + + init(map: Map) throws { + guard let context = map.context as? ImmutableContext else { + throw ImmutablePersonMappingError.contextAbsense + } + + name = try map.value("name") + isDeveloper = context.isDeveloper + } + } + + struct ImmutableNestedPerson: ImmutableMappable { + let person: ImmutablePerson + + init(map: Map) throws { + person = try map.value("person") + } + } + + struct ImmutablePersonList: ImmutableMappable { + let persons: [ImmutablePerson] + + init(map: Map) throws { + persons = try map.value("persons") + } + } +} diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/MappableExtensionsTests.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/MappableExtensionsTests.swift new file mode 100644 index 0000000..2d19a6e --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/MappableExtensionsTests.swift @@ -0,0 +1,105 @@ +// +// MappableExtensionsTests.swift +// ObjectMapper +// +// Created by Scott Hoyt on 10/25/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 +import XCTest +import ObjectMapper + +struct TestMappable: Mappable, Equatable, Hashable { + static let valueForString = "This string should work" + static let workingJSONString = "{ \"value\" : \"\(valueForString)\" }" + static let workingJSON: [String: Any] = ["value": valueForString] + static let workingJSONArrayString = "[\(workingJSONString)]" + + var value: String? + + init() {} + init?(map: Map) { } + + mutating func mapping(map: Map) { + value <- map["value"] + } + + var hashValue: Int { + if let value = value { + return value.hashValue + } + return NSIntegerMax + } +} + +func ==(lhs: TestMappable, rhs: TestMappable) -> Bool { + return lhs.value == rhs.value +} + +class MappableExtensionsTests: XCTestCase { + + var testMappable: TestMappable! + + override func setUp() { + super.setUp() + testMappable = TestMappable() + testMappable.value = TestMappable.valueForString + } + + func testInitFromString() { + let mapped = TestMappable(JSONString: TestMappable.workingJSONString) + + XCTAssertNotNil(mapped) + XCTAssertEqual(mapped?.value, TestMappable.valueForString) + } + + func testToJSONAndBack() { + let mapped = TestMappable(JSON: testMappable.toJSON()) + XCTAssertEqual(mapped, testMappable) + } + + func testArrayFromString() { + let mapped = [TestMappable](JSONString: TestMappable.workingJSONArrayString)! + XCTAssertEqual(mapped, [testMappable]) + } + + func testArrayToJSONAndBack() { + let mapped = [TestMappable](JSONArray: [testMappable].toJSON()) + XCTAssertEqual(mapped, [testMappable]) + } + + func testSetInitFailsWithEmptyString() { + XCTAssertNil(Set(JSONString: "")) + } + + func testSetFromString() { + let mapped = Set(JSONString: TestMappable.workingJSONArrayString)! + XCTAssertEqual(mapped, Set([testMappable])) + } + + func testSetToJSONAndBack() { + let mapped = Set(JSONArray: Set([testMappable]).toJSON()) + XCTAssertEqual(mapped, [testMappable]) + } +} diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/MappableTypesWithTransformsTests.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/MappableTypesWithTransformsTests.swift new file mode 100644 index 0000000..75de412 --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/MappableTypesWithTransformsTests.swift @@ -0,0 +1,343 @@ +// +// MappableTypesWithTransformsTests.swift +// ObjectMapper +// +// Created by Paddy O'Brien on 2015-12-04. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 XCTest +import ObjectMapper + + +class MappableTypesWithTransformsTests: XCTestCase { + // This is a func so that it can be collapsed + func JSONPayload() -> [String: Any] { + return [ + "teams": [[ + "api_uri": "/teams/8", + "full_name": "Team Secret", + "short_name": "Secret", + "players": ["/players/1", "/players/2", "/players/3", "/players/4", "/players/5"] + ], [ + "api_uri": "/teams/43", + "full_name": "Mineski", + "short_name": "Mski", + "players": ["/players/6", "/players/7", "/players/8", "/players/9", "/players/10"] + ]], + "game": [ + "api_uri": "/games/2723", + "game_time": "33:49", + "players": [ + ["/players/1", "/players/2", "/players/3", "/players/4", "/players/5"], + ["/players/6", "/players/7", "/players/8", "/players/9", "/players/10"] + ], + "team1_lineup": [ + "top": "/players/1", + "mid": "/players/2", + "bottom": "/players/3", + "support": "/players/4", + "carry": "/players/5" + ], + "team2_lineup": [ + "top": "/players/6", + "mid": "/players/7", + "bottom": "/players/8", + "support": "/players/9", + "carry": "/players/10" + ], + "head_to_head": [ + "top": ["/players/1", "/players/6"], + "mid": ["/players/2", "/players/7"], + "bottom": ["/players/3", "/players/8"], + "support": ["/players/4", "/players/9"], + "carry": ["/players/5", "/players/10"] + ], + "teams": ["/teams/43", "/teams/8"], + "winning_team_url": "/teams/8" + ] + ] + } + + + // MARK: - Non-Optional Tests + func testParsingSingleInstanceWithTransform() { + let game = Mapper().map(JSONObject: JSONPayload()["game"]) + + XCTAssertNotNil(game) + XCTAssertNotEqual(game!.winner.URI, "FAKE") + } + + func testParsingArrayOfObjectsWithTransform() { + let teams = Mapper().mapArray(JSONObject: JSONPayload()["teams"]) + + XCTAssertNotNil(teams) + XCTAssertNotEqual(teams!.count, 0) + + XCTAssertNotEqual(teams!.first!.players.count, 0) + } + + func testParsing2DimensionalArrayOfObjectsWithTransform() { + let game = Mapper().map(JSONObject: JSONPayload()["game"]) + + XCTAssertNotNil(game) + XCTAssertNotEqual(game!.players.count, 0) + XCTAssertNotEqual(game!.players.first!.count, 0) + XCTAssertNotEqual(game!.players.last!.count, 0) + } + + func testParsingDictionaryOfObjectsWithTransform() { + let game = Mapper().map(JSONObject: JSONPayload()["game"]) + + XCTAssertNotNil(game) + XCTAssertNotEqual(game!.team1Lineup.count, 0) + XCTAssertNotEqual(game!.team2Lineup.count, 0) + } + + func testParsingDictionaryOfArrayOfObjectsWithTransform() { + let game = Mapper().map(JSONObject: JSONPayload()["game"]) + + XCTAssertNotNil(game) + for (position, players) in game!.headToHead { + XCTAssertNotEqual(players.count, 0, "No players were mapped for \(position)") + } + } + + func testParsingSetOfObjectsWithTransform() { + let game = Mapper().map(JSONObject: JSONPayload()["game"]) + + XCTAssertNotNil(game) + XCTAssertNotEqual(game!.teams.count, 0) + } + + + // MARK: - Optional Tests + func testParsingOptionalSingleInstanceWithTransform() { + let game = Mapper().map(JSONObject: JSONPayload()["game"]) + + XCTAssertNotNil(game) + XCTAssertNotNil(game!.O_winner) + } + + func testParsingOptionalArrayOfObjectsWithTransform() { + let teams = Mapper().mapArray(JSONObject: JSONPayload()["teams"]) + + XCTAssertNotNil(teams) + XCTAssertNotEqual(teams!.count, 0) + + XCTAssertNotNil(teams!.first!.O_players) + XCTAssertNotEqual(teams!.first!.O_players!.count, 0) + } + + func testParsingOptional2DimensionalArrayOfObjectsWithTransform() { + let game = Mapper().map(JSONObject: JSONPayload()["game"]) + + XCTAssertNotNil(game) + XCTAssertNotNil(game!.O_players) + XCTAssertNotEqual(game!.O_players!.count, 0) + XCTAssertNotEqual(game!.O_players!.first!.count, 0) + XCTAssertNotEqual(game!.O_players!.last!.count, 0) + } + + func testParsingOptionalDictionaryOfObjectsWithTransform() { + let game = Mapper().map(JSONObject: JSONPayload()["game"]) + + XCTAssertNotNil(game) + XCTAssertNotNil(game!.O_team1Lineup) + XCTAssertNotEqual(game!.O_team1Lineup!.count, 0) + XCTAssertNotNil(game!.O_team2Lineup) + XCTAssertNotEqual(game!.O_team2Lineup!.count, 0) + } + + func testParsingOptionalDictionaryOfArrayOfObjectsWithTransform() { + let game = Mapper().map(JSONObject: JSONPayload()["game"]) + + XCTAssertNotNil(game) + XCTAssertNotNil(game!.O_headToHead) + for (position, players) in game!.O_headToHead! { + XCTAssertNotEqual(players.count, 0, "No players were mapped for \(position)") + } + } + + func testParsingOptionalSetOfObjectsWithTransform() { + let game = Mapper().map(JSONObject: JSONPayload()["game"]) + + XCTAssertNotNil(game) + XCTAssertNotNil(game!.O_teams) + XCTAssertNotEqual(game!.O_teams!.count, 0) + } + + // MARK: - Implicitly Unwrapped Optional Tests + func testParsingImplicitlyUnwrappedSingleInstanceWithTransform() { + let game = Mapper().map(JSONObject: JSONPayload()["game"]) + + XCTAssertNotNil(game) + XCTAssertNotNil(game!.I_winner) + } + + func testParsingImplicitlyUnwrappedArrayOfObjectsWithTransform() { + let teams = Mapper().mapArray(JSONObject: JSONPayload()["teams"]) + + XCTAssertNotNil(teams) + XCTAssertNotEqual(teams!.count, 0) + + XCTAssertNotNil(teams!.first!.I_players) + XCTAssertNotEqual(teams!.first!.I_players!.count, 0) + } + + func testParsingImplicitlyUnwrapped2DimensionalArrayOfObjectsWithTransform() { + let game = Mapper().map(JSONObject: JSONPayload()["game"]) + + XCTAssertNotNil(game) + XCTAssertNotNil(game!.I_players) + XCTAssertNotEqual(game!.I_players!.count, 0) + XCTAssertNotEqual(game!.I_players!.first!.count, 0) + XCTAssertNotEqual(game!.I_players!.last!.count, 0) + } + + func testParsingImplicitlyUnwrappedDictionaryOfObjectsWithTransform() { + let game = Mapper().map(JSONObject: JSONPayload()["game"]) + + XCTAssertNotNil(game) + XCTAssertNotNil(game!.I_team1Lineup) + XCTAssertNotEqual(game!.I_team1Lineup!.count, 0) + XCTAssertNotNil(game!.I_team2Lineup) + XCTAssertNotEqual(game!.I_team2Lineup!.count, 0) + } + + func testParsingImplicitlyUnwrappedDictionaryOfArrayOfObjectsWithTransform() { + let game = Mapper().map(JSONObject: JSONPayload()["game"]) + + XCTAssertNotNil(game) + XCTAssertNotNil(game!.I_headToHead) + for (position, players) in game!.I_headToHead! { + XCTAssertNotEqual(players.count, 0, "No players were mapped for \(position)") + } + } + + func testParsingImplicitlyUnwrappedSetOfObjectsWithTransform() { + let game = Mapper().map(JSONObject: JSONPayload()["game"]) + + XCTAssertNotNil(game) + XCTAssertNotNil(game!.I_teams) + XCTAssertNotEqual(game!.I_teams!.count, 0) + } + + // MARK: - Internal classes for testing + class Game: Mappable, URIInitiable { + var URI: String? + var players: [[Player]] = [[]] + var team1Lineup: [String: Player] = [:] + var team2Lineup: [String: Player] = [:] + var headToHead: [String: [Player]] = [:] + var teams: Set = [] + var winner: Team = Team(URI: "FAKE") + + // Optional + var O_players: [[Player]]? + var O_team1Lineup: [String: Player]? + var O_team2Lineup: [String: Player]? + var O_headToHead: [String: [Player]]? + var O_teams: Set? + var O_winner: Team? + + // Implicitly Unwrapped + var I_players: [[Player]]! + var I_team1Lineup: [String: Player]! + var I_team2Lineup: [String: Player]! + var I_headToHead: [String: [Player]]! + var I_teams: Set! + var I_winner: Team! + + required init(URI: String) { self.URI = URI } + required init?(map: Map) {} + + func mapping(map: Map) { + players <- (map["players"], RelationshipTransform()) // 2D Array with transform + team1Lineup <- (map["team1_lineup"], RelationshipTransform()) // Dictionary with transform + team2Lineup <- (map["team1_lineup"], RelationshipTransform()) + headToHead <- (map["head_to_head"], RelationshipTransform()) // Dictionary of arrays with transform + teams <- (map["teams"], RelationshipTransform()) // Set with transform + winner <- (map["winning_team_url"], RelationshipTransform()) // Single instance with transform + + // Optional + O_players <- (map["players"], RelationshipTransform()) + O_team1Lineup <- (map["team1_lineup"], RelationshipTransform()) + O_team2Lineup <- (map["team1_lineup"], RelationshipTransform()) + O_headToHead <- (map["head_to_head"], RelationshipTransform()) + O_teams <- (map["teams"], RelationshipTransform()) + O_winner <- (map["winning_team_url"], RelationshipTransform()) + + // Implicitly Unwrapped + I_players <- (map["players"], RelationshipTransform()) + I_team1Lineup <- (map["team1_lineup"], RelationshipTransform()) + I_team2Lineup <- (map["team1_lineup"], RelationshipTransform()) + I_headToHead <- (map["head_to_head"], RelationshipTransform()) + I_teams <- (map["teams"], RelationshipTransform()) + I_winner <- (map["winning_team_url"], RelationshipTransform()) + } + } + + class Team: NSObject, Mappable, URIInitiable { + var URI: String? + var players: [Player] = [] + var O_players: [Player]? + var I_players: [Player]? + + required init(URI: String) { self.URI = URI } + required init?(map: Map) {} + + func mapping(map: Map) { + players <- (map["players"], RelationshipTransform()) + O_players <- (map["players"], RelationshipTransform()) + I_players <- (map["players"], RelationshipTransform()) + } + } + + class Player: Mappable, URIInitiable { + required init(URI: String) {} + required init?(map: Map) {} + + func mapping(map: Map) {} + } +} + +protocol URIInitiable { + init(URI: String) +} + +class RelationshipTransform: TransformType where ObjectType: Mappable & URIInitiable { + typealias Object = ObjectType + typealias JSON = [String: AnyObject] + + func transformFromJSON(_ value: Any?) -> Object? { + guard let URI = value as? String else { return nil } + let relation = ObjectType(URI: URI) + + return relation + } + + func transformToJSON(_ value: Object?) -> JSON? { + return nil + } +} diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/NSDecimalNumberTransformTests.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/NSDecimalNumberTransformTests.swift new file mode 100644 index 0000000..f53ed7a --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/NSDecimalNumberTransformTests.swift @@ -0,0 +1,86 @@ +// +// NestedArrayTests.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 10/21/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 XCTest +import ObjectMapper + +class NSDecimalNumberTransformTests: XCTestCase { + + let mapper = Mapper() + + func testNSDecimalNumberTransform() { + let int: Int = 11 + let double: Double = 11.11 + /* Cannot use a float literal (eg: `let decimal: Decimal = 1.66`) as this transforms the value from 1.66 to 1.6599999999999995904 */ + let decimal = Decimal(string: "1.66")! + let intString = "11" + let doubleString = "11.11" + let decimalString = "1.66" + let JSONString = "{\"double\" : \(doubleString), \"int\" : \(intString), \"decimal\" : \(decimalString), \"intString\" : \"\(intString)\", \"doubleString\" : \"\(doubleString)\", \"decimalString\" : \"\(decimalString)\"}" + + let mappedObject = mapper.map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.int, NSDecimalNumber(value: int)) + XCTAssertEqual(mappedObject?.double, NSDecimalNumber(value: double)) + XCTAssertEqual(mappedObject?.decimal, NSDecimalNumber(decimal: decimal)) + XCTAssertEqual(mappedObject?.intString, NSDecimalNumber(string: intString)) + XCTAssertEqual(mappedObject?.doubleString, NSDecimalNumber(string: doubleString)) + XCTAssertEqual(mappedObject?.decimalString, NSDecimalNumber(string: decimalString)) + XCTAssertEqual(mappedObject?.int?.stringValue, intString) + XCTAssertEqual(mappedObject?.double?.stringValue, doubleString) + XCTAssertEqual(mappedObject?.decimal?.stringValue, decimalString) + } +} + +class NSDecimalNumberType: Mappable { + + var int: NSDecimalNumber? + var double: NSDecimalNumber? + var decimal: NSDecimalNumber? + var intString: NSDecimalNumber? + var doubleString: NSDecimalNumber? + var decimalString: NSDecimalNumber? + + init(){ + + } + + required init?(map: Map){ + + } + + func mapping(map: Map) { + int <- (map["int"], NSDecimalNumberTransform()) + double <- (map["double"], NSDecimalNumberTransform()) + decimal <- (map["decimal"], NSDecimalNumberTransform()) + intString <- (map["intString"], NSDecimalNumberTransform()) + doubleString <- (map["doubleString"], NSDecimalNumberTransform()) + decimalString <- (map["decimalString"], NSDecimalNumberTransform()) + } +} diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/NestedArrayTests.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/NestedArrayTests.swift new file mode 100644 index 0000000..640437d --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/NestedArrayTests.swift @@ -0,0 +1,105 @@ +// +// NestedArrayTests.swift +// ObjectMapper +// +// Created by Ruben Samsonyan on 10/21/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 +import XCTest +import ObjectMapper + +class NestedArrayTests: XCTestCase { + + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } + + func testNestedArray() { + let JSON: [String: Any] = [ "nested": [ ["value": 123], ["value": 456] ] ] + + let mapper = Mapper() + + let value: NestedArray! = mapper.map(JSON: JSON) + XCTAssertNotNil(value) + + let JSONFromValue = mapper.toJSON(value) + let valueFromParsedJSON: NestedArray! = mapper.map(JSON: JSONFromValue) + XCTAssertNotNil(valueFromParsedJSON) + + XCTAssertEqual(value.value_0, valueFromParsedJSON.value_0) + XCTAssertEqual(value.value_1, valueFromParsedJSON.value_1) + } + + func testNestedObjectArray() { + let value = 456 + let JSON: [String: Any] = [ "nested": [ ["value": 123], ["value": value] ] ] + + let mapper = Mapper() + + let mappedObject: NestedArray! = mapper.map(JSON: JSON) + XCTAssertNotNil(mappedObject) + + XCTAssertEqual(mappedObject.nestedObject!.value, value) + XCTAssertEqual(mappedObject.nestedObjectValue, value) + } +} + +class NestedArray: Mappable { + + var value_0: Int? + var value_1: Int? + + var nestedObject: NestedObject? + + var nestedObjectValue: Int? + + required init?(map: Map){ + + } + + func mapping(map: Map) { + value_0 <- map["nested.0.value"] + value_1 <- map["nested.1.value"] + + nestedObject <- map["nested.1"] + nestedObjectValue <- map["nested.1.value"] + } +} + +class NestedObject: Mappable { + var value: Int? + + required init?(map: Map){} + + func mapping(map: Map) { + value <- map["value"] + } +} diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/NestedKeysTests.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/NestedKeysTests.swift new file mode 100644 index 0000000..bd33d4e --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/NestedKeysTests.swift @@ -0,0 +1,401 @@ +// +// NestedKeysTests.swift +// ObjectMapper +// +// Created by Syo Ikeda on 3/10/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 +import XCTest +import ObjectMapper + +class NestedKeysTests: XCTestCase { + + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } + + func testNestedKeys() { + let JSON: [String: Any] = [ + "non.nested.key": "string", + "nested": [ + "int64": NSNumber(value: INT64_MAX), + "bool": true, + "int": 255, + "double": 100.0 as Double, + "float": 50.0 as Float, + "string": "String!", + + "nested": [ + "int64Array": [NSNumber(value: INT64_MAX), NSNumber(value: INT64_MAX - 1), NSNumber(value: INT64_MAX - 10)], + "boolArray": [false, true, false], + "intArray": [1, 2, 3], + "doubleArray": [1.0, 2.0, 3.0], + "floatArray": [1.0 as Float, 2.0 as Float, 3.0 as Float], + "stringArray": ["123", "ABC"], + + "int64Dict": ["1": NSNumber(value: INT64_MAX)], + "boolDict": ["2": true], + "intDict": ["3": 999], + "doubleDict": ["4": 999.999], + "floatDict": ["5": 123.456 as Float], + "stringDict": ["6": "InDict"], + + "int64Enum": 1000, + "intEnum": 255, + "doubleEnum": 100.0, + "floatEnum": 100.0, + "stringEnum": "String B", + + "nested": [ + "object": ["value": 987], + "objectArray": [ ["value": 123], ["value": 456] ], + "objectDict": ["key": ["value": 999]] + ] + ] + ] + ] + + let mapper = Mapper() + + let value: NestedKeys! = mapper.map(JSONObject: JSON) + XCTAssertNotNil(value) + + let JSONFromValue = mapper.toJSON(value) + let valueFromParsedJSON: NestedKeys! = mapper.map(JSON: JSONFromValue) + XCTAssertNotNil(valueFromParsedJSON) + + XCTAssertEqual(value.nonNestedString, valueFromParsedJSON.nonNestedString) + + XCTAssertEqual(value.int64, valueFromParsedJSON.int64) + XCTAssertEqual(value.bool, valueFromParsedJSON.bool) + XCTAssertEqual(value.int, valueFromParsedJSON.int) + XCTAssertEqual(value.double, valueFromParsedJSON.double) + XCTAssertEqual(value.float, valueFromParsedJSON.float) + XCTAssertEqual(value.string, valueFromParsedJSON.string) + + XCTAssertEqual(value.int64Array, valueFromParsedJSON.int64Array) + XCTAssertEqual(value.boolArray, valueFromParsedJSON.boolArray) + XCTAssertEqual(value.intArray, valueFromParsedJSON.intArray) + XCTAssertEqual(value.doubleArray, valueFromParsedJSON.doubleArray) + XCTAssertEqual(value.floatArray, valueFromParsedJSON.floatArray) + XCTAssertEqual(value.stringArray, valueFromParsedJSON.stringArray) + + XCTAssertEqual(value.int64Dict, valueFromParsedJSON.int64Dict) + XCTAssertEqual(value.boolDict, valueFromParsedJSON.boolDict) + XCTAssertEqual(value.intDict, valueFromParsedJSON.intDict) + XCTAssertEqual(value.doubleDict, valueFromParsedJSON.doubleDict) + XCTAssertEqual(value.floatDict, valueFromParsedJSON.floatDict) + XCTAssertEqual(value.stringDict, valueFromParsedJSON.stringDict) + + XCTAssertEqual(value.int64Enum, valueFromParsedJSON.int64Enum) + XCTAssertEqual(value.intEnum, valueFromParsedJSON.intEnum) + XCTAssertEqual(value.doubleEnum, valueFromParsedJSON.doubleEnum) + XCTAssertEqual(value.floatEnum, valueFromParsedJSON.floatEnum) + XCTAssertEqual(value.stringEnum, valueFromParsedJSON.stringEnum) + + XCTAssertEqual(value.object, valueFromParsedJSON.object) + XCTAssertEqual(value.objectArray, valueFromParsedJSON.objectArray) + XCTAssertEqual(value.objectDict, valueFromParsedJSON.objectDict) + } + + func testNestedKeysWithDelimiter() { + let JSON: [String: Any] = [ + "non.nested->key": "string", + "com.hearst.ObjectMapper.nested": [ + "com.hearst.ObjectMapper.int64": NSNumber(value: INT64_MAX), + "com.hearst.ObjectMapper.bool": true, + "com.hearst.ObjectMapper.int": 255, + "com.hearst.ObjectMapper.double": 100.0 as Double, + "com.hearst.ObjectMapper.float": 50.0 as Float, + "com.hearst.ObjectMapper.string": "String!", + + "com.hearst.ObjectMapper.nested": [ + "int64Array": [NSNumber(value: INT64_MAX), NSNumber(value: INT64_MAX - 1), NSNumber(value: INT64_MAX - 10)], + "boolArray": [false, true, false], + "intArray": [1, 2, 3], + "doubleArray": [1.0, 2.0, 3.0], + "floatArray": [1.0 as Float, 2.0 as Float, 3.0 as Float], + "stringArray": ["123", "ABC"], + + "int64Dict": ["1": NSNumber(value: INT64_MAX)], + "boolDict": ["2": true], + "intDict": ["3": 999], + "doubleDict": ["4": 999.999], + "floatDict": ["5": 123.456 as Float], + "stringDict": ["6": "InDict"], + + "int64Enum": 1000, + "intEnum": 255, + "doubleEnum": 100.0, + "floatEnum": 100.0, + "stringEnum": "String B", + + "com.hearst.ObjectMapper.nested": [ + "object": ["value": 987], + "objectArray": [ ["value": 123], ["value": 456] ], + "objectDict": ["key": ["value": 999]] + ] + ] + ] + ] + + let mapper = Mapper() + + let value: DelimiterNestedKeys! = mapper.map(JSONObject: JSON) + XCTAssertNotNil(value) + + XCTAssertEqual(value.nonNestedString, "string") + + XCTAssertEqual(value.int64, NSNumber(value: INT64_MAX)) + XCTAssertEqual(value.bool, true) + XCTAssertEqual(value.int, 255) + XCTAssertEqual(value.double, 100.0 as Double) + XCTAssertEqual(value.float, 50.0 as Float) + XCTAssertEqual(value.string, "String!") + + let int64Array = [NSNumber(value: INT64_MAX), NSNumber(value: INT64_MAX - 1), NSNumber(value: INT64_MAX - 10)] + XCTAssertEqual(value.int64Array, int64Array) + XCTAssertEqual(value.boolArray, [false, true, false]) + XCTAssertEqual(value.intArray, [1, 2, 3]) + XCTAssertEqual(value.doubleArray, [1.0, 2.0, 3.0]) + XCTAssertEqual(value.floatArray, [1.0 as Float, 2.0 as Float, 3.0 as Float]) + XCTAssertEqual(value.stringArray, ["123", "ABC"]) + + XCTAssertEqual(value.int64Dict, ["1": NSNumber(value: INT64_MAX)]) + XCTAssertEqual(value.boolDict, ["2": true]) + XCTAssertEqual(value.intDict, ["3": 999]) + XCTAssertEqual(value.doubleDict, ["4": 999.999]) + XCTAssertEqual(value.floatDict, ["5": 123.456 as Float]) + XCTAssertEqual(value.stringDict, ["6": "InDict"]) + + XCTAssertEqual(value.int64Enum, Int64Enum.b) + XCTAssertEqual(value.intEnum, IntEnum.b) +// Skip tests due to float issue - #591 +// XCTAssertEqual(value.doubleEnum, DoubleEnum.b) +// XCTAssertEqual(value.floatEnum, FloatEnum.b) + XCTAssertEqual(value.stringEnum, StringEnum.B) + + XCTAssertEqual(value.object?.value, 987) + XCTAssertEqual(value.objectArray.map { $0.value }, [123, 456]) + XCTAssertEqual(value.objectDict["key"]?.value, 999) + + let JSONFromValue = mapper.toJSON(value) + let valueFromParsedJSON: DelimiterNestedKeys! = mapper.map(JSON: JSONFromValue) + XCTAssertNotNil(valueFromParsedJSON) + + XCTAssertEqual(value.nonNestedString, valueFromParsedJSON.nonNestedString) + + XCTAssertEqual(value.int64, valueFromParsedJSON.int64) + XCTAssertEqual(value.bool, valueFromParsedJSON.bool) + XCTAssertEqual(value.int, valueFromParsedJSON.int) + XCTAssertEqual(value.double, valueFromParsedJSON.double) + XCTAssertEqual(value.float, valueFromParsedJSON.float) + XCTAssertEqual(value.string, valueFromParsedJSON.string) + + XCTAssertEqual(value.int64Array, valueFromParsedJSON.int64Array) + XCTAssertEqual(value.boolArray, valueFromParsedJSON.boolArray) + XCTAssertEqual(value.intArray, valueFromParsedJSON.intArray) + XCTAssertEqual(value.doubleArray, valueFromParsedJSON.doubleArray) + XCTAssertEqual(value.floatArray, valueFromParsedJSON.floatArray) + XCTAssertEqual(value.stringArray, valueFromParsedJSON.stringArray) + + XCTAssertEqual(value.int64Dict, valueFromParsedJSON.int64Dict) + XCTAssertEqual(value.boolDict, valueFromParsedJSON.boolDict) + XCTAssertEqual(value.intDict, valueFromParsedJSON.intDict) + XCTAssertEqual(value.doubleDict, valueFromParsedJSON.doubleDict) + XCTAssertEqual(value.floatDict, valueFromParsedJSON.floatDict) + XCTAssertEqual(value.stringDict, valueFromParsedJSON.stringDict) + + XCTAssertEqual(value.int64Enum, valueFromParsedJSON.int64Enum) + XCTAssertEqual(value.intEnum, valueFromParsedJSON.intEnum) + XCTAssertEqual(value.doubleEnum, valueFromParsedJSON.doubleEnum) + XCTAssertEqual(value.floatEnum, valueFromParsedJSON.floatEnum) + XCTAssertEqual(value.stringEnum, valueFromParsedJSON.stringEnum) + + XCTAssertEqual(value.object, valueFromParsedJSON.object) + XCTAssertEqual(value.objectArray, valueFromParsedJSON.objectArray) + XCTAssertEqual(value.objectDict, valueFromParsedJSON.objectDict) + } + +} + +class NestedKeys: Mappable { + + var nonNestedString: String? + + var int64: NSNumber? + var bool: Bool? + var int: Int? + var double: Double? + var float: Float? + var string: String? + + var int64Array: [NSNumber] = [] + var boolArray: [Bool] = [] + var intArray: [Int] = [] + var doubleArray: [Double] = [] + var floatArray: [Float] = [] + var stringArray: [String] = [] + + var int64Dict: [String: NSNumber] = [:] + var boolDict: [String: Bool] = [:] + var intDict: [String: Int] = [:] + var doubleDict: [String: Double] = [:] + var floatDict: [String: Float] = [:] + var stringDict: [String: String] = [:] + + var int64Enum: Int64Enum? + var intEnum: IntEnum? + var doubleEnum: DoubleEnum? + var floatEnum: FloatEnum? + var stringEnum: StringEnum? + + var object: Object? + var objectArray: [Object] = [] + var objectDict: [String: Object] = [:] + + required init?(map: Map){ + + } + + func mapping(map: Map) { + nonNestedString <- map["non.nested.key", nested: false] + + int64 <- map["nested.int64"] + bool <- map["nested.bool"] + int <- map["nested.int"] + double <- map["nested.double"] + float <- map["nested.float"] + string <- map["nested.string"] + + int64Array <- map["nested.nested.int64Array"] + boolArray <- map["nested.nested.boolArray"] + intArray <- map["nested.nested.intArray"] + doubleArray <- map["nested.nested.doubleArray"] + floatArray <- map["nested.nested.floatArray"] + stringArray <- map["nested.nested.stringArray"] + + int64Dict <- map["nested.nested.int64Dict"] + boolDict <- map["nested.nested.boolDict"] + intDict <- map["nested.nested.intDict"] + doubleDict <- map["nested.nested.doubleDict"] + floatDict <- map["nested.nested.floatDict"] + stringDict <- map["nested.nested.stringDict"] + + int64Enum <- map["nested.nested.int64Enum"] + intEnum <- map["nested.nested.intEnum"] + doubleEnum <- map["nested.nested.doubleEnum"] + floatEnum <- map["nested.nested.floatEnum"] + stringEnum <- map["nested.nested.stringEnum"] + + object <- map["nested.nested.nested.object"] + objectArray <- map["nested.nested.nested.objectArray"] + objectDict <- map["nested.nested.nested.objectDict"] + } +} + +class DelimiterNestedKeys: NestedKeys { + override func mapping(map: Map) { + nonNestedString <- map["non.nested->key", nested: false, delimiter: "->"] + + int64 <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.int64", delimiter: "->"] + bool <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.bool", delimiter: "->"] + int <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.int", delimiter: "->"] + double <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.double", delimiter: "->"] + float <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.float", delimiter: "->"] + string <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.string", delimiter: "->"] + + int64Array <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->int64Array", delimiter: "->"] + boolArray <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->boolArray", delimiter: "->"] + intArray <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->intArray", delimiter: "->"] + doubleArray <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->doubleArray", delimiter: "->"] + floatArray <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->floatArray", delimiter: "->"] + stringArray <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->stringArray", delimiter: "->"] + + int64Dict <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->int64Dict", delimiter: "->"] + boolDict <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->boolDict", delimiter: "->"] + intDict <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->intDict", delimiter: "->"] + doubleDict <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->doubleDict", delimiter: "->"] + floatDict <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->floatDict", delimiter: "->"] + stringDict <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->stringDict", delimiter: "->"] + + int64Enum <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->int64Enum", delimiter: "->"] + intEnum <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->intEnum", delimiter: "->"] + doubleEnum <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->doubleEnum", delimiter: "->"] + floatEnum <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->floatEnum", delimiter: "->"] + stringEnum <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->stringEnum", delimiter: "->"] + + object <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->object", delimiter: "->"] + objectArray <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->objectArray", delimiter: "->"] + objectDict <- map["com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->com.hearst.ObjectMapper.nested->objectDict", delimiter: "->"] + } +} + +class Object: Mappable, Equatable { + var value: Int = Int.min + + required init?(map: Map){ + + } + + func mapping(map: Map) { + value <- map["value"] + } +} + +func == (lhs: Object, rhs: Object) -> Bool { + return lhs.value == rhs.value +} + +enum Int64Enum: NSNumber { + case a = 0 + case b = 1000 +} + +enum IntEnum: Int { + case a = 0 + case b = 255 +} + +enum DoubleEnum: Double { + case a = 0.0 + case b = 100.0 +} + +enum FloatEnum: Float { + case a = 0.0 + case b = 100.0 +} + +enum StringEnum: String { + case A = "String A" + case B = "String B" +} diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/NullableKeysFromJSONTests.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/NullableKeysFromJSONTests.swift new file mode 100644 index 0000000..f0dc13c --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/NullableKeysFromJSONTests.swift @@ -0,0 +1,118 @@ +// +// NullableKeysFromJSONTests.swift +// ObjectMapper +// +// Created by Fabio Teles on 3/22/16. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 +import XCTest +import ObjectMapper + +class NullableKeysFromJSONTests: XCTestCase { + + let fullJSONString = "{\"firstName\": \"John\", \"lastName\": \"Doe\", \"team\": \"Broncos\", \"age\": 25, \"address\": {\"street\": \"Nothing Ave\", \"number\": 101, \"city\": \"Los Angeles\"} }" + let nullJSONString = "{\"firstName\": \"John\", \"lastName\": null, \"team\": \"Broncos\", \"age\": null, \"address\": {\"street\": \"Nothing Ave\", \"number\": 101, \"city\": null} }" + let absentJSONString = "{\"firstName\": \"John\", \"team\": \"Broncos\", \"address\": {\"street\": \"Nothing Ave\", \"number\": 102} }" + + let mapper = Mapper() + + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + func testMapperNullifiesValues() { + guard let player = mapper.map(JSONString: fullJSONString) else { + XCTFail("Mapping failed") + return + } + + XCTAssertNotNil(player.lastName) + XCTAssertNotNil(player.age) + XCTAssertNotNil(player.address?.city) + + _ = mapper.map(JSONString: nullJSONString, toObject: player) + + XCTAssertNotNil(player.firstName) + XCTAssertNil(player.lastName) + XCTAssertNil(player.age) + XCTAssertNil(player.address?.city) + } + + func testMapperAbsentValues() { + guard let player = mapper.map(JSONString: fullJSONString) else { + XCTFail("Mapping failed") + return + } + + XCTAssertNotNil(player.lastName) + XCTAssertNotNil(player.age) + XCTAssertNotNil(player.address?.city) + + _ = mapper.map(JSONString: absentJSONString, toObject: player) + + XCTAssertNotNil(player.firstName) + XCTAssertNotNil(player.lastName) + XCTAssertNotNil(player.age) + XCTAssertNotNil(player.address?.city) + XCTAssertEqual(player.address?.number, 102) + } +} + +class Player: Mappable { + var firstName: String? + var lastName: String? + var team: String? + var age: Int? + var address: Address? + + required init?(map: Map){ + mapping(map: map) + } + + func mapping(map: Map) { + firstName <- map["firstName"] + lastName <- map["lastName"] + team <- map["team"] + age <- map["age"] + address <- map["address"] + } +} + +class Address: Mappable { + var street: String? + var number: Int? + var city: String? + + required init?(map: Map){ + mapping(map: map) + } + + func mapping(map: Map) { + street <- map["street"] + number <- map["number"] + city <- map["city"] + } +} diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/ObjectMapperTests.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/ObjectMapperTests.swift new file mode 100644 index 0000000..7a324ec --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/ObjectMapperTests.swift @@ -0,0 +1,658 @@ +// +// ObjectMapperTests.swift +// ObjectMapperTests +// +// Created by Tristan Himmelman on 2014-10-16. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 +import XCTest +import ObjectMapper + +class ObjectMapperTests: XCTestCase { + + let userMapper = Mapper() + + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } + + func testBasicParsing() { + let username = "John Doe" + let identifier = "user8723" + let photoCount = 13 + let age = 1227 + let weight = 123.23 + let float: Float = 123.231 + let drinker = true + let smoker = false + let sex: Sex = .Female + let subUserJSON = "{\"identifier\" : \"user8723\", \"drinker\" : true, \"age\": 17, \"username\" : \"sub user\" }" + + let userJSONString = "{\"username\":\"\(username)\",\"identifier\":\"\(identifier)\",\"photoCount\":\(photoCount),\"age\":\(age),\"drinker\":\(drinker),\"smoker\":\(smoker), \"sex\":\"\(sex.rawValue)\", \"arr\":[ \"bla\", true, 42 ], \"dict\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 }, \"arrOpt\":[ \"bla\", true, 42 ], \"dictOpt\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 }, \"weight\": \(weight), \"float\": \(float), \"friend\": \(subUserJSON), \"friendDictionary\":{ \"bestFriend\": \(subUserJSON)}}" + + let user = userMapper.map(JSONString: userJSONString)! + + XCTAssertNotNil(user) + XCTAssertEqual(username, user.username) + XCTAssertEqual(identifier, user.identifier) + XCTAssertEqual(photoCount, user.photoCount) + XCTAssertEqual(age, user.age) + XCTAssertEqual(weight, user.weight) + XCTAssertEqual(float, user.float) + XCTAssertEqual(drinker, user.drinker) + XCTAssertEqual(smoker, user.smoker) + XCTAssertEqual(sex, user.sex) + + //print(Mapper().toJSONString(user, prettyPrint: true)) + } + + func testOptionalStringParsing() { + let username = "John Doe" + let identifier = "user8723" + let photoCount = 13 + let age = 1227 + let weight = 123.23 + let float: Float = 123.231 + let drinker = true + let smoker = false + let sex: Sex = .Female + let subUserJSON = "{\"identifier\" : \"user8723\", \"drinker\" : true, \"age\": 17, \"username\" : \"sub user\" }" + + let userJSONString: String? = "{\"username\":\"\(username)\",\"identifier\":\"\(identifier)\",\"photoCount\":\(photoCount),\"age\":\(age),\"drinker\":\(drinker),\"smoker\":\(smoker), \"sex\":\"\(sex.rawValue)\", \"arr\":[ \"bla\", true, 42 ], \"dict\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 }, \"arrOpt\":[ \"bla\", true, 42 ], \"dictOpt\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 }, \"weight\": \(weight), \"float\": \(float), \"friend\": \(subUserJSON), \"friendDictionary\":{ \"bestFriend\": \(subUserJSON)}}" + + let user = userMapper.map(JSONString: userJSONString!)! + + XCTAssertNotNil(user) + XCTAssertEqual(username, user.username) + XCTAssertEqual(identifier, user.identifier) + XCTAssertEqual(photoCount, user.photoCount) + XCTAssertEqual(age, user.age) + XCTAssertEqual(weight, user.weight) + XCTAssertEqual(float, user.float) + XCTAssertEqual(drinker, user.drinker) + XCTAssertEqual(smoker, user.smoker) + XCTAssertEqual(sex, user.sex) + } + + func testInstanceParsing() { + let username = "John Doe" + let identifier = "user8723" + let photoCount = 13 + let age = 1227 + let weight = 123.23 + let float: Float = 123.231 + let drinker = true + let smoker = false + let sex: Sex = .Female + let subUserJSON = "{\"identifier\" : \"user8723\", \"drinker\" : true, \"age\": 17, \"username\" : \"sub user\" }" + + let userJSONString = "{\"username\":\"\(username)\",\"identifier\":\"\(identifier)\",\"photoCount\":\(photoCount),\"age\":\(age),\"drinker\":\(drinker),\"smoker\":\(smoker), \"sex\":\"\(sex.rawValue)\", \"arr\":[ \"bla\", true, 42 ], \"dict\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 }, \"arrOpt\":[ \"bla\", true, 42 ], \"dictOpt\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 },\"weight\": \(weight), \"float\": \(float), \"friend\": \(subUserJSON), \"friendDictionary\":{ \"bestFriend\": \(subUserJSON)}}" + + let user = Mapper().map(JSONString: userJSONString, toObject: User()) + + XCTAssertEqual(username, user.username) + XCTAssertEqual(identifier, user.identifier) + XCTAssertEqual(photoCount, user.photoCount) + XCTAssertEqual(age, user.age) + XCTAssertEqual(weight, user.weight) + XCTAssertEqual(float, user.float) + XCTAssertEqual(drinker, user.drinker) + XCTAssertEqual(smoker, user.smoker) + XCTAssertEqual(sex, user.sex) + //print(Mapper().toJSONString(user, prettyPrint: true)) + } + + func testDictionaryParsing() { + let name: String = "Genghis khan" + let UUID: String = "12345" + let major: Int = 99 + let minor: Int = 1 + let json: [String: Any] = ["name": name, "UUID": UUID, "major": major] + + //test that the sematics of value types works as expected. the resulting maped student + //should have the correct minor property set even thoug it's not mapped + var s = Student() + s.minor = minor + let student = Mapper().map(JSON: json, toObject: s) + + XCTAssertEqual(name, student.name) + XCTAssertEqual(UUID, student.UUID) + XCTAssertEqual(major, student.major) + XCTAssertEqual(minor, student.minor) + + //Test that mapping a reference type works as expected while not relying on the return value + let username: String = "Barack Obama" + let identifier: String = "Political" + let photoCount: Int = 1000000000 + + let json2: [String: Any] = ["username": username, "identifier": identifier, "photoCount": photoCount] + let user = User() + _ = Mapper().map(JSON: json2, toObject: user) + + XCTAssertEqual(username, user.username) + XCTAssertEqual(identifier, user.identifier) + XCTAssertEqual(photoCount, user.photoCount) + } + + func testNullObject() { + let JSONString = "{\"username\":\"bob\"}" + + let user = userMapper.map(JSONString: JSONString) + + XCTAssertNotNil(user) + XCTAssertNil(user?.age) + } + + func testToJSONAndBack(){ + let user = User() + user.username = "tristan_him" + user.identifier = "tristan_him_identifier" + user.photoCount = 0 + user.age = 28 + user.weight = 150 + user.drinker = true + user.smoker = false + user.sex = .Female + user.arr = ["cheese", 11234] + + let JSONString = Mapper().toJSONString(user, prettyPrint: true) + //print(JSONString) + + let parsedUser = userMapper.map(JSONString: JSONString!)! + + XCTAssertNotNil(parsedUser) + XCTAssertEqual(user.identifier, parsedUser.identifier) + XCTAssertEqual(user.photoCount, parsedUser.photoCount) + XCTAssertEqual(user.age, parsedUser.age) + XCTAssertEqual(user.weight, parsedUser.weight) + XCTAssertEqual(user.drinker, parsedUser.drinker) + XCTAssertEqual(user.smoker, parsedUser.smoker) + XCTAssertEqual(user.sex, parsedUser.sex) + } + + func testToJSONArrayAndBack(){ + let user = User() + user.username = "tristan_him" + user.identifier = "tristan_him_identifier" + user.photoCount = 0 + user.age = 28 + user.weight = 150 + user.drinker = true + user.smoker = false + user.sex = .Female + user.arr = ["cheese", 11234] + let users = [user, user, user] + + //print(JSONString) + let JSONString = Mapper().toJSONString(users) + let parsedUsers = userMapper.mapArray(JSONString: JSONString!) + + XCTAssertNotNil(parsedUsers) + XCTAssertTrue(parsedUsers?.count == 3) + XCTAssertEqual(user.identifier, parsedUsers?[0].identifier) + XCTAssertEqual(user.photoCount, parsedUsers?[0].photoCount) + XCTAssertEqual(user.age, parsedUsers?[0].age) + XCTAssertEqual(user.weight, parsedUsers?[0].weight) + XCTAssertEqual(user.drinker, parsedUsers?[0].drinker) + XCTAssertEqual(user.smoker, parsedUsers?[0].smoker) + XCTAssertEqual(user.sex, parsedUsers?[0].sex) + } + + func testUnknownPropertiesIgnored() { + let JSONString = "{\"username\":\"bob\",\"identifier\":\"bob1987\", \"foo\" : \"bar\", \"fooArr\" : [ 1, 2, 3], \"fooObj\" : { \"baz\" : \"qux\" } }" + + let user = userMapper.map(JSONString: JSONString) + + XCTAssertNotNil(user) + } + + func testInvalidJsonResultsInNilObject() { + let JSONString = "{\"username\":\"bob\",\"identifier\":\"bob1987\"" // missing ending brace + + let user = userMapper.map(JSONString: JSONString) + + XCTAssertNil(user) + } + + func testMapArrayJSON(){ + let name1 = "Bob" + let name2 = "Jane" + + let JSONString = "[{\"name\": \"\(name1)\", \"UUID\": \"3C074D4B-FC8C-4CA2-82A9-6E9367BBC875\", \"major\": 541, \"minor\": 123},{ \"name\": \"\(name2)\", \"UUID\": \"3C074D4B-FC8C-4CA2-82A9-6E9367BBC876\", \"major\": 54321,\"minor\": 13 }]" + + let students = Mapper().mapArray(JSONString: JSONString) + + XCTAssertTrue(students?.count ?? 0 > 0) + XCTAssertTrue(students?.count == 2) + XCTAssertEqual(students?[0].name, name1) + XCTAssertEqual(students?[1].name, name2) + } + + // test mapArray() with JSON string that is not an array form + // should return a collection with one item + func testMapArrayJSONWithNoArray(){ + let name1 = "Bob" + + let JSONString = "{\"name\": \"\(name1)\", \"UUID\": \"3C074D4B-FC8C-4CA2-82A9-6E9367BBC875\", \"major\": 541, \"minor\": 123}" + + let students = Mapper().mapArray(JSONString: JSONString) + + XCTAssertTrue(students?.count ?? 0 > 0) + XCTAssertTrue(students?.count == 1) + XCTAssertEqual(students?[0].name, name1) + } + + func testMapArrayJSONWithEmptyArray() { + let JSONString = "[]" + + let students = Mapper().mapArray(JSONString: JSONString) + + XCTAssertNotNil(students) + XCTAssertTrue(students?.count == 0) + } + + func testArrayOfCustomObjects(){ + let percentage1: Double = 0.1 + let percentage2: Double = 1792.41 + + let JSONString = "{ \"tasks\": [{\"taskId\":103,\"percentage\":\(percentage1)},{\"taskId\":108,\"percentage\":\(percentage2)}] }" + + let plan = Mapper().map(JSONString: JSONString) + + let tasks = plan?.tasks + + XCTAssertNotNil(tasks) + XCTAssertEqual(tasks?[0].percentage, percentage1) + XCTAssertEqual(tasks?[1].percentage, percentage2) + } + + func testDictionaryOfArrayOfCustomObjects(){ + let percentage1: Double = 0.1 + let percentage2: Double = 1792.41 + + let JSONString = "{ \"dictionaryOfTasks\": { \"mondayTasks\" :[{\"taskId\":103,\"percentage\":\(percentage1)},{\"taskId\":108,\"percentage\":\(percentage2)}] } }" + + let plan = Mapper().map(JSONString: JSONString) + + let dictionaryOfTasks = plan?.dictionaryOfTasks + XCTAssertNotNil(dictionaryOfTasks) + XCTAssertEqual(dictionaryOfTasks?["mondayTasks"]?[0].percentage, percentage1) + XCTAssertEqual(dictionaryOfTasks?["mondayTasks"]?[1].percentage, percentage2) + + let planToJSON = Mapper().toJSONString(plan!, prettyPrint: true) + //print(planToJSON!) + let planFromJSON = Mapper().map(JSONString: planToJSON!) + + let dictionaryOfTasks2 = planFromJSON?.dictionaryOfTasks + XCTAssertNotNil(dictionaryOfTasks2) + XCTAssertEqual(dictionaryOfTasks2?["mondayTasks"]?[0].percentage, percentage1) + XCTAssertEqual(dictionaryOfTasks2?["mondayTasks"]?[1].percentage, percentage2) + } + + func testArrayOfEnumObjects(){ + let a: ExampleEnum = .a + let b: ExampleEnum = .b + let c: ExampleEnum = .c + + let JSONString = "{ \"enums\": [\(a.rawValue), \(b.rawValue), \(c.rawValue)] }" + + let enumArray = Mapper().map(JSONString: JSONString) + let enums = enumArray?.enums + + XCTAssertNotNil(enums) + XCTAssertTrue(enums?.count == 3) + XCTAssertEqual(enums?[0], a) + XCTAssertEqual(enums?[1], b) + XCTAssertEqual(enums?[2], c) + } + + func testDictionaryOfCustomObjects(){ + let percentage1: Double = 0.1 + let percentage2: Double = 1792.41 + + let JSONString = "{\"tasks\": { \"task1\": {\"taskId\":103,\"percentage\":\(percentage1)}, \"task2\": {\"taskId\":108,\"percentage\":\(percentage2)}}}" + + let taskDict = Mapper().map(JSONString: JSONString) + + let task = taskDict?.tasks?["task1"] + XCTAssertNotNil(task) + XCTAssertEqual(task?.percentage, percentage1) + } + + func testDictionryOfEnumObjects(){ + let a: ExampleEnum = .a + let b: ExampleEnum = .b + let c: ExampleEnum = .c + + let JSONString = "{ \"enums\": {\"A\": \(a.rawValue), \"B\": \(b.rawValue), \"C\": \(c.rawValue)} }" + + let enumDict = Mapper().map(JSONString: JSONString) + let enums = enumDict?.enums + + XCTAssertNotNil(enums) + XCTAssertTrue(enums?.count == 3) + } + + func testDoubleParsing(){ + let percentage1: Double = 1792.41 + + let JSONString = "{\"taskId\":103,\"percentage\":\(percentage1)}" + + let task = Mapper().map(JSONString: JSONString) + + XCTAssertNotNil(task) + XCTAssertEqual(task?.percentage, percentage1) + } + + func testToJSONArray(){ + let task1 = Task() + task1.taskId = 1 + task1.percentage = 11.1 + let task2 = Task() + task2.taskId = 2 + task2.percentage = 22.2 + let task3 = Task() + task3.taskId = 3 + task3.percentage = 33.3 + + let taskArray = [task1, task2, task3] + + let JSONArray = Mapper().toJSONArray(taskArray) + + let taskId1 = JSONArray[0]["taskId"] as? Int + let percentage1 = JSONArray[0]["percentage"] as? Double + + XCTAssertEqual(taskId1, task1.taskId) + XCTAssertEqual(percentage1, task1.percentage) + + let taskId2 = JSONArray[1]["taskId"] as? Int + let percentage2 = JSONArray[1]["percentage"] as? Double + + XCTAssertEqual(taskId2, task2.taskId) + XCTAssertEqual(percentage2, task2.percentage) + + let taskId3 = JSONArray[2]["taskId"] as? Int + let percentage3 = JSONArray[2]["percentage"] as? Double + + XCTAssertEqual(taskId3, task3.taskId) + XCTAssertEqual(percentage3, task3.percentage) + } + + func testArrayOfArrayOfMappable() { + let base1 = "1" + let base2 = "2" + let base3 = "3" + let base4 = "4" + + let array1 = [["base": base1], ["base": base2], ["base": base3]] + let array2 = [["base": base4]] + let JSON = ["twoDimensionalArray":[array1, array2]] + + let arrayTest = Mapper().map(JSON: JSON) + + XCTAssertNotNil(arrayTest) + XCTAssertEqual(arrayTest?.twoDimensionalArray?[0][0].base, base1) + XCTAssertEqual(arrayTest?.twoDimensionalArray?[0][1].base, base2) + XCTAssertEqual(arrayTest?.twoDimensionalArray?[0][2].base, base3) + XCTAssertEqual(arrayTest?.twoDimensionalArray?[1][0].base, base4) + + XCTAssertEqual(arrayTest?.twoDimensionalArray?[0].count, array1.count) + XCTAssertEqual(arrayTest?.twoDimensionalArray?[1].count, array2.count) + + let backToJSON = Mapper().toJSON(arrayTest!) + XCTAssertNotNil(backToJSON) + + let arrayTest2 = Mapper().map(JSON: backToJSON) + XCTAssertNotNil(arrayTest2) + XCTAssertEqual(arrayTest2?.twoDimensionalArray?[0][0].base, arrayTest?.twoDimensionalArray?[0][0].base) + XCTAssertEqual(arrayTest2?.twoDimensionalArray?[0][1].base, arrayTest?.twoDimensionalArray?[0][1].base) + } + + func testShouldPreventOverwritingMappableProperty() { + let json: [String: Any] = [ + "name": "Entry 1", + "bigList": [["name": "item 1"], ["name": "item 2"], ["name": "item 3"]] + ] + let model = CachedModel() + _ = Mapper().map(JSON: json, toObject: model) + + XCTAssertEqual(model.name, "Entry 1") + XCTAssertEqual(model.bigList?.count, 3) + + let json2: [String: Any] = ["name": "Entry 1"] + _ = Mapper().map(JSON: json2, toObject: model) + + XCTAssertEqual(model.name, "Entry 1") + XCTAssertEqual(model.bigList?.count, 3) + } +} + +class Status: Mappable { + var status: Int? + + required init?(map: Map){ + + } + + func mapping(map: Map) { + status <- map["code"] + } +} + +class Plan: Mappable { + var tasks: [Task]? + var dictionaryOfTasks: [String: [Task]]? + + required init?(map: Map){ + + } + + func mapping(map: Map) { + tasks <- map["tasks"] + dictionaryOfTasks <- map["dictionaryOfTasks"] + } +} + +class Task: Mappable { + var taskId: Int? + var percentage: Double? + + init(){ + + } + + required init?(map: Map){ + + } + + func mapping(map: Map) { + taskId <- map["taskId"] + percentage <- map["percentage"] + } +} + +class TaskDictionary: Mappable { + var test: String? + var tasks: [String : Task]? + + required init?(map: Map){ + + } + + func mapping(map: Map) { + test <- map["test"] + tasks <- map["tasks"] + } +} + + +// Confirm that struct can conform to `Mappable` +struct Student: Mappable { + var name: String? + var UUID: String? + var major: Int? + var minor: Int? + + init(){ + + } + + init?(map: Map){ + + } + + mutating func mapping(map: Map) { + name <- map["name"] + UUID <- map["UUID"] + major <- map["major"] + minor <- map["minor"] + } +} + +enum Sex: String { + case Male = "Male" + case Female = "Female" +} + +class User: Mappable { + + var username: String = "" + var identifier: String? + var photoCount: Int = 0 + var age: Int? + var weight: Double? + var float: Float? + var drinker: Bool = false + var smoker: Bool? + var sex: Sex? + var arr: [Any] = [] + var arrOptional: [Any]? + var dict: [String : Any] = [:] + var dictOptional: [String : Any]? + var dictString: [String : String]? + var friendDictionary: [String : User]? + var friend: User? + var friends: [User]? = [] + + init(){ + + } + + required init?(map: Map){ + + } + + func mapping(map: Map) { + username <- map["username"] + identifier <- map["identifier"] + photoCount <- map["photoCount"] + age <- map["age"] + weight <- map["weight"] + float <- map["float"] + drinker <- map["drinker"] + smoker <- map["smoker"] + sex <- map["sex"] + arr <- map["arr"] + arrOptional <- map["arrOpt"] + dict <- map["dict"] + dictOptional <- map["dictOpt"] + friend <- map["friend"] + friends <- map["friends"] + friendDictionary <- map["friendDictionary"] + dictString <- map["dictString"] + } +} + + +enum ExampleEnum: Int { + case a + case b + case c +} + +class ExampleEnumArray: Mappable { + var enums: [ExampleEnum] = [] + + required init?(map: Map){ + + } + + func mapping(map: Map) { + enums <- map["enums"] + } +} + +class ExampleEnumDictionary: Mappable { + var enums: [String: ExampleEnum] = [:] + + required init?(map: Map){ + + } + + func mapping(map: Map) { + enums <- map["enums"] + } +} + +class ArrayTest: Mappable { + + var twoDimensionalArray: Array>? + + required init?(map: Map){} + + func mapping(map: Map) { + twoDimensionalArray <- map["twoDimensionalArray"] + } +} + +class CachedModel: Mappable { + var name: String? + var bigList: [CachedItem]? + + init() {} + + required init?(map: Map){} + + func mapping(map: Map) { + name <- map["name"] + bigList <- map["bigList"] + } +} + +struct CachedItem: Mappable { + var name: String? + + init?(map: Map){} + + mutating func mapping(map: Map) { + name <- map["name"] + } +} diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/PerformanceTests.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/PerformanceTests.swift new file mode 100644 index 0000000..c03650f --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/PerformanceTests.swift @@ -0,0 +1,174 @@ +// +// PerformanceTests.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2015-09-21. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 +import XCTest +import ObjectMapper + +class PerformanceTests: XCTestCase { + + let JSONTestString: String = { + let subObjectJSON = "{\"string\":\"This is a string\", \"int\": 12,\"double\":12.27,\"float\":12.3212, \"bool\":false, \"arr\":[ \"bla\", true, 42 ], \"dict\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 } }" + + let objectJSONString = "{\"string\":\"This is a string\", \"int\": 12,\"double\":12.27,\"float\":12.3212, \"bool\":false, \"arr\":[ \"bla\", true, 42 ], \"dict\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 }, \"object\": \(subObjectJSON), \"objects\":{ \"key1\": \(subObjectJSON), \"key2\": \(subObjectJSON)}}" + + var JSONString = "[" + for _ in 0...1000 { + JSONString += "\(objectJSONString)," + } + JSONString += "\(objectJSONString)]" + return JSONString + }() + + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } + + func testPerformance() { + self.measure { + // Put the code you want to measure the time of here. + _ = Mapper().mapArray(JSONString: self.JSONTestString) + } + } + + func testPerformanceCluster() { + self.measure { + // Put the code you want to measure the time of here. + _ = Mapper().mapArray(JSONString: self.JSONTestString) + } + } + + func testPerformanceImmutable() { + self.measure { + _ = try? Mapper().mapArray(JSONString: self.JSONTestString) + } + } +} + +class PerformanceMappableObject: Mappable { + + var string: String? + var int: Int? + var double: Double? + var float: Float? + var bool: Bool? + var array: [Any]? + var dictionary: [String: Any]? + var object: PerformanceMappableObject? + var objects: [PerformanceMappableObject]? + + required init?(map: Map){ + + } + + func mapping(map: Map) { + string <- map["string"] + int <- map["int"] + double <- map["double"] + float <- map["float"] + bool <- map["bool"] + array <- map["array"] + dictionary <- map["dictionary"] + object <- map["object"] + objects <- map["objects"] + } +} + +class PerformanceStaticMappableObject: StaticMappable { + + var string: String? + var int: Int? + var double: Double? + var float: Float? + var bool: Bool? + var array: [Any]? + var dictionary: [String: Any]? + var object: PerformanceStaticMappableObject? + var objects: [PerformanceStaticMappableObject]? + + static func objectForMapping(map: Map) -> BaseMappable? { + return PerformanceStaticMappableObject() + } + + func mapping(map: Map) { + string <- map["string"] + int <- map["int"] + double <- map["double"] + float <- map["float"] + bool <- map["bool"] + array <- map["array"] + dictionary <- map["dictionary"] + object <- map["object"] + objects <- map["objects"] + } +} + +class PerformanceImmutableMappableObject: ImmutableMappable { + + let string: String? + let int: Int? + let double: Double? + let float: Float? + let bool: Bool? + let array: [Any]? + let dictionary: [String: Any]? + let object: PerformanceImmutableMappableObject? + let objects: [PerformanceImmutableMappableObject]? + + required init(map: Map) throws { + string = try map.value("string") + int = try map.value("int") + double = try map.value("double") + float = try map.value("float") + bool = try map.value("bool") + array = try map.value("array") + dictionary = try map.value("dictionary") + object = try map.value("object") + objects = try map.value("objects") + } + + func mapping(map: Map) { + string >>> map["string"] + int >>> map["int"] + double >>> map["double"] + float >>> map["float"] + bool >>> map["bool"] + array >>> map["array"] + dictionary >>> map["dictionary"] + object >>> map["object"] + objects >>> map["objects"] + } +} + + diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/ToObjectTests.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/ToObjectTests.swift new file mode 100644 index 0000000..7c8430e --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/ToObjectTests.swift @@ -0,0 +1,207 @@ +// +// ReferenceTypesFromJSON.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2015-11-29. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2016 Hearst +// +// 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 +import XCTest +import ObjectMapper + +class ToObjectTests: XCTestCase { + + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } + + func testMappingPersonFromJSON(){ + let name = "ASDF" + let spouseName = "HJKL" + let JSONString = "{\"name\" : \"\(name)\", \"spouse\" : {\"name\" : \"\(spouseName)\"}}" + + let mappedObject = Mapper().map(JSONString: JSONString) + + XCTAssertNotNil(mappedObject) + XCTAssertEqual(mappedObject?.name, name) + XCTAssertEqual(mappedObject?.spouse?.name, spouseName) + } + + func testUpdatingChildObject(){ + let name = "ASDF" + let initialSpouseName = "HJKL" + let updatedSpouseName = "QWERTY" + let initialJSONString = "{\"name\" : \"\(name)\", \"spouse\" : {\"name\" : \"\(initialSpouseName)\"}}" + let updatedJSONString = "{\"name\" : \"\(name)\", \"spouse\" : {\"name\" : \"\(updatedSpouseName)\"}}" + + let mappedObject = Mapper().map(JSONString: initialJSONString) + let initialSpouse = mappedObject?.spouse + + XCTAssertNotNil(mappedObject) + + let updatedObject = Mapper().map(JSONString: updatedJSONString, toObject: mappedObject!) + + XCTAssert(initialSpouse === updatedObject.spouse, "Expected mapping to update the existing object not create a new one") + XCTAssertEqual(updatedObject.spouse?.name, updatedSpouseName) + XCTAssertEqual(initialSpouse?.name, updatedSpouseName) + } + + func testUpdatingChildDictionary(){ + let childKey = "child_1" + let initialChildName = "HJKL" + let updatedChildName = "QWERTY" + let initialJSONString = "{\"children\" : {\"\(childKey)\" : {\"name\" : \"\(initialChildName)\"}}}" + let updatedJSONString = "{\"children\" : {\"\(childKey)\" : {\"name\" : \"\(updatedChildName)\"}}}" + + let mappedObject = Mapper().map(JSONString: initialJSONString) + let initialChild = mappedObject?.children?[childKey] + + XCTAssertNotNil(mappedObject) + XCTAssertNotNil(initialChild) + XCTAssertEqual(initialChild?.name, initialChildName) + + _ = Mapper().map(JSONString: updatedJSONString, toObject: mappedObject!) + + let updatedChild = mappedObject?.children?[childKey] + XCTAssert(initialChild === updatedChild, "Expected mapping to update the existing object not create a new one") + XCTAssertEqual(updatedChild?.name, updatedChildName) + XCTAssertEqual(initialChild?.name, updatedChildName) + } + + func testToObjectFromString() { + let username = "bob" + let JSONString = "{\"username\":\"\(username)\"}" + + let user = User() + user.username = "Tristan" + + _ = Mapper().map(JSONString: JSONString, toObject: user) + + XCTAssertEqual(user.username, username) + } + + func testToObjectFromJSON() { + let username = "bob" + let JSON = ["username": username] + + let user = User() + user.username = "Tristan" + + _ = Mapper().map(JSON: JSON, toObject: user) + + XCTAssertEqual(username, user.username) + } + + func testToObjectFromAny() { + let username = "bob" + let userJSON = ["username": username] + + let user = User() + user.username = "Tristan" + + _ = Mapper().map(JSONObject: userJSON as Any, toObject: user) + + XCTAssertEqual(user.username, username) + } + + class Person: Mappable { + var name: String? + var spouse: Person? + var children: [String: Person]? + + required init?(map: Map) { + + } + + func mapping(map: Map) { + name <- map["name"] + spouse <- map["spouse"] + children <- map["children"] + } + } + + class User: Mappable { + + var username: String = "" + + init(){ + + } + + required init?(map: Map){ + + } + + func mapping(map: Map) { + username <- map["username"] + } + } + + struct HumanInfo: Mappable { + var name: String? + + init(name: String) { + self.name = name + } + + init?(map: Map) { + + } + + mutating func mapping(map: Map) { + name <- map["name"] + } + } + + struct Human: Mappable { + var info: HumanInfo? + + init(name: String) { + info = HumanInfo(name: name) + } + + init?(map: Map) { + + } + + mutating func mapping(map: Map) { + info <- map["info"] + } + } + + func testConsume() { + var human1 = Human(name: "QW") //has a with name "QW" + let human2 = Human(name: "ER") //has a with name "ER" + human1 = Mapper().map(JSON: human2.toJSON(), toObject: human1) + + XCTAssertEqual(human1.info?.name, human2.info?.name) + } +} + diff --git a/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/URLTransformTests.swift b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/URLTransformTests.swift new file mode 100644 index 0000000..ca0a7bc --- /dev/null +++ b/Carthage/Checkouts/ObjectMapper/Tests/ObjectMapperTests/URLTransformTests.swift @@ -0,0 +1,31 @@ +// +// URLTransformTests.swift +// ObjectMapper +// +// Created by pawel-rusin on 4/7/17. +// Copyright © 2017 hearst. All rights reserved. +// + +import XCTest +import ObjectMapper + +class URLTransformTests: XCTestCase { + + func testUrlQueryAllowed() { + let urlTransform = URLTransform() + let input = "https://example.com/search?query=foo" + let output = urlTransform.transformFromJSON(input) + + XCTAssertEqual(output, URL(string: "https://example.com/search?query=foo")) + } + + func testCanPassInAllowedCharacterSet() { + var characterSet = CharacterSet.urlQueryAllowed + characterSet.insert(charactersIn: "%") + let urlTransform = URLTransform(allowedCharacterSet: characterSet) + let input = "https://example.com/%25" + let output = urlTransform.transformFromJSON(input) + + XCTAssertEqual(output, URL(string: "https://example.com/%25")) + } +} diff --git a/Example/APNSUtil.xcodeproj/project.pbxproj b/Example/APNSUtil.xcodeproj/project.pbxproj index 0ed86fc..fa84969 100644 --- a/Example/APNSUtil.xcodeproj/project.pbxproj +++ b/Example/APNSUtil.xcodeproj/project.pbxproj @@ -323,15 +323,11 @@ inputPaths = ( "${SRCROOT}/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example-frameworks.sh", "${BUILT_PRODUCTS_DIR}/APNSUtil/APNSUtil.framework", - "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework", - "${BUILT_PRODUCTS_DIR}/AlamofireObjectMapper/AlamofireObjectMapper.framework", "${BUILT_PRODUCTS_DIR}/ObjectMapper/ObjectMapper.framework", ); name = "[CP] Embed Pods Frameworks"; outputPaths = ( "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/APNSUtil.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AlamofireObjectMapper.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ObjectMapper.framework", ); runOnlyForDeploymentPostprocessing = 0; @@ -468,7 +464,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.3; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -514,7 +510,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.3; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; @@ -528,12 +524,13 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = APNSUtil/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; MODULE_NAME = ExampleApp; PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_SWIFT3_OBJC_INFERENCE = Default; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -543,12 +540,13 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = APNSUtil/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; MODULE_NAME = ExampleApp; PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_SWIFT3_OBJC_INFERENCE = Default; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 3.0; }; name = Release; }; diff --git a/Example/APNSUtil/AppDelegate.swift b/Example/APNSUtil/AppDelegate.swift index 9f404ca..247bff9 100644 --- a/Example/APNSUtil/AppDelegate.swift +++ b/Example/APNSUtil/AppDelegate.swift @@ -35,18 +35,18 @@ class AppDelegate: UIResponder, UIApplicationDelegate { application.registerForRemoteNotifications() } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) { - APNSManager.shared.received(APNSPayload.self, userInfo: userInfo, isInactive: application.applicationState == .inactive) + APNSManager.shared.didReceive(userInfo: userInfo, as: APNSPayload.self, isInactive: application.applicationState == .inactive) } // MARK: - Push Notification for iOS 10 or higher @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { - APNSManager.shared.received(APNSPayload.self, userInfo: notification.request.content.userInfo, isInactive: false) + APNSManager.shared.didReceive(userInfo: notification.request.content.userInfo, as: APNSPayload.self, isInactive: false) } @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { - APNSManager.shared.received(APNSPayload.self, userInfo: response.notification.request.content.userInfo, isInactive: true) + APNSManager.shared.didReceive(userInfo: response.notification.request.content.userInfo, as: APNSPayload.self, isInactive: true) } } diff --git a/Example/Podfile.lock b/Example/Podfile.lock index d91c5f7..a897b26 100644 --- a/Example/Podfile.lock +++ b/Example/Podfile.lock @@ -1,11 +1,7 @@ PODS: - - Alamofire (4.6.0) - - AlamofireObjectMapper (5.0.0): - - Alamofire (~> 4.1) - - ObjectMapper (~> 3.0) - APNSUtil (1.0.0): - - AlamofireObjectMapper (~> 5.0.0) - - ObjectMapper (3.1.0) + - ObjectMapper (~> 2.0) + - ObjectMapper (2.0.0) DEPENDENCIES: - APNSUtil (from `../`) @@ -15,10 +11,8 @@ EXTERNAL SOURCES: :path: ../ SPEC CHECKSUMS: - Alamofire: f41a599bd63041760b26d393ec1069d9d7b917f4 - AlamofireObjectMapper: 5fafc816351cbbc0d486611aaeba7461c0cbad49 - APNSUtil: dd57ed78950e8eace6889403997f62f86e9996b3 - ObjectMapper: 20505058f54e5c3ca69e1d6de9897d152a5369a6 + APNSUtil: c39a8a3327a2fc5df8a961cc0c766bd674073a35 + ObjectMapper: aed2570edabbd3c9b26c939e1cabdb6558f933e0 PODFILE CHECKSUM: 613e78454e33684404b49d733e0a3a475e0ef3f8 diff --git a/Example/Pods/Alamofire/LICENSE b/Example/Pods/Alamofire/LICENSE deleted file mode 100644 index 1654602..0000000 --- a/Example/Pods/Alamofire/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2014-2017 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/Example/Pods/Alamofire/README.md b/Example/Pods/Alamofire/README.md deleted file mode 100644 index eb5a522..0000000 --- a/Example/Pods/Alamofire/README.md +++ /dev/null @@ -1,236 +0,0 @@ -![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)](http://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](Documentation/Usage.md) - - **Intro -** [Making a Request](Documentation/Usage.md#making-a-request), [Response Handling](Documentation/Usage.md#response-handling), [Response Validation](Documentation/Usage.md#response-validation), [Response Caching](Documentation/Usage.md#response-caching) - - **HTTP -** [HTTP Methods](Documentation/Usage.md#http-methods), [Parameter Encoding](Documentation/Usage.md#parameter-encoding), [HTTP Headers](Documentation/Usage.md#http-headers), [Authentication](Documentation/Usage.md#authentication) - - **Large Data -** [Downloading Data to a File](Documentation/Usage.md#downloading-data-to-a-file), [Uploading Data to a Server](Documentation/Usage.md#uploading-data-to-a-server) - - **Tools -** [Statistical Metrics](Documentation/Usage.md#statistical-metrics), [cURL Command Output](Documentation/Usage.md#curl-command-output) -- [Advanced Usage](Documentation/AdvancedUsage.md) - - **URL Session -** [Session Manager](Documentation/AdvancedUsage.md#session-manager), [Session Delegate](Documentation/AdvancedUsage.md#session-delegate), [Request](Documentation/AdvancedUsage.md#request) - - **Routing -** [Routing Requests](Documentation/AdvancedUsage.md#routing-requests), [Adapting and Retrying Requests](Documentation/AdvancedUsage.md#adapting-and-retrying-requests) - - **Model Objects -** [Custom Response Serialization](Documentation/AdvancedUsage.md#custom-response-serialization) - - **Connection -** [Security](Documentation/AdvancedUsage.md#security), [Network Reachability](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](http://stackoverflow.com/questions/tagged/alamofire). (Tag 'alamofire') -- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). -- If you **found a bug**, open an issue. -- If you **have a feature request**, open an issue. -- If you **want to contribute**, submit a pull request. - -## Installation - -### CocoaPods - -[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: - -```bash -$ gem install cocoapods -``` - -> CocoaPods 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.5' -end -``` - -Then, run the following command: - -```bash -$ pod install -``` - -### Carthage - -[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. - -You can install Carthage with [Homebrew](http://brew.sh/) using the following command: - -```bash -$ brew update -$ brew install carthage -``` - -To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: - -```ogdl -github "Alamofire/Alamofire" ~> 4.5 -``` - -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](http://git-scm.com/docs/git-submodule) by running the following command: - - ```bash - $ git submodule add https://github.com/Alamofire/Alamofire.git - ``` - -- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. - - > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. - -- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. -- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. -- In the tab bar at the top of that window, open the "General" panel. -- Click on the `+` button under the "Embedded Binaries" section. -- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. - - > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. - -- Select the top `Alamofire.framework` for iOS and the bottom one for OS X. - - > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS`, `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` - -## 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 register as a federal non-profit organization. Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. Donating to the ASF will enable us to: - -- Pay our legal fees to register as a federal non-profit organization -- Pay our yearly legal fees to keep the non-profit in good status -- Pay for our mail servers to help us stay on top of all questions and security issues -- Potentially fund test servers to make it easier for us to test the edge cases -- Potentially fund developers to work on one of our projects full-time - -The community adoption of the ASF libraries has been amazing. We are greatly humbled by your 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. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. - -Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com ! - -## License - -Alamofire is released under the MIT license. [See LICENSE](https://github.com/Alamofire/Alamofire/blob/master/LICENSE) for details. diff --git a/Example/Pods/Alamofire/Source/AFError.swift b/Example/Pods/Alamofire/Source/AFError.swift deleted file mode 100644 index 585ae14..0000000 --- a/Example/Pods/Alamofire/Source/AFError.swift +++ /dev/null @@ -1,460 +0,0 @@ -// -// AFError.swift -// -// Copyright (c) 2014-2017 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/Example/Pods/Alamofire/Source/Alamofire.swift b/Example/Pods/Alamofire/Source/Alamofire.swift deleted file mode 100644 index e971613..0000000 --- a/Example/Pods/Alamofire/Source/Alamofire.swift +++ /dev/null @@ -1,465 +0,0 @@ -// -// Alamofire.swift -// -// Copyright (c) 2014-2017 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/Example/Pods/Alamofire/Source/MultipartFormData.swift b/Example/Pods/Alamofire/Source/MultipartFormData.swift deleted file mode 100644 index ba02d24..0000000 --- a/Example/Pods/Alamofire/Source/MultipartFormData.swift +++ /dev/null @@ -1,580 +0,0 @@ -// -// MultipartFormData.swift -// -// Copyright (c) 2014-2017 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/Example/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/Example/Pods/Alamofire/Source/NetworkReachabilityManager.swift deleted file mode 100644 index cdb5a02..0000000 --- a/Example/Pods/Alamofire/Source/NetworkReachabilityManager.swift +++ /dev/null @@ -1,233 +0,0 @@ -// -// NetworkReachabilityManager.swift -// -// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -#if !os(watchOS) - -import Foundation -import SystemConfiguration - -/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and -/// WiFi network interfaces. -/// -/// Reachability can be used to determine background information about why a network operation failed, or to retry -/// network requests when a connection is established. It should not be used to prevent a user from initiating a network -/// request, as it's possible that an initial request may be required to establish reachability. -public class NetworkReachabilityManager { - /// Defines the various states of network reachability. - /// - /// - unknown: It is unknown whether the network is reachable. - /// - notReachable: The network is not reachable. - /// - 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. - public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } - - /// Whether the network is currently reachable over the WWAN interface. - public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) } - - /// Whether the network is currently reachable over Ethernet or WiFi interface. - public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } - - /// The current network reachability status. - public var networkReachabilityStatus: NetworkReachabilityStatus { - guard let flags = self.flags else { return .unknown } - return networkReachabilityStatusForFlags(flags) - } - - /// The dispatch queue to execute the `listener` closure on. - public var listenerQueue: DispatchQueue = DispatchQueue.main - - /// A closure executed when the network reachability status changes. - public var listener: Listener? - - private var flags: SCNetworkReachabilityFlags? { - var flags = SCNetworkReachabilityFlags() - - if SCNetworkReachabilityGetFlags(reachability, &flags) { - return flags - } - - return nil - } - - private let reachability: SCNetworkReachability - private var previousFlags: SCNetworkReachabilityFlags - - // MARK: - Initialization - - /// Creates a `NetworkReachabilityManager` instance with the specified host. - /// - /// - parameter host: The host used to evaluate network reachability. - /// - /// - returns: The new `NetworkReachabilityManager` instance. - public convenience init?(host: String) { - guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } - self.init(reachability: reachability) - } - - /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. - /// - /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing - /// status of the device, both IPv4 and IPv6. - /// - /// - returns: The new `NetworkReachabilityManager` instance. - public convenience init?() { - var address = sockaddr_in() - address.sin_len = UInt8(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 - public 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. - public func stopListening() { - SCNetworkReachabilitySetCallback(reachability, nil, nil) - SCNetworkReachabilitySetDispatchQueue(reachability, nil) - } - - // MARK: - Internal - Listener Notification - - func notifyListener(_ flags: SCNetworkReachabilityFlags) { - guard previousFlags != flags else { return } - previousFlags = flags - - listener?(networkReachabilityStatusForFlags(flags)) - } - - // MARK: - Internal - Network Reachability Status - - func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { - guard 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/Example/Pods/Alamofire/Source/Notifications.swift b/Example/Pods/Alamofire/Source/Notifications.swift deleted file mode 100644 index df41505..0000000 --- a/Example/Pods/Alamofire/Source/Notifications.swift +++ /dev/null @@ -1,52 +0,0 @@ -// -// Notifications.swift -// -// Copyright (c) 2014-2017 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" - } -} diff --git a/Example/Pods/Alamofire/Source/ParameterEncoding.swift b/Example/Pods/Alamofire/Source/ParameterEncoding.swift deleted file mode 100644 index dabb562..0000000 --- a/Example/Pods/Alamofire/Source/ParameterEncoding.swift +++ /dev/null @@ -1,432 +0,0 @@ -// -// ParameterEncoding.swift -// -// Copyright (c) 2014-2017 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`. Since there is no published specification for how to encode -/// collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending -/// the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). -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 - } - - // 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 - - // MARK: Initialization - - /// Creates a `URLEncoding` instance using the specified destination. - /// - /// - parameter destination: The destination defining where the encoded query string is to be applied. - /// - /// - returns: The new `URLEncoding` instance. - public init(destination: Destination = .methodDependent) { - self.destination = destination - } - - // 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: "\(key)[]", value: value) - } - } else if let value = value as? NSNumber { - if value.isBool { - components.append((escape(key), escape((value.boolValue ? "1" : "0")))) - } else { - components.append((escape(key), escape("\(value)"))) - } - } else if let bool = value as? Bool { - components.append((escape(key), escape((bool ? "1" : "0")))) - } 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/Example/Pods/Alamofire/Source/Request.swift b/Example/Pods/Alamofire/Source/Request.swift deleted file mode 100644 index d93c52d..0000000 --- a/Example/Pods/Alamofire/Source/Request.swift +++ /dev/null @@ -1,653 +0,0 @@ -// -// Request.swift -// -// Copyright (c) 2014-2017 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. - open 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 static 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/Example/Pods/Alamofire/Source/Response.swift b/Example/Pods/Alamofire/Source/Response.swift deleted file mode 100644 index 814662c..0000000 --- a/Example/Pods/Alamofire/Source/Response.swift +++ /dev/null @@ -1,567 +0,0 @@ -// -// Response.swift -// -// Copyright (c) 2014-2017 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/Example/Pods/Alamofire/Source/ResponseSerialization.swift b/Example/Pods/Alamofire/Source/ResponseSerialization.swift deleted file mode 100644 index 1f29ed8..0000000 --- a/Example/Pods/Alamofire/Source/ResponseSerialization.swift +++ /dev/null @@ -1,715 +0,0 @@ -// -// ResponseSerialization.swift -// -// Copyright (c) 2014-2017 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 ?? String.Encoding.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/Example/Pods/Alamofire/Source/Result.swift b/Example/Pods/Alamofire/Source/Result.swift deleted file mode 100644 index bbd3c61..0000000 --- a/Example/Pods/Alamofire/Source/Result.swift +++ /dev/null @@ -1,300 +0,0 @@ -// -// Result.swift -// -// Copyright (c) 2014-2017 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/Example/Pods/Alamofire/Source/ServerTrustPolicy.swift b/Example/Pods/Alamofire/Source/ServerTrustPolicy.swift deleted file mode 100644 index 1ad3530..0000000 --- a/Example/Pods/Alamofire/Source/ServerTrustPolicy.swift +++ /dev/null @@ -1,307 +0,0 @@ -// -// ServerTrustPolicy.swift -// -// Copyright (c) 2014-2017 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. - open 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/Example/Pods/Alamofire/Source/SessionDelegate.swift b/Example/Pods/Alamofire/Source/SessionDelegate.swift deleted file mode 100644 index d38c253..0000000 --- a/Example/Pods/Alamofire/Source/SessionDelegate.swift +++ /dev/null @@ -1,719 +0,0 @@ -// -// SessionDelegate.swift -// -// Copyright (c) 2014-2017 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? - - private 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) - - NotificationCenter.default.post( - name: Notification.Name.Task.DidComplete, - object: strongSelf, - userInfo: [Notification.Key.Task: task] - ) - - 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/Example/Pods/Alamofire/Source/SessionManager.swift b/Example/Pods/Alamofire/Source/SessionManager.swift deleted file mode 100644 index 0ff677b..0000000 --- a/Example/Pods/Alamofire/Source/SessionManager.swift +++ /dev/null @@ -1,892 +0,0 @@ -// -// SessionManager.swift -// -// Copyright (c) 2014-2017 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. - open 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. - open 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. - open static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000 - - /// The underlying session. - open let session: URLSession - - /// The session delegate handling all the task and session delegate callbacks. - open 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) - - 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/Example/Pods/Alamofire/Source/TaskDelegate.swift b/Example/Pods/Alamofire/Source/TaskDelegate.swift deleted file mode 100644 index 0607758..0000000 --- a/Example/Pods/Alamofire/Source/TaskDelegate.swift +++ /dev/null @@ -1,466 +0,0 @@ -// -// TaskDelegate.swift -// -// Copyright (c) 2014-2017 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. - open 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/Example/Pods/Alamofire/Source/Timeline.swift b/Example/Pods/Alamofire/Source/Timeline.swift deleted file mode 100644 index c5dabd1..0000000 --- a/Example/Pods/Alamofire/Source/Timeline.swift +++ /dev/null @@ -1,136 +0,0 @@ -// -// Timeline.swift -// -// Copyright (c) 2014-2017 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/Example/Pods/Alamofire/Source/Validation.swift b/Example/Pods/Alamofire/Source/Validation.swift deleted file mode 100644 index 989ac20..0000000 --- a/Example/Pods/Alamofire/Source/Validation.swift +++ /dev/null @@ -1,315 +0,0 @@ -// -// Validation.swift -// -// Copyright (c) 2014-2017 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/Example/Pods/AlamofireObjectMapper/AlamofireObjectMapper/AlamofireObjectMapper.swift b/Example/Pods/AlamofireObjectMapper/AlamofireObjectMapper/AlamofireObjectMapper.swift deleted file mode 100644 index b181e84..0000000 --- a/Example/Pods/AlamofireObjectMapper/AlamofireObjectMapper/AlamofireObjectMapper.swift +++ /dev/null @@ -1,205 +0,0 @@ -// -// Request.swift -// AlamofireObjectMapper -// -// Created by Tristan Himmelman on 2015-04-30. -// -// The MIT License (MIT) -// -// Copyright (c) 2014-2015 Tristan Himmelman -// -// 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 -import Alamofire -import ObjectMapper - -extension DataRequest { - - enum ErrorCode: Int { - case noData = 1 - case dataSerializationFailed = 2 - } - - internal static func newError(_ code: ErrorCode, failureReason: String) -> NSError { - let errorDomain = "com.alamofireobjectmapper.error" - - let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] - let returnError = NSError(domain: errorDomain, code: code.rawValue, userInfo: userInfo) - - return returnError - } - - /// Utility function for checking for errors in response - internal static func checkResponseForError(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) -> Error? { - if let error = error { - return error - } - guard let _ = data else { - let failureReason = "Data could not be serialized. Input data was nil." - let error = newError(.noData, failureReason: failureReason) - return error - } - return nil - } - - /// Utility function for extracting JSON from response - internal static func processResponse(request: URLRequest?, response: HTTPURLResponse?, data: Data?, keyPath: String?) -> Any? { - let jsonResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) - let result = jsonResponseSerializer.serializeResponse(request, response, data, nil) - - let JSON: Any? - if let keyPath = keyPath , keyPath.isEmpty == false { - JSON = (result.value as AnyObject?)?.value(forKeyPath: keyPath) - } else { - JSON = result.value - } - - return JSON - } - - /// BaseMappable Object Serializer - public static func ObjectMapperSerializer(_ keyPath: String?, mapToObject object: T? = nil, context: MapContext? = nil) -> DataResponseSerializer { - return DataResponseSerializer { request, response, data, error in - if let error = checkResponseForError(request: request, response: response, data: data, error: error){ - return .failure(error) - } - - let JSONObject = processResponse(request: request, response: response, data: data, keyPath: keyPath) - - if let object = object { - _ = Mapper(context: context, shouldIncludeNilValues: false).map(JSONObject: JSONObject, toObject: object) - return .success(object) - } else if let parsedObject = Mapper(context: context, shouldIncludeNilValues: false).map(JSONObject: JSONObject){ - return .success(parsedObject) - } - - let failureReason = "ObjectMapper failed to serialize response." - let error = newError(.dataSerializationFailed, failureReason: failureReason) - return .failure(error) - } - } - - /// ImmutableMappable Array Serializer - public static func ObjectMapperImmutableSerializer(_ keyPath: String?, context: MapContext? = nil) -> DataResponseSerializer { - return DataResponseSerializer { request, response, data, error in - if let error = checkResponseForError(request: request, response: response, data: data, error: error){ - return .failure(error) - } - - let JSONObject = processResponse(request: request, response: response, data: data, keyPath: keyPath) - - if let JSONObject = JSONObject, - let parsedObject = (try? Mapper(context: context, shouldIncludeNilValues: false).map(JSONObject: JSONObject)){ - return .success(parsedObject) - } - - let failureReason = "ObjectMapper failed to serialize response." - let error = newError(.dataSerializationFailed, failureReason: failureReason) - return .failure(error) - } - } - - /** - Adds a handler to be called once the request has finished. - - - parameter queue: The queue on which the completion handler is dispatched. - - parameter keyPath: The key path where object mapping should be performed - - parameter object: An object to perform the mapping on to - - parameter completionHandler: A closure to be executed once the request has finished and the data has been mapped by ObjectMapper. - - - returns: The request. - */ - @discardableResult - public func responseObject(queue: DispatchQueue? = nil, keyPath: String? = nil, mapToObject object: T? = nil, context: MapContext? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return response(queue: queue, responseSerializer: DataRequest.ObjectMapperSerializer(keyPath, mapToObject: object, context: context), completionHandler: completionHandler) - } - - @discardableResult - public func responseObject(queue: DispatchQueue? = nil, keyPath: String? = nil, mapToObject object: T? = nil, context: MapContext? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { - return response(queue: queue, responseSerializer: DataRequest.ObjectMapperImmutableSerializer(keyPath, context: context), completionHandler: completionHandler) - } - - /// BaseMappable Array Serializer - public static func ObjectMapperArraySerializer(_ keyPath: String?, context: MapContext? = nil) -> DataResponseSerializer<[T]> { - return DataResponseSerializer { request, response, data, error in - if let error = checkResponseForError(request: request, response: response, data: data, error: error){ - return .failure(error) - } - - let JSONObject = processResponse(request: request, response: response, data: data, keyPath: keyPath) - - if let parsedObject = Mapper(context: context, shouldIncludeNilValues: false).mapArray(JSONObject: JSONObject){ - return .success(parsedObject) - } - - let failureReason = "ObjectMapper failed to serialize response." - let error = newError(.dataSerializationFailed, failureReason: failureReason) - return .failure(error) - } - } - - /// ImmutableMappable Array Serializer - public static func ObjectMapperImmutableArraySerializer(_ keyPath: String?, context: MapContext? = nil) -> DataResponseSerializer<[T]> { - return DataResponseSerializer { request, response, data, error in - if let error = checkResponseForError(request: request, response: response, data: data, error: error){ - return .failure(error) - } - - if let JSONObject = processResponse(request: request, response: response, data: data, keyPath: keyPath){ - - if let parsedObject = try? Mapper(context: context, shouldIncludeNilValues: false).mapArray(JSONObject: JSONObject){ - return .success(parsedObject) - } - } - - let failureReason = "ObjectMapper failed to serialize response." - let error = newError(.dataSerializationFailed, failureReason: failureReason) - return .failure(error) - } - } - - /** - Adds a handler to be called once the request has finished. T: BaseMappable - - - parameter queue: The queue on which the completion handler is dispatched. - - parameter keyPath: The key path where object mapping should be performed - - parameter completionHandler: A closure to be executed once the request has finished and the data has been mapped by ObjectMapper. - - - returns: The request. - */ - @discardableResult - public func responseArray(queue: DispatchQueue? = nil, keyPath: String? = nil, context: MapContext? = nil, completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self { - return response(queue: queue, responseSerializer: DataRequest.ObjectMapperArraySerializer(keyPath, context: context), completionHandler: completionHandler) - } - - /** - Adds a handler to be called once the request has finished. T: ImmutableMappable - - - parameter queue: The queue on which the completion handler is dispatched. - - parameter keyPath: The key path where object mapping should be performed - - parameter completionHandler: A closure to be executed once the request has finished and the data has been mapped by ObjectMapper. - - - returns: The request. - */ - @discardableResult - public func responseArray(queue: DispatchQueue? = nil, keyPath: String? = nil, context: MapContext? = nil, completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self { - return response(queue: queue, responseSerializer: DataRequest.ObjectMapperImmutableArraySerializer(keyPath, context: context), completionHandler: completionHandler) - } -} diff --git a/Example/Pods/AlamofireObjectMapper/LICENSE b/Example/Pods/AlamofireObjectMapper/LICENSE deleted file mode 100644 index cee2d0c..0000000 --- a/Example/Pods/AlamofireObjectMapper/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Tristan Himmelman - -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/Example/Pods/AlamofireObjectMapper/README.md b/Example/Pods/AlamofireObjectMapper/README.md deleted file mode 100644 index 7e89fd4..0000000 --- a/Example/Pods/AlamofireObjectMapper/README.md +++ /dev/null @@ -1,192 +0,0 @@ -AlamofireObjectMapper -============ -[![Build Status](https://travis-ci.org/tristanhimmelman/AlamofireObjectMapper.svg?branch=master)](https://travis-ci.org/tristanhimmelman/AlamofireObjectMapper) -[![CocoaPods](https://img.shields.io/cocoapods/v/AlamofireObjectMapper.svg)](https://github.com/tristanhimmelman/AlamofireObjectMapper) -[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) - - -An extension to [Alamofire](https://github.com/Alamofire/Alamofire) which automatically converts JSON response data into swift objects using [ObjectMapper](https://github.com/Hearst-DD/ObjectMapper/). - -# Usage - -Given a URL which returns weather data in the following form: -``` -{ - "location": "Toronto, Canada", - "three_day_forecast": [ - { - "conditions": "Partly cloudy", - "day" : "Monday", - "temperature": 20 - }, - { - "conditions": "Showers", - "day" : "Tuesday", - "temperature": 22 - }, - { - "conditions": "Sunny", - "day" : "Wednesday", - "temperature": 28 - } - ] -} -``` - -You can use the extension as the follows: -```swift -import AlamofireObjectMapper - -let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/d8bb95982be8a11a2308e779bb9a9707ebe42ede/sample_json" -Alamofire.request(URL).responseObject { (response: DataResponse) in - - let weatherResponse = response.result.value - print(weatherResponse?.location) - - if let threeDayForecast = weatherResponse?.threeDayForecast { - for forecast in threeDayForecast { - print(forecast.day) - print(forecast.temperature) - } - } -} -``` - -The `WeatherResponse` object in the completion handler is a custom object which you define. The only requirement is that the object must conform to [ObjectMapper's](https://github.com/Hearst-DD/ObjectMapper/) `Mappable` protocol. In the above example, the `WeatherResponse` object looks like the following: - -```swift -import ObjectMapper - -class WeatherResponse: Mappable { - var location: String? - var threeDayForecast: [Forecast]? - - required init?(map: Map){ - - } - - func mapping(map: Map) { - location <- map["location"] - threeDayForecast <- map["three_day_forecast"] - } -} - -class Forecast: Mappable { - var day: String? - var temperature: Int? - var conditions: String? - - required init?(map: Map){ - - } - - func mapping(map: Map) { - day <- map["day"] - temperature <- map["temperature"] - conditions <- map["conditions"] - } -} -``` - -The extension uses Generics to allow you to create your own custom response objects. Below is the `responseObject` function definition. Just replace `T` in the completionHandler with your custom response object and the extension handles the rest: -```swift -public func responseObject(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, mapToObject object: T? = nil, completionHandler: DataResponse -> Void) -> Self -``` -The `responseObject` function has 3 optional parameters and a required completionHandler: -- `queue`: The queue on which the completion handler is dispatched. -- `keyPath`: The key path of the JSON where object mapping should be performed -- `mapToObject`: An object to perform the mapping on to -- `completionHandler`: A closure to be executed once the request has finished and the data has been mapped by ObjectMapper. - -### Easy Mapping of Nested Objects - -AlamofireObjectMapper supports dot notation within keys for easy mapping of nested objects. Given the following JSON String: -```json -"distance" : { - "text" : "102 ft", - "value" : 31 -} -``` -You can access the nested objects as follows: -```swift -func mapping(map: Map) { - distance <- map["distance.value"] -} -``` -[See complete documentation](https://github.com/Hearst-DD/ObjectMapper#easy-mapping-of-nested-objects) - -### KeyPath - -The `keyPath` variable is used to drill down into a JSON response and only map the data found at that `keyPath`. It supports nested values such as `data.weather` to drill down several levels in a JSON response. -```swift -let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/2ee8f34d21e8febfdefb2b3a403f18a43818d70a/sample_keypath_json" -let expectation = expectationWithDescription("\(URL)") - -Alamofire.request(URL).responseObject(keyPath: "data") { (response: DataResponse) in - expectation.fulfill() - - let weatherResponse = response.result.value - print(weatherResponse?.location) - - if let threeDayForecast = weatherResponse?.threeDayForecast { - for forecast in threeDayForecast { - print(forecast.day) - print(forecast.temperature) - } - } -} -``` - -# Array Responses -If you have an endpoint that returns data in `Array` form you can map it with the following function: -```swift -public func responseArray(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, completionHandler: DataResponse<[T]> -> Void) -> Self -``` - -For example, if your endpoint returns the following: -``` -[ - { - "conditions": "Partly cloudy", - "day" : "Monday", - "temperature": 20 - }, - { - "conditions": "Showers", - "day" : "Tuesday", - "temperature": 22 - }, - { - "conditions": "Sunny", - "day" : "Wednesday", - "temperature": 28 - } -] -``` -You can request and map it as follows: -```swift -let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/f583be1121dbc5e9b0381b3017718a70c31054f7/sample_array_json" -Alamofire.request(URL).responseArray { (response: DataResponse<[Forecast]>) in - - let forecastArray = response.result.value - - if let forecastArray = forecastArray { - for forecast in forecastArray { - print(forecast.day) - print(forecast.temperature) - } - } -} - -``` - -# Installation -AlamofireObjectMapper can be added to your project using [CocoaPods](https://cocoapods.org/) by adding the following line to your Podfile: -``` -pod 'AlamofireObjectMapper', '~> 4.0' -``` - -If you're using [Carthage](https://github.com/Carthage/Carthage) you can add a dependency on AlamofireObjectMapper by adding it to your Cartfile: -``` -github "tristanhimmelman/AlamofireObjectMapper" ~> 4.0 -``` diff --git a/Example/Pods/Local Podspecs/APNSUtil.podspec.json b/Example/Pods/Local Podspecs/APNSUtil.podspec.json index 968f939..0912119 100644 --- a/Example/Pods/Local Podspecs/APNSUtil.podspec.json +++ b/Example/Pods/Local Podspecs/APNSUtil.podspec.json @@ -1,8 +1,8 @@ { "name": "APNSUtil", "version": "1.0.0", - "summary": "APNSUtil is makes code simple for apple push notification service.", - "description": "APNSUtil is makes code simple for apple push notification service.", + "summary": "APNSUtil is makes code simple using apple push notification service.", + "description": "APNSUtil is makes code simple using apple push notification service.", "homepage": "https://github.com/pisces/APNSUtil", "license": { "type": "MIT", @@ -16,12 +16,12 @@ "tag": "1.0.0" }, "platforms": { - "ios": "8.0" + "ios": "9.0" }, "source_files": "APNSUtil/Classes/**/*", "dependencies": { - "AlamofireObjectMapper": [ - "~> 5.0.0" + "ObjectMapper": [ + "~> 2.0" ] } } diff --git a/Example/Pods/Manifest.lock b/Example/Pods/Manifest.lock index d91c5f7..a897b26 100644 --- a/Example/Pods/Manifest.lock +++ b/Example/Pods/Manifest.lock @@ -1,11 +1,7 @@ PODS: - - Alamofire (4.6.0) - - AlamofireObjectMapper (5.0.0): - - Alamofire (~> 4.1) - - ObjectMapper (~> 3.0) - APNSUtil (1.0.0): - - AlamofireObjectMapper (~> 5.0.0) - - ObjectMapper (3.1.0) + - ObjectMapper (~> 2.0) + - ObjectMapper (2.0.0) DEPENDENCIES: - APNSUtil (from `../`) @@ -15,10 +11,8 @@ EXTERNAL SOURCES: :path: ../ SPEC CHECKSUMS: - Alamofire: f41a599bd63041760b26d393ec1069d9d7b917f4 - AlamofireObjectMapper: 5fafc816351cbbc0d486611aaeba7461c0cbad49 - APNSUtil: dd57ed78950e8eace6889403997f62f86e9996b3 - ObjectMapper: 20505058f54e5c3ca69e1d6de9897d152a5369a6 + APNSUtil: c39a8a3327a2fc5df8a961cc0c766bd674073a35 + ObjectMapper: aed2570edabbd3c9b26c939e1cabdb6558f933e0 PODFILE CHECKSUM: 613e78454e33684404b49d733e0a3a475e0ef3f8 diff --git a/Example/Pods/ObjectMapper/ObjectMapper/Core/FromJSON.swift b/Example/Pods/ObjectMapper/ObjectMapper/Core/FromJSON.swift new file mode 100755 index 0000000..336c8f1 --- /dev/null +++ b/Example/Pods/ObjectMapper/ObjectMapper/Core/FromJSON.swift @@ -0,0 +1,181 @@ +// +// FromJSON.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-09. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2015 Hearst +// +// 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. + +internal final class FromJSON { + + /// Basic type + class func basicType(_ field: inout FieldType, object: FieldType?) { + if let value = object { + field = value + } + } + + /// optional basic type + class func optionalBasicType(_ field: inout FieldType?, object: FieldType?) { + field = object + } + + /// Implicitly unwrapped optional basic type + class func optionalBasicType(_ field: inout FieldType!, object: FieldType?) { + field = object + } + + /// Mappable object + class func object(_ field: inout N, map: Map) { + if map.toObject { + _ = Mapper(context: map.context).map(JSONObject: map.currentValue, toObject: field) + } else if let value: N = Mapper(context: map.context).map(JSONObject: map.currentValue) { + field = value + } + } + + /// Optional Mappable Object + + class func optionalObject(_ field: inout N?, map: Map) { + if let field = field , map.toObject && map.currentValue != nil { + _ = Mapper(context: map.context).map(JSONObject: map.currentValue, toObject: field) + } else { + field = Mapper(context: map.context).map(JSONObject: map.currentValue) + } + } + + /// Implicitly unwrapped Optional Mappable Object + class func optionalObject(_ field: inout N!, map: Map) { + if let field = field , map.toObject && map.currentValue != nil { + _ = Mapper(context: map.context).map(JSONObject: map.currentValue, toObject: field) + } else { + field = Mapper(context: map.context).map(JSONObject: map.currentValue) + } + } + + /// mappable object array + class func objectArray(_ field: inout Array, map: Map) { + if let objects = Mapper(context: map.context).mapArray(JSONObject: map.currentValue) { + field = objects + } + } + + /// optional mappable object array + + class func optionalObjectArray(_ field: inout Array?, map: Map) { + if let objects: Array = Mapper(context: map.context).mapArray(JSONObject: map.currentValue) { + field = objects + } else { + field = nil + } + } + + /// Implicitly unwrapped optional mappable object array + class func optionalObjectArray(_ field: inout Array!, map: Map) { + if let objects: Array = Mapper(context: map.context).mapArray(JSONObject: map.currentValue) { + field = objects + } else { + field = nil + } + } + + /// mappable object array + class func twoDimensionalObjectArray(_ field: inout Array>, map: Map) { + if let objects = Mapper(context: map.context).mapArrayOfArrays(JSONObject: map.currentValue) { + field = objects + } + } + + /// optional mappable 2 dimentional object array + class func optionalTwoDimensionalObjectArray(_ field: inout Array>?, map: Map) { + field = Mapper(context: map.context).mapArrayOfArrays(JSONObject: map.currentValue) + } + + /// Implicitly unwrapped optional 2 dimentional mappable object array + class func optionalTwoDimensionalObjectArray(_ field: inout Array>!, map: Map) { + field = Mapper(context: map.context).mapArrayOfArrays(JSONObject: map.currentValue) + } + + /// Dctionary containing Mappable objects + class func objectDictionary(_ field: inout Dictionary, map: Map) { + if map.toObject { + _ = Mapper(context: map.context).mapDictionary(JSONObject: map.currentValue, toDictionary: field) + } else { + if let objects = Mapper(context: map.context).mapDictionary(JSONObject: map.currentValue) { + field = objects + } + } + } + + /// Optional dictionary containing Mappable objects + class func optionalObjectDictionary(_ field: inout Dictionary?, map: Map) { + if let field = field , map.toObject && map.currentValue != nil { + _ = Mapper(context: map.context).mapDictionary(JSONObject: map.currentValue, toDictionary: field) + } else { + field = Mapper(context: map.context).mapDictionary(JSONObject: map.currentValue) + } + } + + /// Implicitly unwrapped Dictionary containing Mappable objects + class func optionalObjectDictionary(_ field: inout Dictionary!, map: Map) { + if let field = field , map.toObject && map.currentValue != nil { + _ = Mapper(context: map.context).mapDictionary(JSONObject: map.currentValue, toDictionary: field) + } else { + field = Mapper(context: map.context).mapDictionary(JSONObject: map.currentValue) + } + } + + /// Dictionary containing Array of Mappable objects + class func objectDictionaryOfArrays(_ field: inout Dictionary, map: Map) { + if let objects = Mapper(context: map.context).mapDictionaryOfArrays(JSONObject: map.currentValue) { + field = objects + } + } + + /// Optional Dictionary containing Array of Mappable objects + class func optionalObjectDictionaryOfArrays(_ field: inout Dictionary?, map: Map) { + field = Mapper(context: map.context).mapDictionaryOfArrays(JSONObject: map.currentValue) + } + + /// Implicitly unwrapped Dictionary containing Array of Mappable objects + class func optionalObjectDictionaryOfArrays(_ field: inout Dictionary!, map: Map) { + field = Mapper(context: map.context).mapDictionaryOfArrays(JSONObject: map.currentValue) + } + + /// mappable object Set + class func objectSet(_ field: inout Set, map: Map) { + if let objects = Mapper(context: map.context).mapSet(JSONObject: map.currentValue) { + field = objects + } + } + + /// optional mappable object array + class func optionalObjectSet(_ field: inout Set?, map: Map) { + field = Mapper(context: map.context).mapSet(JSONObject: map.currentValue) + } + + /// Implicitly unwrapped optional mappable object array + class func optionalObjectSet(_ field: inout Set!, map: Map) { + field = Mapper(context: map.context).mapSet(JSONObject: map.currentValue) + } +} diff --git a/Example/Pods/ObjectMapper/ObjectMapper/Core/Map.swift b/Example/Pods/ObjectMapper/ObjectMapper/Core/Map.swift new file mode 100644 index 0000000..f01e77a --- /dev/null +++ b/Example/Pods/ObjectMapper/ObjectMapper/Core/Map.swift @@ -0,0 +1,187 @@ +// +// Map.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2015-10-09. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2015 Hearst +// +// 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 + +/// MapContext is available for developers who wish to pass information around during the mapping process. +public protocol MapContext { + +} + +/// A class used for holding mapping data +public final class Map { + public let mappingType: MappingType + + public internal(set) var JSON: [String: Any] = [:] + public internal(set) var isKeyPresent = false + public var currentValue: Any? + public var context: MapContext? + var currentKey: String? + var keyIsNested = false + + let toObject: Bool // indicates whether the mapping is being applied to an existing object + + /// Counter for failing cases of deserializing values to `let` properties. + private var failedCount: Int = 0 + + public init(mappingType: MappingType, JSON: [String: Any], toObject: Bool = false, context: MapContext? = nil) { + self.mappingType = mappingType + self.JSON = JSON + self.toObject = toObject + self.context = context + } + + /// Sets the current mapper value and key. + /// The Key paramater can be a period separated string (ex. "distance.value") to access sub objects. + public subscript(key: String) -> Map { + // save key and value associated to it + let nested = key.contains(".") + return self[key, nested: nested, ignoreNil: false] + } + + public subscript(key: String, nested nested: Bool) -> Map { + return self[key, nested: nested, ignoreNil: false] + } + + public subscript(key: String, ignoreNil ignoreNil: Bool) -> Map { + let nested = key.contains(".") + return self[key, nested: nested, ignoreNil: ignoreNil] + } + + public subscript(key: String, nested nested: Bool, ignoreNil ignoreNil: Bool) -> Map { + // save key and value associated to it + currentKey = key + keyIsNested = nested + + // check if a value exists for the current key + // do this pre-check for performance reasons + if nested == false { + let object = JSON[key] + let isNSNull = object is NSNull + isKeyPresent = isNSNull ? true : object != nil + currentValue = isNSNull ? nil : object + } else { + // break down the components of the key that are separated by . + (isKeyPresent, currentValue) = valueFor(ArraySlice(key.components(separatedBy: ".")), dictionary: JSON) + } + + // update isKeyPresent if ignoreNil is true + if ignoreNil && currentValue == nil { + isKeyPresent = false + } + + return self + } + + // MARK: Immutable Mapping + + public func value() -> T? { + return currentValue as? T + } + + public func valueOr( _ defaultValue: @autoclosure() -> T) -> T { + return value() ?? defaultValue() + } + + /// Returns current JSON value of type `T` if it is existing, or returns a + /// unusable proxy value for `T` and collects failed count. + public func valueOrFail() -> T { + if let value: T = value() { + return value + } else { + // Collects failed count + failedCount += 1 + + // Returns dummy memory as a proxy for type `T` + let pointer = UnsafeMutablePointer.allocate(capacity: 0) + pointer.deallocate(capacity: 0) + return pointer.pointee + } + } + + /// Returns whether the receiver is success or failure. + public var isValid: Bool { + return failedCount == 0 + } +} + +/// Fetch value from JSON dictionary, loop through keyPathComponents until we reach the desired object +private func valueFor(_ keyPathComponents: ArraySlice, dictionary: [String: Any]) -> (Bool, Any?) { + // Implement it as a tail recursive function. + if keyPathComponents.isEmpty { + return (false, nil) + } + + if let keyPath = keyPathComponents.first { + let object = dictionary[keyPath] + if object is NSNull { + return (true, nil) + } else if let dict = object as? [String: Any] , keyPathComponents.count > 1 { + let tail = keyPathComponents.dropFirst() + return valueFor(tail, dictionary: dict) + } else if let array = object as? [Any] , keyPathComponents.count > 1 { + let tail = keyPathComponents.dropFirst() + return valueFor(tail, array: array) + } else { + return (object != nil, object) + } + } + + return (false, nil) +} + +/// Fetch value from JSON Array, loop through keyPathComponents them until we reach the desired object +private func valueFor(_ keyPathComponents: ArraySlice, array: [Any]) -> (Bool, Any?) { + // Implement it as a tail recursive function. + + if keyPathComponents.isEmpty { + return (false, nil) + } + + //Try to convert keypath to Int as index + if let keyPath = keyPathComponents.first, + let index = Int(keyPath) , index >= 0 && index < array.count { + + let object = array[index] + + if object is NSNull { + return (true, nil) + } else if let array = object as? [Any] , keyPathComponents.count > 1 { + let tail = keyPathComponents.dropFirst() + return valueFor(tail, array: array) + } else if let dict = object as? [String: Any] , keyPathComponents.count > 1 { + let tail = keyPathComponents.dropFirst() + return valueFor(tail, dictionary: dict) + } else { + return (true, object) + } + } + + return (false, nil) +} diff --git a/Example/Pods/ObjectMapper/ObjectMapper/Core/Mappable.swift b/Example/Pods/ObjectMapper/ObjectMapper/Core/Mappable.swift new file mode 100644 index 0000000..18f2ecf --- /dev/null +++ b/Example/Pods/ObjectMapper/ObjectMapper/Core/Mappable.swift @@ -0,0 +1,119 @@ +// +// Mappable.swift +// ObjectMapper +// +// Created by Scott Hoyt on 10/25/15. +// Copyright © 2015 hearst. All rights reserved. +// + +import Foundation + +/// BaseMappable should not be implemented directly. Mappable or StaticMappable should be used instead +public protocol BaseMappable { + /// This function is where all variable mappings should occur. It is executed by Mapper during the mapping (serialization and deserialization) process. + mutating func mapping(map: Map) +} + +public protocol Mappable: BaseMappable { + /// This function can be used to validate JSON prior to mapping. Return nil to cancel mapping at this point + init?(map: Map) +} + +public protocol StaticMappable: BaseMappable { + /// This is function that can be used to: + /// 1) provide an existing cached object to be used for mapping + /// 2) return an object of another class (which conforms to Mappable) to be used for mapping. For instance, you may inspect the JSON to infer the type of object that should be used for any given mapping + static func objectForMapping(map: Map) -> BaseMappable? +} + +public extension BaseMappable { + + /// Initializes object from a JSON String + public init?(JSONString: String, context: MapContext? = nil) { + if let obj: Self = Mapper(context: context).map(JSONString: JSONString) { + self = obj + } else { + return nil + } + } + + /// Initializes object from a JSON Dictionary + public init?(JSON: [String: Any], context: MapContext? = nil) { + if let obj: Self = Mapper(context: context).map(JSON: JSON) { + self = obj + } else { + return nil + } + } + + /// Returns the JSON Dictionary for the object + public func toJSON() -> [String: Any] { + return Mapper().toJSON(self) + } + + /// Returns the JSON String for the object + public func toJSONString(prettyPrint: Bool = false) -> String? { + return Mapper().toJSONString(self, prettyPrint: prettyPrint) + } +} + +public extension Array where Element: BaseMappable { + + /// Initialize Array from a JSON String + public init?(JSONString: String, context: MapContext? = nil) { + if let obj: [Element] = Mapper(context: context).mapArray(JSONString: JSONString) { + self = obj + } else { + return nil + } + } + + /// Initialize Array from a JSON Array + public init?(JSONArray: [[String: Any]], context: MapContext? = nil) { + if let obj: [Element] = Mapper(context: context).mapArray(JSONArray: JSONArray) { + self = obj + } else { + return nil + } + } + + /// Returns the JSON Array + public func toJSON() -> [[String: Any]] { + return Mapper().toJSONArray(self) + } + + /// Returns the JSON String for the object + public func toJSONString(prettyPrint: Bool = false) -> String? { + return Mapper().toJSONString(self, prettyPrint: prettyPrint) + } +} + +public extension Set where Element: BaseMappable { + + /// Initializes a set from a JSON String + public init?(JSONString: String, context: MapContext? = nil) { + if let obj: Set = Mapper(context: context).mapSet(JSONString: JSONString) { + self = obj + } else { + return nil + } + } + + /// Initializes a set from JSON + public init?(JSONArray: [[String: Any]], context: MapContext? = nil) { + guard let obj = Mapper(context: context).mapSet(JSONArray: JSONArray) as Set? else { + return nil + } + self = obj + } + + /// Returns the JSON Set + public func toJSON() -> [[String: Any]] { + return Mapper().toJSONSet(self) + } + + /// Returns the JSON String for the object + public func toJSONString(prettyPrint: Bool = false) -> String? { + return Mapper().toJSONString(self, prettyPrint: prettyPrint) + } +} diff --git a/Example/Pods/ObjectMapper/ObjectMapper/Core/Mapper.swift b/Example/Pods/ObjectMapper/ObjectMapper/Core/Mapper.swift new file mode 100755 index 0000000..df02a50 --- /dev/null +++ b/Example/Pods/ObjectMapper/ObjectMapper/Core/Mapper.swift @@ -0,0 +1,430 @@ +// +// Mapper.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-09. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2015 Hearst +// +// 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 + +public enum MappingType { + case fromJSON + case toJSON +} + +/// The Mapper class provides methods for converting Model objects to JSON and methods for converting JSON to Model objects +public final class Mapper { + + public var context: MapContext? + + public init(context: MapContext? = nil){ + self.context = context + } + + // MARK: Mapping functions that map to an existing object toObject + + /// Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is + public func map(JSONObject: Any?, toObject object: N) -> N { + if let JSON = JSONObject as? [String: Any] { + return map(JSON: JSON, toObject: object) + } + + return object + } + + /// Map a JSON string onto an existing object + public func map(JSONString: String, toObject object: N) -> N { + if let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) { + return map(JSON: JSON, toObject: object) + } + return object + } + + /// Maps a JSON dictionary to an existing object that conforms to Mappable. + /// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject + public func map(JSON: [String: Any], toObject object: N) -> N { + var mutableObject = object + let map = Map(mappingType: .fromJSON, JSON: JSON, toObject: true, context: context) + mutableObject.mapping(map: map) + return mutableObject + } + + //MARK: Mapping functions that create an object + + /// Map a JSON string to an object that conforms to Mappable + public func map(JSONString: String) -> N? { + if let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) { + return map(JSON: JSON) + } + + return nil + } + + /// Maps a JSON object to a Mappable object if it is a JSON dictionary or NSString, or returns nil. + public func map(JSONObject: Any?) -> N? { + if let JSON = JSONObject as? [String: Any] { + return map(JSON: JSON) + } + + return nil + } + + /// Maps a JSON dictionary to an object that conforms to Mappable + public func map(JSON: [String: Any]) -> N? { + let map = Map(mappingType: .fromJSON, JSON: JSON, context: context) + + // check if object is StaticMappable + if let klass = N.self as? StaticMappable.Type { + if var object = klass.objectForMapping(map: map) as? N { + object.mapping(map: map) + return object + } + } + + // fall back to using init? to create N + if let klass = N.self as? Mappable.Type { + if var object = klass.init(map: map) as? N { + object.mapping(map: map) + return object + } + } + + return nil + } + + // MARK: Mapping functions for Arrays and Dictionaries + + /// Maps a JSON array to an object that conforms to Mappable + public func mapArray(JSONString: String) -> [N]? { + let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) + + if let objectArray = mapArray(JSONObject: parsedJSON) { + return objectArray + } + + // failed to parse JSON into array form + // try to parse it into a dictionary and then wrap it in an array + if let object = map(JSONObject: parsedJSON) { + return [object] + } + + return nil + } + + /// Maps a JSON object to an array of Mappable objects if it is an array of JSON dictionary, or returns nil. + public func mapArray(JSONObject: Any?) -> [N]? { + if let JSONArray = JSONObject as? [[String: Any]] { + return mapArray(JSONArray: JSONArray) + } + + return nil + } + + /// Maps an array of JSON dictionary to an array of Mappable objects + public func mapArray(JSONArray: [[String: Any]]) -> [N]? { + // map every element in JSON array to type N + let result = JSONArray.flatMap(map) + return result + } + + /// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil. + public func mapDictionary(JSONString: String) -> [String: N]? { + let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) + return mapDictionary(JSONObject: parsedJSON) + } + + /// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil. + public func mapDictionary(JSONObject: Any?) -> [String: N]? { + if let JSON = JSONObject as? [String: [String: Any]] { + return mapDictionary(JSON: JSON) + } + + return nil + } + + /// Maps a JSON dictionary of dictionaries to a dictionary of Mappble objects + public func mapDictionary(JSON: [String: [String: Any]]) -> [String: N]? { + // map every value in dictionary to type N + let result = JSON.filterMap(map) + if result.isEmpty == false { + return result + } + + return nil + } + + /// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil. + public func mapDictionary(JSONObject: Any?, toDictionary dictionary: [String: N]) -> [String: N] { + if let JSON = JSONObject as? [String : [String : Any]] { + return mapDictionary(JSON: JSON, toDictionary: dictionary) + } + + return dictionary + } + + /// Maps a JSON dictionary of dictionaries to an existing dictionary of Mappble objects + public func mapDictionary(JSON: [String: [String: Any]], toDictionary dictionary: [String: N]) -> [String: N] { + var mutableDictionary = dictionary + for (key, value) in JSON { + if let object = dictionary[key] { + _ = map(JSON: value, toObject: object) + } else { + mutableDictionary[key] = map(JSON: value) + } + } + + return mutableDictionary + } + + /// Maps a JSON object to a dictionary of arrays of Mappable objects + public func mapDictionaryOfArrays(JSONObject: Any?) -> [String: [N]]? { + if let JSON = JSONObject as? [String: [[String: Any]]] { + return mapDictionaryOfArrays(JSON: JSON) + } + + return nil + } + + ///Maps a JSON dictionary of arrays to a dictionary of arrays of Mappable objects + public func mapDictionaryOfArrays(JSON: [String: [[String: Any]]]) -> [String: [N]]? { + // map every value in dictionary to type N + let result = JSON.filterMap { + mapArray(JSONArray: $0) + } + + if result.isEmpty == false { + return result + } + + return nil + } + + /// Maps an 2 dimentional array of JSON dictionaries to a 2 dimentional array of Mappable objects + public func mapArrayOfArrays(JSONObject: Any?) -> [[N]]? { + if let JSONArray = JSONObject as? [[[String: Any]]] { + var objectArray = [[N]]() + for innerJSONArray in JSONArray { + if let array = mapArray(JSONArray: innerJSONArray){ + objectArray.append(array) + } + } + + if objectArray.isEmpty == false { + return objectArray + } + } + + return nil + } + + // MARK: Utility functions for converting strings to JSON objects + + /// Convert a JSON String into a Dictionary using NSJSONSerialization + public static func parseJSONStringIntoDictionary(JSONString: String) -> [String: Any]? { + let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) + return parsedJSON as? [String: Any] + } + + /// Convert a JSON String into an Object using NSJSONSerialization + public static func parseJSONString(JSONString: String) -> Any? { + let data = JSONString.data(using: String.Encoding.utf8, allowLossyConversion: true) + if let data = data { + let parsedJSON: Any? + do { + parsedJSON = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) + } catch let error { + print(error) + parsedJSON = nil + } + return parsedJSON + } + + return nil + } +} + +extension Mapper { + + // MARK: Functions that create JSON from objects + + ///Maps an object that conforms to Mappable to a JSON dictionary + public func toJSON(_ object: N) -> [String: Any] { + var mutableObject = object + let map = Map(mappingType: .toJSON, JSON: [:], context: context) + mutableObject.mapping(map: map) + return map.JSON + } + + ///Maps an array of Objects to an array of JSON dictionaries [[String: Any]] + public func toJSONArray(_ array: [N]) -> [[String: Any]] { + return array.map { + // convert every element in array to JSON dictionary equivalent + self.toJSON($0) + } + } + + ///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries. + public func toJSONDictionary(_ dictionary: [String: N]) -> [String: [String: Any]] { + return dictionary.map { k, v in + // convert every value in dictionary to its JSON dictionary equivalent + return (k, self.toJSON(v)) + } + } + + ///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries. + public func toJSONDictionaryOfArrays(_ dictionary: [String: [N]]) -> [String: [[String: Any]]] { + return dictionary.map { k, v in + // convert every value (array) in dictionary to its JSON dictionary equivalent + return (k, self.toJSONArray(v)) + } + } + + /// Maps an Object to a JSON string with option of pretty formatting + public func toJSONString(_ object: N, prettyPrint: Bool = false) -> String? { + let JSONDict = toJSON(object) + + return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint) + } + + /// Maps an array of Objects to a JSON string with option of pretty formatting + public func toJSONString(_ array: [N], prettyPrint: Bool = false) -> String? { + let JSONDict = toJSONArray(array) + + return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint) + } + + /// Converts an Object to a JSON string with option of pretty formatting + public static func toJSONString(_ JSONObject: Any, prettyPrint: Bool) -> String? { + let options: JSONSerialization.WritingOptions = prettyPrint ? .prettyPrinted : [] + if let JSON = Mapper.toJSONData(JSONObject, options: options) { + return String(data: JSON, encoding: String.Encoding.utf8) + } + + return nil + } + + /// Converts an Object to JSON data with options + public static func toJSONData(_ JSONObject: Any, options: JSONSerialization.WritingOptions) -> Data? { + if JSONSerialization.isValidJSONObject(JSONObject) { + let JSONData: Data? + do { + JSONData = try JSONSerialization.data(withJSONObject: JSONObject, options: options) + } catch let error { + print(error) + JSONData = nil + } + + return JSONData + } + + return nil + } +} + +extension Mapper where N: Hashable { + + /// Maps a JSON array to an object that conforms to Mappable + public func mapSet(JSONString: String) -> Set? { + let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) + + if let objectArray = mapArray(JSONObject: parsedJSON) { + return Set(objectArray) + } + + // failed to parse JSON into array form + // try to parse it into a dictionary and then wrap it in an array + if let object = map(JSONObject: parsedJSON) { + return Set([object]) + } + + return nil + } + + /// Maps a JSON object to an Set of Mappable objects if it is an array of JSON dictionary, or returns nil. + public func mapSet(JSONObject: Any?) -> Set? { + if let JSONArray = JSONObject as? [[String: Any]] { + return mapSet(JSONArray: JSONArray) + } + + return nil + } + + /// Maps an Set of JSON dictionary to an array of Mappable objects + public func mapSet(JSONArray: [[String: Any]]) -> Set { + // map every element in JSON array to type N + return Set(JSONArray.flatMap(map)) + } + + ///Maps a Set of Objects to a Set of JSON dictionaries [[String : Any]] + public func toJSONSet(_ set: Set) -> [[String: Any]] { + return set.map { + // convert every element in set to JSON dictionary equivalent + self.toJSON($0) + } + } + + /// Maps a set of Objects to a JSON string with option of pretty formatting + public func toJSONString(_ set: Set, prettyPrint: Bool = false) -> String? { + let JSONDict = toJSONSet(set) + + return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint) + } +} + +extension Dictionary { + internal func map(_ f: (Element) -> (K, V)) -> [K: V] { + var mapped = [K: V]() + + for element in self { + let newElement = f(element) + mapped[newElement.0] = newElement.1 + } + + return mapped + } + + internal func map(_ f: (Element) -> (K, [V])) -> [K: [V]] { + var mapped = [K: [V]]() + + for element in self { + let newElement = f(element) + mapped[newElement.0] = newElement.1 + } + + return mapped + } + + + internal func filterMap(_ f: (Value) -> U?) -> [Key: U] { + var mapped = [Key: U]() + + for (key, value) in self { + if let newValue = f(value) { + mapped[key] = newValue + } + } + + return mapped + } +} diff --git a/Example/Pods/ObjectMapper/ObjectMapper/Core/Operators.swift b/Example/Pods/ObjectMapper/ObjectMapper/Core/Operators.swift new file mode 100755 index 0000000..77617e3 --- /dev/null +++ b/Example/Pods/ObjectMapper/ObjectMapper/Core/Operators.swift @@ -0,0 +1,795 @@ +// +// Operators.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-09. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2015 Hearst +// +// 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. + +/** +* This file defines a new operator which is used to create a mapping between an object and a JSON key value. +* There is an overloaded operator definition for each type of object that is supported in ObjectMapper. +* This provides a way to add custom logic to handle specific types of objects +*/ + +infix operator <- + +// MARK:- Objects with Basic types + +/// Object of Basic type +public func <- (left: inout T, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.basicType(&left, object: right.value()) + case .toJSON: + ToJSON.basicType(left, map: right) + default: () + } +} + +/// Optional object of basic type +public func <- (left: inout T?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalBasicType(&left, object: right.value()) + case .toJSON: + ToJSON.optionalBasicType(left, map: right) + default: () + } +} + +/// Implicitly unwrapped optional object of basic type +public func <- (left: inout T!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalBasicType(&left, object: right.value()) + case .toJSON: + ToJSON.optionalBasicType(left, map: right) + default: () + } +} + +// MARK:- Raw Representable types + +/// Object of Raw Representable type +public func <- (left: inout T, right: Map) { + left <- (right, EnumTransform()) +} + +/// Optional Object of Raw Representable type +public func <- (left: inout T?, right: Map) { + left <- (right, EnumTransform()) +} + +/// Implicitly Unwrapped Optional Object of Raw Representable type +public func <- (left: inout T!, right: Map) { + left <- (right, EnumTransform()) +} + +// MARK:- Arrays of Raw Representable type + +/// Array of Raw Representable object +public func <- (left: inout [T], right: Map) { + left <- (right, EnumTransform()) +} + +/// Array of Raw Representable object +public func <- (left: inout [T]?, right: Map) { + left <- (right, EnumTransform()) +} + +/// Array of Raw Representable object +public func <- (left: inout [T]!, right: Map) { + left <- (right, EnumTransform()) +} + +// MARK:- Dictionaries of Raw Representable type + +/// Dictionary of Raw Representable object +public func <- (left: inout [String: T], right: Map) { + left <- (right, EnumTransform()) +} + +/// Dictionary of Raw Representable object +public func <- (left: inout [String: T]?, right: Map) { + left <- (right, EnumTransform()) +} + +/// Dictionary of Raw Representable object +public func <- (left: inout [String: T]!, right: Map) { + left <- (right, EnumTransform()) +} + +// MARK:- Transforms + +/// Object of Basic type with Transform +public func <- (left: inout Transform.Object, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let value = transform.transformFromJSON(map.currentValue) + FromJSON.basicType(&left, object: value) + case .toJSON: + let value: Transform.JSON? = transform.transformToJSON(left) + ToJSON.optionalBasicType(value, map: map) + default: () + } +} + +/// Optional object of basic type with Transform +public func <- (left: inout Transform.Object?, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let value = transform.transformFromJSON(map.currentValue) + FromJSON.optionalBasicType(&left, object: value) + case .toJSON: + let value: Transform.JSON? = transform.transformToJSON(left) + ToJSON.optionalBasicType(value, map: map) + default: () + } +} + +/// Implicitly unwrapped optional object of basic type with Transform +public func <- (left: inout Transform.Object!, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let value = transform.transformFromJSON(map.currentValue) + FromJSON.optionalBasicType(&left, object: value) + case .toJSON: + let value: Transform.JSON? = transform.transformToJSON(left) + ToJSON.optionalBasicType(value, map: map) + default: () + } +} + +/// Array of Basic type with Transform +public func <- (left: inout [Transform.Object], right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let values = fromJSONArrayWithTransform(map.currentValue, transform: transform) + FromJSON.basicType(&left, object: values) + case .toJSON: + let values = toJSONArrayWithTransform(left, transform: transform) + ToJSON.optionalBasicType(values, map: map) + default: () + } +} + +/// Optional array of Basic type with Transform +public func <- (left: inout [Transform.Object]?, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let values = fromJSONArrayWithTransform(map.currentValue, transform: transform) + FromJSON.optionalBasicType(&left, object: values) + case .toJSON: + let values = toJSONArrayWithTransform(left, transform: transform) + ToJSON.optionalBasicType(values, map: map) + default: () + } +} + +/// Implicitly unwrapped optional array of Basic type with Transform +public func <- (left: inout [Transform.Object]!, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let values = fromJSONArrayWithTransform(map.currentValue, transform: transform) + FromJSON.optionalBasicType(&left, object: values) + case .toJSON: + let values = toJSONArrayWithTransform(left, transform: transform) + ToJSON.optionalBasicType(values, map: map) + default: () + } +} + +/// Dictionary of Basic type with Transform +public func <- (left: inout [String: Transform.Object], right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let values = fromJSONDictionaryWithTransform(map.currentValue, transform: transform) + FromJSON.basicType(&left, object: values) + case .toJSON: + let values = toJSONDictionaryWithTransform(left, transform: transform) + ToJSON.optionalBasicType(values, map: map) + default: () + } +} + +/// Optional dictionary of Basic type with Transform +public func <- (left: inout [String: Transform.Object]?, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let values = fromJSONDictionaryWithTransform(map.currentValue, transform: transform) + FromJSON.optionalBasicType(&left, object: values) + case .toJSON: + let values = toJSONDictionaryWithTransform(left, transform: transform) + ToJSON.optionalBasicType(values, map: map) + default: () + } +} + +/// Implicitly unwrapped optional dictionary of Basic type with Transform +public func <- (left: inout [String: Transform.Object]!, right: (Map, Transform)) { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let values = fromJSONDictionaryWithTransform(map.currentValue, transform: transform) + FromJSON.optionalBasicType(&left, object: values) + case .toJSON: + let values = toJSONDictionaryWithTransform(left, transform: transform) + ToJSON.optionalBasicType(values, map: map) + default: () + } +} + +private func fromJSONArrayWithTransform(_ input: Any?, transform: Transform) -> [Transform.Object]? { + if let values = input as? [AnyObject] { + return values.flatMap { value in + return transform.transformFromJSON(value) + } + } else { + return nil + } +} + +private func fromJSONDictionaryWithTransform(_ input: Any?, transform: Transform) -> [String: Transform.Object]? { + if let values = input as? [String: AnyObject] { + return values.filterMap { value in + return transform.transformFromJSON(value) + } + } else { + return nil + } +} + +private func toJSONArrayWithTransform(_ input: [Transform.Object]?, transform: Transform) -> [Transform.JSON]? { + return input?.flatMap { value in + return transform.transformToJSON(value) + } +} + +private func toJSONDictionaryWithTransform(_ input: [String: Transform.Object]?, transform: Transform) -> [String: Transform.JSON]? { + return input?.filterMap { value in + return transform.transformToJSON(value) + } +} + +// MARK:- Mappable Objects - + +/// Object conforming to Mappable +public func <- (left: inout T, right: Map) { + switch right.mappingType { + case .fromJSON: + FromJSON.object(&left, map: right) + case .toJSON: + ToJSON.object(left, map: right) + } +} + +/// Optional Mappable objects +public func <- (left: inout T?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObject(&left, map: right) + case .toJSON: + ToJSON.optionalObject(left, map: right) + default: () + } +} + +/// Implicitly unwrapped optional Mappable objects +public func <- (left: inout T!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObject(&left, map: right) + case .toJSON: + ToJSON.optionalObject(left, map: right) + default: () + } +} + +// MARK:- Transforms of Mappable Objects - + +/// Object conforming to Mappable that have transforms +public func <- (left: inout Transform.Object, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let value: Transform.Object? = transform.transformFromJSON(map.currentValue) + FromJSON.basicType(&left, object: value) + case .toJSON: + let value: Transform.JSON? = transform.transformToJSON(left) + ToJSON.optionalBasicType(value, map: map) + default: () + } +} + +/// Optional Mappable objects that have transforms +public func <- (left: inout Transform.Object?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let value: Transform.Object? = transform.transformFromJSON(map.currentValue) + FromJSON.optionalBasicType(&left, object: value) + case .toJSON: + let value: Transform.JSON? = transform.transformToJSON(left) + ToJSON.optionalBasicType(value, map: map) + default: () + } +} + +/// Implicitly unwrapped optional Mappable objects that have transforms +public func <- (left: inout Transform.Object!, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let value: Transform.Object? = transform.transformFromJSON(map.currentValue) + FromJSON.optionalBasicType(&left, object: value) + case .toJSON: + let value: Transform.JSON? = transform.transformToJSON(left) + ToJSON.optionalBasicType(value, map: map) + default: () + } +} + +// MARK:- Dictionary of Mappable objects - Dictionary + +/// Dictionary of Mappable objects +public func <- (left: inout Dictionary, right: Map) { switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.objectDictionary(&left, map: right) + case .toJSON: + ToJSON.objectDictionary(left, map: right) + default: () + } +} + +/// Optional Dictionary of Mappable object +public func <- (left: inout Dictionary?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectDictionary(&left, map: right) + case .toJSON: + ToJSON.optionalObjectDictionary(left, map: right) + default: () + } +} + +/// Implicitly unwrapped Optional Dictionary of Mappable object +public func <- (left: inout Dictionary!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectDictionary(&left, map: right) + case .toJSON: + ToJSON.optionalObjectDictionary(left, map: right) + default: () + } +} + +/// Dictionary of Mappable objects +public func <- (left: inout Dictionary, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.objectDictionaryOfArrays(&left, map: right) + case .toJSON: + ToJSON.objectDictionaryOfArrays(left, map: right) + default: () + } +} + +/// Optional Dictionary of Mappable object +public func <- (left: inout Dictionary?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectDictionaryOfArrays(&left, map: right) + case .toJSON: + ToJSON.optionalObjectDictionaryOfArrays(left, map: right) + default: () + } +} + +/// Implicitly unwrapped Optional Dictionary of Mappable object +public func <- (left: inout Dictionary!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectDictionaryOfArrays(&left, map: right) + case .toJSON: + ToJSON.optionalObjectDictionaryOfArrays(left, map: right) + default: () + } +} + +// MARK:- Dictionary of Mappable objects with a transform - Dictionary + +/// Dictionary of Mappable objects with a transform +public func <- (left: inout Dictionary, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .fromJSON && map.isKeyPresent, + let object = map.currentValue as? [String: AnyObject] { + let value = fromJSONDictionaryWithTransform(object as AnyObject?, transform: transform) ?? left + FromJSON.basicType(&left, object: value) + } else if map.mappingType == .toJSON { + let value = toJSONDictionaryWithTransform(left, transform: transform) + ToJSON.basicType(value, map: map) + } +} + +/// Optional Dictionary of Mappable object with a transform +public func <- (left: inout Dictionary?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .fromJSON && map.isKeyPresent, let object = map.currentValue as? [String : AnyObject]{ + let value = fromJSONDictionaryWithTransform(object as AnyObject?, transform: transform) ?? left + FromJSON.optionalBasicType(&left, object: value) + } else if map.mappingType == .toJSON { + let value = toJSONDictionaryWithTransform(left, transform: transform) + ToJSON.optionalBasicType(value, map: map) + } +} + +/// Implicitly unwrapped Optional Dictionary of Mappable object with a transform +public func <- (left: inout Dictionary!, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .fromJSON && map.isKeyPresent, let dictionary = map.currentValue as? [String : AnyObject]{ + let transformedDictionary = fromJSONDictionaryWithTransform(dictionary as AnyObject?, transform: transform) ?? left + FromJSON.optionalBasicType(&left, object: transformedDictionary) + } else if map.mappingType == .toJSON { + let value = toJSONDictionaryWithTransform(left, transform: transform) + ToJSON.optionalBasicType(value, map: map) + } +} + +/// Dictionary of Mappable objects with a transform +public func <- (left: inout Dictionary, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + + if let dictionary = map.currentValue as? [String : [AnyObject]], map.mappingType == .fromJSON && map.isKeyPresent { + let transformedDictionary = dictionary.map { (key: String, values: [AnyObject]) -> (String, [Transform.Object]) in + if let jsonArray = fromJSONArrayWithTransform(values, transform: transform) { + return (key, jsonArray) + } + if let leftValue = left[key] { + return (key, leftValue) + } + return (key, []) + } + + FromJSON.basicType(&left, object: transformedDictionary) + } else if map.mappingType == .toJSON { + let transformedDictionary = left.map { (key, values) in + return (key, toJSONArrayWithTransform(values, transform: transform) ?? []) + } + + ToJSON.basicType(transformedDictionary, map: map) + } +} + +/// Optional Dictionary of Mappable object with a transform +public func <- (left: inout Dictionary?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + + if let dictionary = map.currentValue as? [String : [AnyObject]], map.mappingType == .fromJSON && map.isKeyPresent { + + let transformedDictionary = dictionary.map { (key: String, values: [AnyObject]) -> (String, [Transform.Object]) in + if let jsonArray = fromJSONArrayWithTransform(values, transform: transform) { + return (key, jsonArray) + } + if let leftValue = left?[key] { + return (key, leftValue) + } + return (key, []) + + } + + FromJSON.optionalBasicType(&left, object: transformedDictionary) + } else if map.mappingType == .toJSON { + let transformedDictionary = left?.map { (key, values) in + return (key, toJSONArrayWithTransform(values, transform: transform) ?? []) + } + + ToJSON.optionalBasicType(transformedDictionary, map: map) + } +} + +/// Implicitly unwrapped Optional Dictionary of Mappable object with a transform +public func <- (left: inout Dictionary!, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + + if let dictionary = map.currentValue as? [String : [AnyObject]], map.mappingType == .fromJSON && map.isKeyPresent { + let transformedDictionary = dictionary.map { (key: String, values: [AnyObject]) -> (String, [Transform.Object]) in + if let jsonArray = fromJSONArrayWithTransform(values, transform: transform) { + return (key, jsonArray) + } + if let leftValue = left?[key] { + return (key, leftValue) + } + return (key, []) + } + FromJSON.optionalBasicType(&left, object: transformedDictionary) + } else if map.mappingType == .toJSON { + let transformedDictionary = left?.map { (key, values) in + return (key, toJSONArrayWithTransform(values, transform: transform) ?? []) + } + + ToJSON.optionalBasicType(transformedDictionary, map: map) + } +} + +// MARK:- Array of Mappable objects - Array + +/// Array of Mappable objects +public func <- (left: inout Array, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.objectArray(&left, map: right) + case .toJSON: + ToJSON.objectArray(left, map: right) + default: () + } +} + +/// Optional array of Mappable objects +public func <- (left: inout Array?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectArray(&left, map: right) + case .toJSON: + ToJSON.optionalObjectArray(left, map: right) + default: () + } +} + +/// Implicitly unwrapped Optional array of Mappable objects +public func <- (left: inout Array!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectArray(&left, map: right) + case .toJSON: + ToJSON.optionalObjectArray(left, map: right) + default: () + } +} + +// MARK:- Array of Mappable objects with transforms - Array + +/// Array of Mappable objects +public func <- (left: inout Array, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + if let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) { + FromJSON.basicType(&left, object: transformedValues) + } + case .toJSON: + let transformedValues = toJSONArrayWithTransform(left, transform: transform) + ToJSON.optionalBasicType(transformedValues, map: map) + default: () + } +} + +/// Optional array of Mappable objects +public func <- (left: inout Array?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) + FromJSON.optionalBasicType(&left, object: transformedValues) + case .toJSON: + let transformedValues = toJSONArrayWithTransform(left, transform: transform) + ToJSON.optionalBasicType(transformedValues, map: map) + default: () + } +} + +/// Implicitly unwrapped Optional array of Mappable objects +public func <- (left: inout Array!, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) + FromJSON.optionalBasicType(&left, object: transformedValues) + case .toJSON: + let transformedValues = toJSONArrayWithTransform(left, transform: transform) + ToJSON.optionalBasicType(transformedValues, map: map) + default: () + } +} + +// MARK:- Array of Array of Mappable objects - Array> + +/// Array of Array Mappable objects +public func <- (left: inout Array>, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.twoDimensionalObjectArray(&left, map: right) + case .toJSON: + ToJSON.twoDimensionalObjectArray(left, map: right) + default: () + } +} + +/// Optional array of Mappable objects +public func <- (left:inout Array>?, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalTwoDimensionalObjectArray(&left, map: right) + case .toJSON: + ToJSON.optionalTwoDimensionalObjectArray(left, map: right) + default: () + } +} + +/// Implicitly unwrapped Optional array of Mappable objects +public func <- (left: inout Array>!, right: Map) { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalTwoDimensionalObjectArray(&left, map: right) + case .toJSON: + ToJSON.optionalTwoDimensionalObjectArray(left, map: right) + default: () + } +} + +// MARK:- Array of Array of Mappable objects - Array> with transforms + +/// Array of Array Mappable objects with transform +public func <- (left: inout Array>, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .fromJSON && map.isKeyPresent, let original2DArray = map.currentValue as? [[AnyObject]]{ + let transformed2DArray = original2DArray.flatMap { values in + fromJSONArrayWithTransform(values as AnyObject?, transform: transform) + } + FromJSON.basicType(&left, object: transformed2DArray) + } else if map.mappingType == .toJSON { + let transformed2DArray = left.flatMap { values in + toJSONArrayWithTransform(values, transform: transform) + } + ToJSON.basicType(transformed2DArray, map: map) + } +} + +/// Optional array of Mappable objects with transform +public func <- (left:inout Array>?, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .fromJSON && map.isKeyPresent, let original2DArray = map.currentValue as? [[AnyObject]]{ + let transformed2DArray = original2DArray.flatMap { values in + fromJSONArrayWithTransform(values as AnyObject?, transform: transform) + } + FromJSON.optionalBasicType(&left, object: transformed2DArray) + } else if map.mappingType == .toJSON { + let transformed2DArray = left?.flatMap { values in + toJSONArrayWithTransform(values, transform: transform) + } + ToJSON.optionalBasicType(transformed2DArray, map: map) + } +} + +/// Implicitly unwrapped Optional array of Mappable objects with transform +public func <- (left: inout Array>!, right: (Map, Transform)) where Transform.Object: BaseMappable { + let (map, transform) = right + if map.mappingType == .fromJSON && map.isKeyPresent, let original2DArray = map.currentValue as? [[AnyObject]] { + let transformed2DArray = original2DArray.flatMap { values in + fromJSONArrayWithTransform(values as AnyObject?, transform: transform) + } + FromJSON.optionalBasicType(&left, object: transformed2DArray) + } else if map.mappingType == .toJSON { + let transformed2DArray = left?.flatMap { values in + toJSONArrayWithTransform(values, transform: transform) + } + ToJSON.optionalBasicType(transformed2DArray, map: map) + } +} + +// MARK:- Set of Mappable objects - Set + +/// Set of Mappable objects +public func <- (left: inout Set, right: Map) where T: Hashable { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.objectSet(&left, map: right) + case .toJSON: + ToJSON.objectSet(left, map: right) + default: () + } +} + + +/// Optional Set of Mappable objects +public func <- (left: inout Set?, right: Map) where T: Hashable, T: Hashable { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectSet(&left, map: right) + case .toJSON: + ToJSON.optionalObjectSet(left, map: right) + default: () + } +} + +/// Implicitly unwrapped Optional Set of Mappable objects +public func <- (left: inout Set!, right: Map) where T: Hashable { + switch right.mappingType { + case .fromJSON where right.isKeyPresent: + FromJSON.optionalObjectSet(&left, map: right) + case .toJSON: + ToJSON.optionalObjectSet(left, map: right) + default: () + } +} + + +// MARK:- Set of Mappable objects with a transform - Set + +/// Set of Mappable objects with transform +public func <- (left: inout Set, right: (Map, Transform)) where Transform.Object: Hashable & Mappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + if let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) { + FromJSON.basicType(&left, object: Set(transformedValues)) + } + case .toJSON: + let transformedValues = toJSONArrayWithTransform(Array(left), transform: transform) + ToJSON.optionalBasicType(transformedValues, map: map) + default: () + } +} + + +/// Optional Set of Mappable objects with transform +public func <- (left: inout Set?, right: (Map, Transform)) where Transform.Object: Hashable & Mappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + if let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) { + FromJSON.basicType(&left, object: Set(transformedValues)) + } + case .toJSON: + if let values = left { + let transformedValues = toJSONArrayWithTransform(Array(values), transform: transform) + ToJSON.optionalBasicType(transformedValues, map: map) + } + default: () + } +} + +/// Implicitly unwrapped Optional set of Mappable objects with transform +public func <- (left: inout Set!, right: (Map, Transform)) where Transform.Object: Hashable & Mappable { + let (map, transform) = right + switch map.mappingType { + case .fromJSON where map.isKeyPresent: + if let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) { + FromJSON.basicType(&left, object: Set(transformedValues)) + } + case .toJSON: + if let values = left { + let transformedValues = toJSONArrayWithTransform(Array(values), transform: transform) + ToJSON.optionalBasicType(transformedValues, map: map) + } + default: () + } +} diff --git a/Example/Pods/ObjectMapper/ObjectMapper/Core/ToJSON.swift b/Example/Pods/ObjectMapper/ObjectMapper/Core/ToJSON.swift new file mode 100644 index 0000000..65966ad --- /dev/null +++ b/Example/Pods/ObjectMapper/ObjectMapper/Core/ToJSON.swift @@ -0,0 +1,176 @@ +// +// ToJSON.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-13. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2015 Hearst +// +// 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 class Foundation.NSNumber + +private func setValue(_ value: Any, map: Map) { + setValue(value, key: map.currentKey!, checkForNestedKeys: map.keyIsNested, dictionary: &map.JSON) +} + +private func setValue(_ value: Any, key: String, checkForNestedKeys: Bool, dictionary: inout [String : Any]) { + if checkForNestedKeys { + let keyComponents = ArraySlice(key.characters.split { $0 == "." }) + setValue(value, forKeyPathComponents: keyComponents, dictionary: &dictionary) + } else { + dictionary[key] = value + } +} + +private func setValue(_ value: Any, forKeyPathComponents components: ArraySlice, dictionary: inout [String : Any]) { + if components.isEmpty { + return + } + + let head = components.first! + + if components.count == 1 { + dictionary[String(head)] = value + } else { + var child = dictionary[String(head)] as? [String : Any] + if child == nil { + child = [:] + } + + let tail = components.dropFirst() + setValue(value, forKeyPathComponents: tail, dictionary: &child!) + + dictionary[String(head)] = child + } +} + +internal final class ToJSON { + + class func basicType(_ field: N, map: Map) { + if let x = field as Any? , false + || x is NSNumber // Basic types + || x is Bool + || x is Int + || x is Double + || x is Float + || x is String + || x is Array // Arrays + || x is Array + || x is Array + || x is Array + || x is Array + || x is Array + || x is Array + || x is Array> + || x is Dictionary // Dictionaries + || x is Dictionary + || x is Dictionary + || x is Dictionary + || x is Dictionary + || x is Dictionary + || x is Dictionary + { + setValue(x, map: map) + } + } + + class func optionalBasicType(_ field: N?, map: Map) { + if let field = field { + basicType(field, map: map) + } + } + + class func object(_ field: N, map: Map) { + if let result = Mapper(context: map.context).toJSON(field) as Any? { + setValue(result, map: map) + } + } + + class func optionalObject(_ field: N?, map: Map) { + if let field = field { + object(field, map: map) + } + } + + class func objectArray(_ field: Array, map: Map) { + let JSONObjects = Mapper(context: map.context).toJSONArray(field) + + setValue(JSONObjects, map: map) + } + + class func optionalObjectArray(_ field: Array?, map: Map) { + if let field = field { + objectArray(field, map: map) + } + } + + class func twoDimensionalObjectArray(_ field: Array>, map: Map) { + var array = [[[String: Any]]]() + for innerArray in field { + let JSONObjects = Mapper(context: map.context).toJSONArray(innerArray) + array.append(JSONObjects) + } + setValue(array, map: map) + } + + class func optionalTwoDimensionalObjectArray(_ field: Array>?, map: Map) { + if let field = field { + twoDimensionalObjectArray(field, map: map) + } + } + + class func objectSet(_ field: Set, map: Map) where N: Hashable { + let JSONObjects = Mapper(context: map.context).toJSONSet(field) + + setValue(JSONObjects, map: map) + } + + class func optionalObjectSet(_ field: Set?, map: Map) where N: Hashable { + if let field = field { + objectSet(field, map: map) + } + } + + class func objectDictionary(_ field: Dictionary, map: Map) { + let JSONObjects = Mapper(context: map.context).toJSONDictionary(field) + + setValue(JSONObjects, map: map) + } + + class func optionalObjectDictionary(_ field: Dictionary?, map: Map) { + if let field = field { + objectDictionary(field, map: map) + } + } + + class func objectDictionaryOfArrays(_ field: Dictionary, map: Map) { + let JSONObjects = Mapper(context: map.context).toJSONDictionaryOfArrays(field) + + setValue(JSONObjects, map: map) + } + + class func optionalObjectDictionaryOfArrays(_ field: Dictionary?, map: Map) { + if let field = field { + objectDictionaryOfArrays(field, map: map) + } + } +} diff --git a/Example/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/CustomDateFormatTransform.swift similarity index 62% rename from Example/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift rename to Example/Pods/ObjectMapper/ObjectMapper/Transforms/CustomDateFormatTransform.swift index 9031395..a4bf599 100644 --- a/Example/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift +++ b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/CustomDateFormatTransform.swift @@ -1,7 +1,12 @@ // -// DispatchQueue+Alamofire.swift +// CustomDateFormatTransform.swift +// ObjectMapper // -// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// Created by Dan McCracken on 3/8/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2015 Hearst // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -20,18 +25,16 @@ // 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) +open class CustomDateFormatTransform: DateFormatterTransform { + + public init(formatString: String) { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.dateFormat = formatString + + super.init(dateFormatter: formatter) } } diff --git a/Example/Pods/ObjectMapper/ObjectMapper/Transforms/DataTransform.swift b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/DataTransform.swift new file mode 100644 index 0000000..c5285aa --- /dev/null +++ b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/DataTransform.swift @@ -0,0 +1,50 @@ +// +// DataTransform.swift +// ObjectMapper +// +// Created by Yagrushkin, Evgeny on 8/30/16. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2015 Hearst +// +// 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 + +open class DataTransform: TransformType { + public typealias Object = Data + public typealias JSON = String + + public init() {} + + public func transformFromJSON(_ value: Any?) -> Data? { + guard let string = value as? String else{ + return nil + } + return Data(base64Encoded: string) + } + + public func transformToJSON(_ value: Data?) -> String? { + guard let data = value else{ + return nil + } + return data.base64EncodedString() + } +} diff --git a/Example/Pods/ObjectMapper/ObjectMapper/Transforms/DateFormatterTransform.swift b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/DateFormatterTransform.swift new file mode 100644 index 0000000..5574c3f --- /dev/null +++ b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/DateFormatterTransform.swift @@ -0,0 +1,54 @@ +// +// DateFormatterTransform.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2015-03-09. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2015 Hearst +// +// 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 + +open class DateFormatterTransform: TransformType { + public typealias Object = Date + public typealias JSON = String + + let dateFormatter: DateFormatter + + public init(dateFormatter: DateFormatter) { + self.dateFormatter = dateFormatter + } + + public func transformFromJSON(_ value: Any?) -> Date? { + if let dateString = value as? String { + return dateFormatter.date(from: dateString) + } + return nil + } + + public func transformToJSON(_ value: Date?) -> String? { + if let date = value { + return dateFormatter.string(from: date) + } + return nil + } +} diff --git a/Example/Pods/ObjectMapper/ObjectMapper/Transforms/DateTransform.swift b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/DateTransform.swift new file mode 100644 index 0000000..989fa16 --- /dev/null +++ b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/DateTransform.swift @@ -0,0 +1,55 @@ +// +// DateTransform.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-13. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2015 Hearst +// +// 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 + +open class DateTransform: TransformType { + public typealias Object = Date + public typealias JSON = Double + + public init() {} + + public func transformFromJSON(_ value: Any?) -> Date? { + if let timeInt = value as? Double { + return Date(timeIntervalSince1970: TimeInterval(timeInt)) + } + + if let timeStr = value as? String { + return Date(timeIntervalSince1970: TimeInterval(atof(timeStr))) + } + + return nil + } + + public func transformToJSON(_ value: Date?) -> Double? { + if let date = value { + return Double(date.timeIntervalSince1970) + } + return nil + } +} diff --git a/Example/Pods/ObjectMapper/ObjectMapper/Transforms/DictionaryTransform.swift b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/DictionaryTransform.swift new file mode 100644 index 0000000..e7b6ef3 --- /dev/null +++ b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/DictionaryTransform.swift @@ -0,0 +1,58 @@ +// +// DictionaryTransform.swift +// ObjectMapper +// +// Created by Milen Halachev on 7/20/16. +// Copyright © 2016 hearst. All rights reserved. +// + +import Foundation + +///Transforms [String: AnyObject] <-> [Key: Value] where Key is RawRepresentable as String, Value is Mappable +public struct DictionaryTransform: TransformType where Key: Hashable, Key: RawRepresentable, Key.RawValue == String, Value: Mappable { + + public init() { + + } + + public func transformFromJSON(_ value: Any?) -> [Key: Value]? { + + guard let json = value as? [String: Any] else { + + return nil + } + + let result = json.reduce([:]) { (result, element) -> [Key: Value] in + + guard + let key = Key(rawValue: element.0), + let valueJSON = element.1 as? [String: Any], + let value = Value(JSON: valueJSON) + else { + + return result + } + + var result = result + result[key] = value + return result + } + + return result + } + + public func transformToJSON(_ value: [Key: Value]?) -> Any? { + + let result = value?.reduce([:]) { (result, element) -> [String: Any] in + + let key = element.0.rawValue + let value = element.1.toJSON() + + var result = result + result[key] = value + return result + } + + return result + } +} diff --git a/Example/Pods/ObjectMapper/ObjectMapper/Transforms/EnumTransform.swift b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/EnumTransform.swift new file mode 100644 index 0000000..b83d553 --- /dev/null +++ b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/EnumTransform.swift @@ -0,0 +1,50 @@ +// +// EnumTransform.swift +// ObjectMapper +// +// Created by Kaan Dedeoglu on 3/20/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2015 Hearst +// +// 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 + +open class EnumTransform: TransformType { + public typealias Object = T + public typealias JSON = T.RawValue + + public init() {} + + public func transformFromJSON(_ value: Any?) -> T? { + if let raw = value as? T.RawValue { + return T(rawValue: raw) + } + return nil + } + + public func transformToJSON(_ value: T?) -> T.RawValue? { + if let obj = value { + return obj.rawValue + } + return nil + } +} diff --git a/Example/Pods/ObjectMapper/ObjectMapper/Transforms/ISO8601DateTransform.swift b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/ISO8601DateTransform.swift new file mode 100644 index 0000000..b8898f7 --- /dev/null +++ b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/ISO8601DateTransform.swift @@ -0,0 +1,41 @@ +// +// ISO8601DateTransform.swift +// ObjectMapper +// +// Created by Jean-Pierre Mouilleseaux on 21 Nov 2014. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2015 Hearst +// +// 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 + +open class ISO8601DateTransform: DateFormatterTransform { + + public init() { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" + + super.init(dateFormatter: formatter) + } + +} diff --git a/Example/Pods/ObjectMapper/ObjectMapper/Transforms/NSDecimalNumberTransform.swift b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/NSDecimalNumberTransform.swift new file mode 100644 index 0000000..c4ad974 --- /dev/null +++ b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/NSDecimalNumberTransform.swift @@ -0,0 +1,51 @@ +// +// TransformOf.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 8/22/16. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2015 Hearst +// +// 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 + +open class NSDecimalNumberTransform: TransformType { + public typealias Object = NSDecimalNumber + public typealias JSON = String + + public init() {} + + public func transformFromJSON(_ value: Any?) -> NSDecimalNumber? { + if let string = value as? String { + return NSDecimalNumber(string: string) + } + if let double = value as? Double { + return NSDecimalNumber(value: double) + } + return nil + } + + public func transformToJSON(_ value: NSDecimalNumber?) -> String? { + guard let value = value else { return nil } + return value.description + } +} diff --git a/Example/Pods/ObjectMapper/ObjectMapper/Transforms/TransformOf.swift b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/TransformOf.swift new file mode 100644 index 0000000..2a53f17 --- /dev/null +++ b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/TransformOf.swift @@ -0,0 +1,48 @@ +// +// TransformOf.swift +// ObjectMapper +// +// Created by Syo Ikeda on 1/23/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2015 Hearst +// +// 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. + +open class TransformOf: TransformType { + public typealias Object = ObjectType + public typealias JSON = JSONType + + private let fromJSON: (JSONType?) -> ObjectType? + private let toJSON: (ObjectType?) -> JSONType? + + public init(fromJSON: @escaping(JSONType?) -> ObjectType?, toJSON: @escaping(ObjectType?) -> JSONType?) { + self.fromJSON = fromJSON + self.toJSON = toJSON + } + + public func transformFromJSON(_ value: Any?) -> ObjectType? { + return fromJSON(value as? JSONType) + } + + public func transformToJSON(_ value: ObjectType?) -> JSONType? { + return toJSON(value) + } +} diff --git a/Example/Pods/ObjectMapper/ObjectMapper/Transforms/TransformType.swift b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/TransformType.swift new file mode 100644 index 0000000..8916694 --- /dev/null +++ b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/TransformType.swift @@ -0,0 +1,35 @@ +// +// TransformType.swift +// ObjectMapper +// +// Created by Syo Ikeda on 2/4/15. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2015 Hearst +// +// 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. + +public protocol TransformType { + associatedtype Object + associatedtype JSON + + func transformFromJSON(_ value: Any?) -> Object? + func transformToJSON(_ value: Object?) -> JSON? +} diff --git a/Example/Pods/ObjectMapper/ObjectMapper/Transforms/URLTransform.swift b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/URLTransform.swift new file mode 100644 index 0000000..ee2c1ac --- /dev/null +++ b/Example/Pods/ObjectMapper/ObjectMapper/Transforms/URLTransform.swift @@ -0,0 +1,65 @@ +// +// URLTransform.swift +// ObjectMapper +// +// Created by Tristan Himmelman on 2014-10-27. +// +// The MIT License (MIT) +// +// Copyright (c) 2014-2015 Hearst +// +// 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 + +open class URLTransform: TransformType { + public typealias Object = URL + public typealias JSON = String + private let shouldEncodeURLString: Bool + + /** + Initializes the URLTransform with an option to encode URL strings before converting them to an NSURL + - parameter shouldEncodeUrlString: when true (the default) the string is encoded before passing + to `NSURL(string:)` + - returns: an initialized transformer + */ + public init(shouldEncodeURLString: Bool = true) { + self.shouldEncodeURLString = shouldEncodeURLString + } + + public func transformFromJSON(_ value: Any?) -> URL? { + guard let URLString = value as? String else { return nil } + + if !shouldEncodeURLString { + return URL(string: URLString) + } + + guard let escapedURLString = URLString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else { + return nil + } + return URL(string: escapedURLString) + } + + public func transformToJSON(_ value: URL?) -> String? { + if let URL = value { + return URL.absoluteString + } + return nil + } +} diff --git a/Example/Pods/ObjectMapper/README.md b/Example/Pods/ObjectMapper/README.md new file mode 100644 index 0000000..e5f012e --- /dev/null +++ b/Example/Pods/ObjectMapper/README.md @@ -0,0 +1,351 @@ +ObjectMapper +============ +[![CocoaPods](https://img.shields.io/cocoapods/v/ObjectMapper.svg)](https://github.com/Hearst-DD/ObjectMapper) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Build Status](https://travis-ci.org/Hearst-DD/ObjectMapper.svg?branch=master)](https://travis-ci.org/Hearst-DD/ObjectMapper) + +ObjectMapper is a framework written in Swift that makes it easy for you to convert your model objects (classes and structs) to and from JSON. + +- [Features](#features) +- [The Basics](#the-basics) +- [Mapping Nested Objects](#easy-mapping-of-nested-objects) +- [Custom Transformations](#custom-transforms) +- [Subclassing](#subclasses) +- [Generic Objects](#generic-objects) +- [Mapping Context](#mapping-context) +- [ObjectMapper + Alamofire](#objectmapper--alamofire) +- [ObjectMapper + Realm](#objectmapper--realm) +- [To Do](#to-do) +- [Contributing](#contributing) +- [Installation](#installation) + +# Features: +- Mapping JSON to objects +- Mapping objects to JSON +- Nested Objects (stand alone, in arrays or in dictionaries) +- Custom transformations during mapping +- Struct support + +# The Basics +To support mapping, a class or struct just needs to implement the ```Mappable``` protocol which includes the following functions: +```swift +init?(_ map: Map) +mutating func mapping(map: Map) +``` +ObjectMapper uses the ```<-``` operator to define how each member variable maps to and from JSON. + +```swift +class User: Mappable { + var username: String? + var age: Int? + var weight: Double! + var array: [AnyObject]? + var dictionary: [String : AnyObject] = [:] + var bestFriend: User? // Nested User object + var friends: [User]? // Array of Users + var birthday: NSDate? + + required init?(_ map: Map) { + + } + + // Mappable + func mapping(map: Map) { + username <- map["username"] + age <- map["age"] + weight <- map["weight"] + array <- map["arr"] + dictionary <- map["dict"] + bestFriend <- map["best_friend"] + friends <- map["friends"] + birthday <- (map["birthday"], DateTransform()) + } +} + +struct Temperature: Mappable { + var celsius: Double? + var fahrenheit: Double? + + init?(_ map: Map) { + + } + + mutating func mapping(map: Map) { + celsius <- map["celsius"] + fahrenheit <- map["fahrenheit"] + } +} +``` + +Once your class implements `Mappable`, ObjectMapper allows you to easily convert to and from JSON. + +Convert a JSON string to a model object: +```swift +let user = User(JSONString: JSONString) +``` + +Convert a model object to a JSON string: +```swift +let JSONString = user.toJSONString(prettyPrint: true) +``` + +Alternatively, the `Mapper.swift` class can also be used to accomplish the above (it also provides extra functionality for other situations): +``` +// Convert JSON String to Model +let user = Mapper().map(JSONString: JSONString) +// Create JSON String from Model +let JSONString = Mapper().toJSONString(user, prettyPrint: true) +``` + +ObjectMapper can map classes composed of the following types: +- `Int` +- `Bool` +- `Double` +- `Float` +- `String` +- `RawRepresentable` (Enums) +- `Array` +- `Dictionary` +- `Object` +- `Array` +- `Array>` +- `Set` +- `Dictionary` +- `Dictionary>` +- Optionals of all the above +- Implicitly Unwrapped Optionals of the above + +## `Mappable` Protocol + +#### `mutating func mapping(map: Map)` +This function is where all mapping definitions should go. When parsing JSON, this function is executed after successful object creation. When generating JSON, it is the only function that is called on the object. + +#### `init?(_ map: Map)` +This failable initializer is used by ObjectMapper for object creation. It can be used by developers to validate JSON prior to object serialization. Returning nil within the function will prevent the mapping from occuring. You can inspect the JSON stored within the `Map` object to do your validation: +```swift +required init?(_ map: Map){ + // check if a required "name" property exists within the JSON. + if map.JSONDictionary["name"] == nil { + return nil + } +} +``` + +## `StaticMappable` Protocol +`StaticMappable` is an alternative to `Mappable`. It provides developers with a static function that is used by ObjectMapper for object initialization instead of `init?(_ map: Map)`. + +Note: `StaticMappable`, like `Mappable`, is a sub protocol of `BaseMappable` which is where the `mapping(_ map: Map)` function is defined. + +#### `static func objectForMapping(map: Map) -> BaseMappable?` +ObjectMapper uses this function to get objects to use for mapping. Developers should return an instance of an object that conforms to `BaseMappable` in this function. This function can also be used to: +- validate JSON prior to object serialization +- provide an existing cached object to be used for mapping +- return an object of another type (which also conforms to BaseMappable) to be used for mapping. For instance, you may inspect the JSON to infer the type of object that should be used for mapping ([see example](https://github.com/Hearst-DD/ObjectMapper/blob/master/ObjectMapperTests/ClassClusterTests.swift#L62)) + +If you need to implemented ObjectMapper in an extension, you will need to select this protocol instead of `Mappable`. + +# Easy Mapping of Nested Objects +ObjectMapper supports dot notation within keys for easy mapping of nested objects. Given the following JSON String: +```json +"distance" : { + "text" : "102 ft", + "value" : 31 +} +``` +You can access the nested objects as follows: +```swift +func mapping(map: Map) { + distance <- map["distance.value"] +} +``` +Nested keys also support accessing values from an array. Given a JSON response with an array of distances, the value could be accessed as follows: +``` +distance <- map["distances.0.value"] +``` +If you have a key that contains `.`, you can individually disable the above feature as follows: +```swift +func mapping(map: Map) { + identifier <- map["app.identifier", nested: false] +} +``` + +# Custom Transforms +ObjectMapper also supports custom transforms that convert values during the mapping process. To use a transform, simply create a tuple with ```map["field_name"]``` and the transform of your choice on the right side of the ```<-``` operator: +```swift +birthday <- (map["birthday"], DateTransform()) +``` +The above transform will convert the JSON Int value to an NSDate when reading JSON and will convert the NSDate to an Int when converting objects to JSON. + +You can easily create your own custom transforms by adopting and implementing the methods in the ```TransformType``` protocol: +```swift +public protocol TransformType { + typealias Object + typealias JSON + + func transformFromJSON(value: AnyObject?) -> Object? + func transformToJSON(value: Object?) -> JSON? +} +``` + +### TransformOf +In a lot of situations you can use the built-in transform class ```TransformOf``` to quickly perform a desired transformation. ```TransformOf``` is initialized with two types and two closures. The types define what the transform is converting to and from and the closures perform the actual transformation. + +For example, if you want to transform a JSON String value to an Int you could use ```TransformOf``` as follows: +```swift +let transform = TransformOf(fromJSON: { (value: String?) -> Int? in + // transform value from String? to Int? + return Int(value!) +}, toJSON: { (value: Int?) -> String? in + // transform value from Int? to String? + if let value = value { + return String(value) + } + return nil +}) + +id <- (map["id"], transform) +``` +Here is a more condensed version of the above: +```swift +id <- (map["id"], TransformOf(fromJSON: { Int($0!) }, toJSON: { $0.map { String($0) } })) +``` + +# Subclasses + +Classes that implement the ```Mappable``` protocol can easily be subclassed. When subclassing mappable classes, follow the structure below: + +```swift +class Base: Mappable { + var base: String? + + required init?(_ map: Map) { + + } + + func mapping(map: Map) { + base <- map["base"] + } +} + +class Subclass: Base { + var sub: String? + + required init?(_ map: Map) { + super.init(map) + } + + override func mapping(map: Map) { + super.mapping(map) + + sub <- map["sub"] + } +} +``` + +Make sure your subclass implemenation calls the right initializers and mapping functions to also apply the mappings from your superclass. + +# Generic Objects + +ObjectMapper can handle classes with generic types as long as the generic type also conforms to `Mappable`. See the following example: +```swift +class Result: Mappable { + var result: T? + + required init?(_ map: Map){ + + } + + func mapping(map: Map) { + result <- map["result"] + } +} + +let result = Mapper>().map(JSON) +``` + +# Mapping Context + +The `Map` object which is passed around during mapping, has an optional `MapContext` object that is available for developers to use if they need to pass information around during mapping. + +To take advantage of this feature, simple create an object that implements `MapContext` (which is an empty protocol) and pass it into `Mapper` during initialization. +```swift +struct Context: MapContext { + var importantMappingInfo = "Info that I need during mapping" +} + +class User: Mappable { + var name: String? + + required init?(_ map: Map){ + + } + + func mapping(map: Map){ + if let context = map.context as? Context { + // use context to make decisions about mapping + } + } +} + +let context = Context() +let user = Mapper(context: context).map(JSONString) +``` + +#ObjectMapper + Alamofire + +If you are using [Alamofire](https://github.com/Alamofire/Alamofire) for networking and you want to convert your responses to Swift objects, you can use [AlamofireObjectMapper](https://github.com/tristanhimmelman/AlamofireObjectMapper). It is a simple Alamofire extension that uses ObjectMapper to automatically map JSON response data to Swift objects. + + +#ObjectMapper + Realm + +ObjectMapper and Realm can be used together. Simply follow the class structure below and you will be able to use ObjectMapper to generate your Realm models: + +```swift +class Model: Object, Mappable { + dynamic var name = "" + + required convenience init?(_ map: Map) { + self.init() + } + + func mapping(map: Map) { + name <- map["name"] + } +} +``` + +If you want to serialize associated RealmObjects, you can use [ObjectMapper+Realm](https://github.com/jakenberg/ObjectMapper-Realm). It is a simple Realm extension that serializes arbitrary JSON into Realm's List class. + +Note: Generating a JSON string of a Realm Object using ObjectMappers' `toJSON` function only works within a Realm write transaction. This is caused because ObjectMapper uses the `inout` flag in its mapping functions (`<-`) which are used both for serializing and deserializing. Realm detects the flag and forces the `toJSON` function to be called within a write block even though the objects are not being modified. + +# To Do +- Improve error handling. Perhaps using `throws` +- Class cluster documentation + +# Contributing + +Contributions are very welcome 👍😃. + +Before submitting any pull request, please ensure you have run the included tests and they have passed. If you are including new functionality, please write test cases for it as well. + +# Installation +ObjectMapper can be added to your project using [CocoaPods 0.36 or later](http://blog.cocoapods.org/Pod-Authors-Guide-to-CocoaPods-Frameworks/) by adding the following line to your `Podfile`: + +```ruby +pod 'ObjectMapper', '~> 1.3' +``` + +If you're using [Carthage](https://github.com/Carthage/Carthage) you can add a dependency on ObjectMapper by adding it to your `Cartfile`: +``` +github "Hearst-DD/ObjectMapper" ~> 1.3 +``` + +Otherwise, ObjectMapper can be added as a submodule: + +1. Add ObjectMapper as a [submodule](http://git-scm.com/docs/git-submodule) by opening the terminal, `cd`-ing into your top-level project directory, and entering the command `git submodule add https://github.com/Hearst-DD/ObjectMapper.git` +2. Open the `ObjectMapper` folder, and drag `ObjectMapper.xcodeproj` into the file navigator of your app project. +3. In Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the "Targets" heading in the sidebar. +4. Ensure that the deployment target of `ObjectMapper.framework` matches that of the application target. +5. In the tab bar at the top of that window, open the "Build Phases" panel. +6. Expand the "Target Dependencies" group, and add `ObjectMapper.framework`. +7. Click on the `+` button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and add `ObjectMapper.framework`. diff --git a/Example/Pods/Pods.xcodeproj/project.pbxproj b/Example/Pods/Pods.xcodeproj/project.pbxproj index bd8c348..535f231 100644 --- a/Example/Pods/Pods.xcodeproj/project.pbxproj +++ b/Example/Pods/Pods.xcodeproj/project.pbxproj @@ -7,271 +7,136 @@ objects = { /* Begin PBXBuildFile section */ - 0202E91BD433E428B5ABA0057800D7BD /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CF0AE397A3983666DD05CCFEBB495D2D /* Foundation.framework */; }; - 028F7BF3F13D9D6CD093BE577808B1B1 /* DateFormatterTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = CDA993EC8C34829B83B7C527401EA1FF /* DateFormatterTransform.swift */; }; - 05CB6B5B3A5024A0678959CCBFC2A0F7 /* Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84DBEE1354EB2B74C2490CEC876C5E44 /* Operators.swift */; }; - 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA9FAC159DF216DEBC697BBA1C2F3A3F /* Timeline.swift */; }; - 12F7D4AA220E04394209750788551924 /* APNSUtil-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = D85D4A4452EDE5AA1605B4E8E5F8A09C /* APNSUtil-dummy.m */; }; - 1674976E5691AC6C3F018C2E42683218 /* ObjectMapper-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 58842F94DB5A654A43E36EB229E104C5 /* ObjectMapper-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 10BE86DA3D5E1FC2E267FEB3E5C04B9C /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 25C2F434629DF31A170BEDA7490BF3A9 /* AlamofireObjectMapper.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 869FF2EE9A527F3F19469125B76BE4FE /* AlamofireObjectMapper.framework */; }; - 260112ED9612CF82C0D3B42913FE73BC /* AlamofireObjectMapper-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 8F89AA801689E71C17F25FA2A0E93D8B /* AlamofireObjectMapper-dummy.m */; }; - 27429B88154F56606E23A9D517D2AC6C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CF0AE397A3983666DD05CCFEBB495D2D /* Foundation.framework */; }; - 2AE76D7833D5507C28DEB039D1866671 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CF0AE397A3983666DD05CCFEBB495D2D /* Foundation.framework */; }; - 2BC2003FED13A1D2AB91AA280641691B /* Pods-APNSUtil_Example-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 1CD771035EC108995DC9E7BF9872C60A /* Pods-APNSUtil_Example-dummy.m */; }; - 3000EF5DAA54B7B361CE8CC387EC769E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CF0AE397A3983666DD05CCFEBB495D2D /* Foundation.framework */; }; - 35AFBFB34DA1956EF7FCB64BC50946D8 /* EnumTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9091397C4729B3DCC1CE6856904B976 /* EnumTransform.swift */; }; - 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80B2426289289A77E7E548DE8EBD7A6B /* TaskDelegate.swift */; }; - 375698920E797E91DBDB8A3249B56B0E /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E827D71BF2F91A6742C882EC593324C /* Map.swift */; }; - 375AD5B4037B367C74B348C0644C0509 /* FromJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = B339A9D352CAD3A021BE61898B6FB9F8 /* FromJSON.swift */; }; - 37F2DCED1A444D3923D9D0A6380AB050 /* NSObject+Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = AEC3C2FE1CC510FE756FF9F09D6D0C2D /* NSObject+Codable.swift */; }; - 3EB9DC3783A4296C8BAAB07AC36C05F3 /* AlamofireObjectMapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0DCA6A9FCC4B1D65F83A545AF02C612 /* AlamofireObjectMapper.swift */; }; - 4863B9B382D2BA7A07C414A91E1DD6B0 /* ObjectMapper-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = CA1366C8D2B3A8AB85467335B347C19C /* ObjectMapper-dummy.m */; }; - 4E144A5F6A61AACDFDFF8E00A4E5C17B /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0193825564CFDBD56812D93E90FA2E4D /* Alamofire.framework */; }; - 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF1783D7A34EB66A031BF558A3110D78 /* Request.swift */; }; - 54334A036232F3AD1BD3D9D682EA702D /* HexColorTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CF68ACB68863BBEA9B6AE14A9519895 /* HexColorTransform.swift */; }; - 5BEC65F1E64F4BC3B0AD838E60E1C4A9 /* ToJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21A82EE9C1C556B2E8BFBA8D068C8401 /* ToJSON.swift */; }; - 5D0812EFA9986DE3E6336326AF267904 /* APNSInstance.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7029C9DB50DDA75466AA7966D21DD26 /* APNSInstance.swift */; }; - 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4D5FAB7BB93E73B5DF85A67C0D1BDB9 /* DispatchQueue+Alamofire.swift */; }; - 6140699B499701C95C16CA9E10A60B10 /* EnumOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = A42153AB600F91887F98BEDF4BB9A6BC /* EnumOperators.swift */; }; - 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AF63DC915CBBB5A6A37C5693618BCE9 /* ServerTrustPolicy.swift */; }; - 6561EFAAAFE0E3FB560D8B87D50C0414 /* DateTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5D744537DA1AB15AD87CC74D96215DA /* DateTransform.swift */; }; - 73B9C996AED49ED7CF8EC2A6F1738059 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CF0AE397A3983666DD05CCFEBB495D2D /* Foundation.framework */; }; - 74D7B56EE91ACB42EB352CEF073CF4BB /* MapError.swift in Sources */ = {isa = PBXBuildFile; fileRef = B264E8DFD26C5EDB5EB2ECB92D655321 /* MapError.swift */; }; - 765624085108240F1A2952486A60B66F /* DataTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CF6916D13AB7FD63E2FD155102F52DA /* DataTransform.swift */; }; - 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE5E4BD5634AA3F7F9790B3737626EC4 /* SessionDelegate.swift */; }; - 7BE81D28BE233A47AC5BE1B3FA26FDB5 /* TransformOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93B078301421E24725CBDAA939BEB8B3 /* TransformOperators.swift */; }; - 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = CDE2FB1CB544D67C7A28A45356A6569E /* Result.swift */; }; - 8022FE8243222780F58CDFD44A49F311 /* ISO8601DateTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B501F5330D236283AE79D286E8B15FB /* ISO8601DateTransform.swift */; }; - 80FBD965D6160B82CF4B55FB3409C1FD /* Mappable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40E85602775D62B1F6118974F3964D37 /* Mappable.swift */; }; - 82B33F223516A2AA7DA2985E5A954B88 /* ObjectMapper.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A4B4EFDBE0B5BB0C075AAD603A7479FA /* ObjectMapper.framework */; }; - 8491440E494CAAAE6DB2EA1D8D215903 /* ImmutableMappable.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8DC92DCD95A2CE28232D27E7222C67C /* ImmutableMappable.swift */; }; - 8F46A5E6F7671EA5EA201315E3A799E6 /* IntegerOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06D4FD479A75D5161C787905EA1BA4D8 /* IntegerOperators.swift */; }; + 0BB4EF281398F2725F72FDEE1810B637 /* Pods-APNSUtil_Example-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 7397B3445CE676557E4265AC8EF876BD /* Pods-APNSUtil_Example-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 145F6799296F51B9F7873400A3D8A139 /* TransformOf.swift in Sources */ = {isa = PBXBuildFile; fileRef = 12D80EDCBFDADFEAF83E73B1F4298320 /* TransformOf.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 19A895C2151A5A4B52BCD5D5E9797B6F /* APNSManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 587052262552155C7131469CDD7F8A52 /* APNSManager.swift */; }; + 1F2E918A8908D3D92E4182C36753837C /* Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF0D03B56D4F7FCD2115F600E9B3EBEB /* Operators.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 44293254A39E424D2CB406C290761A8B /* APNSInstance.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7029C9DB50DDA75466AA7966D21DD26 /* APNSInstance.swift */; }; + 474BC828D1115EB6A350756458E0CD06 /* ObjectMapper-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 3E3C40B9A5500F757AE2B4B683445695 /* ObjectMapper-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 482C235C5F03C7EEB6AC3B12245A3BBC /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E8359AB8D753A60C5C56B0034310570 /* Map.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 5BDAA3E3F32E24BBB3A49A154BD2F566 /* ObjectMapper-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 93F8B9088984CF79F217D0181BD4E544 /* ObjectMapper-dummy.m */; }; + 5C8ADD24DF4288FFD90DB7647C1C3D62 /* Mapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 112D75C7A5A386F5ABAEF337FB8F57EC /* Mapper.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 69B06A09B453136BF0DA5CF0F254F2E7 /* FromJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61998C6866565296C0486EBA1527EA1A /* FromJSON.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 8C33A9D0E248A6EA1A49B689CADFAA7E /* DataTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = E76DA17569AC50A6854CE5717667831D /* DataTransform.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 93D135DD91E720E4B0E418749FD06299 /* TransformType.swift in Sources */ = {isa = PBXBuildFile; fileRef = A06BAACE3FA7D3CBE72A76C4BA017E48 /* TransformType.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 946855648446BD41EEB975BCC6E617D0 /* Mappable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3AB688F03D047D5077D38B60DD99FBAE /* Mappable.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 95BF1622195CDF8B8F272F3A09C27B48 /* ObjectMapper.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 515BB24BCB558A6C6816DC6C1C97492C /* ObjectMapper.framework */; }; + 9B5A0B1F3D35B736FBD6DE2D7AEE1AB5 /* ToJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 027C6B65C90B5085666C806F6A5AB721 /* ToJSON.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; 9BE8BFDAFD5FFF6562683DF6A3E075AC /* Pods-APNSUtil_Tests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 6CB105BC1AD4C3A47657CB05A517C95C /* Pods-APNSUtil_Tests-dummy.m */; }; - 9C655404E5C7D42907234439EF895BD5 /* TransformOf.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B67422BB4CCE7DF4F1933D8446C5853 /* TransformOf.swift */; }; - 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5518B44E6BD587E06A1F14E2B75A375 /* AFError.swift */; }; - A1450B7B54640746CE365C20F3D112EA /* Pods-APNSUtil_Example-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 7397B3445CE676557E4265AC8EF876BD /* Pods-APNSUtil_Example-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - A22566C71CFE2650BB542C4626477DAA /* Mapper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9732DBE4794B1B0C36BE01801B214034 /* Mapper.swift */; }; - A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6904F2951EDDDF8A86B40E2AAB93527C /* NetworkReachabilityManager.swift */; }; + A4ABDF7DA8DEFD6C5F902A37F57ACCC6 /* URLTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DE9E0EBFB8EC6494211B4FC150DA5B2 /* URLTransform.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; A86EC6FA9849E85E07CDAA83213CC8FD /* Pods-APNSUtil_Tests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 8CAA54154B306944E1171E39A9C6DBA9 /* Pods-APNSUtil_Tests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 8D11BAFC6A2AC82E2C3D730D6D28B59F /* Alamofire-dummy.m */; }; - AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 134430AD6BCC02A45AD7C4DBAF50C6A0 /* SessionManager.swift */; }; - B0438CAC2C1459719EC744B12F5C91DC /* DictionaryTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = C323EFA758A4C140F3E416C76D022843 /* DictionaryTransform.swift */; }; - B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 926722659F3F03EDCD52039F064B6A09 /* MultipartFormData.swift */; }; - B73D4607C1DB58B06986EF7182EE9D08 /* CustomDateFormatTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = EADDCC5720720B7AA5CFF0DC72F3B3F9 /* CustomDateFormatTransform.swift */; }; - BB0BDE136A252F119EB3631B328143FA /* ObjectMapper.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A4B4EFDBE0B5BB0C075AAD603A7479FA /* ObjectMapper.framework */; }; - BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5F45218D36108E9B8FC8CBC403F9567 /* Validation.swift */; }; - BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CAF45E56B5BAF03813F8B18E348C132 /* ParameterEncoding.swift */; }; - BF2DA37432E1D9314BE16AC227B5C07D /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0193825564CFDBD56812D93E90FA2E4D /* Alamofire.framework */; }; - C133DC6459457DE302ECD5B038DC2461 /* APNSManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 587052262552155C7131469CDD7F8A52 /* APNSManager.swift */; }; - CA1E06CB00C147AD88B8A721BF00F8D5 /* NSDecimalNumberTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = DFBF46735426641B03E3B95AAB9BA5AA /* NSDecimalNumberTransform.swift */; }; - CA2F35983F4B2670A0A195384FF21BD0 /* URLTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = C586828E4F4612149E740DFB653BF367 /* URLTransform.swift */; }; - CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = FBBF6A0A78F9806F84CB665EAE59592D /* Response.swift */; }; - D7414CF8CFD499D328E07EE53D88BA7F /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CF0AE397A3983666DD05CCFEBB495D2D /* Foundation.framework */; }; - E1FDB8EB49DCBA9C697BF5EE4103D28A /* AlamofireObjectMapper-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = BCF54625A4DEFD8C62BD62E98ABF3964 /* AlamofireObjectMapper-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - E2B172D4B630FCBD7D61A3FA14892658 /* TransformType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 380095459E1F371BFB777E5C70EC68B4 /* TransformType.swift */; }; - EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55D544C8A59616D0B71C49516901BC50 /* Notifications.swift */; }; - F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B7CB4C3C0344D0BA34DC49DE9EFDDD8 /* ResponseSerialization.swift */; }; - F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B40A51A4BCA4B665DFFE8AF136844E7 /* Alamofire.swift */; }; - FA216D830A6BC63572A1BAA766FEF827 /* APNSUtil-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9C4B45C0912C00EA24AB9369BAE3339F /* APNSUtil-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + AE9A572F49619A67EA839319EC4D3B52 /* NSDecimalNumberTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 656C835719301CE6AD3F310BE0A775E3 /* NSDecimalNumberTransform.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + B06D659923AA2EB173C0C7C442F63EBE /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BBF2A8127EDF29ABAA8C2FD230237309 /* Foundation.framework */; }; + B2460C7DE53E260EEB686A681FA3B50C /* CustomDateFormatTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE4D02DC965DE9E40147BD31446858DF /* CustomDateFormatTransform.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + BC8A6A56332550BA8971E030F3D7D8AF /* DictionaryTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = C37D9B1E53E879BF167168969D1EEAB6 /* DictionaryTransform.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + BDCD0842F48C5A23486CD1B0E4376D0B /* APNSUtil-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = D85D4A4452EDE5AA1605B4E8E5F8A09C /* APNSUtil-dummy.m */; }; + C1A7AC15996C3A3B90B73914563CEEB9 /* NSObject+Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = AEC3C2FE1CC510FE756FF9F09D6D0C2D /* NSObject+Codable.swift */; }; + CA685C6CACDDCAD80706FE33EF9A1905 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BBF2A8127EDF29ABAA8C2FD230237309 /* Foundation.framework */; }; + CAC46E189303160EBAB515A335C99D37 /* APNSUtil-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9C4B45C0912C00EA24AB9369BAE3339F /* APNSUtil-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D21EDFD6C67B02EDF959000665672155 /* EnumTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB4229A951C4A418977079EBDF91F868 /* EnumTransform.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + D7321A0F3650CDAC522A1CB5D94B2ACD /* Pods-APNSUtil_Example-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 1CD771035EC108995DC9E7BF9872C60A /* Pods-APNSUtil_Example-dummy.m */; }; + D7414CF8CFD499D328E07EE53D88BA7F /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BBF2A8127EDF29ABAA8C2FD230237309 /* Foundation.framework */; }; + DED06D4BE1E80D6EFE672D8C9432C17F /* ISO8601DateTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B44FDBB52336DEED4EE3B4E24A7E0E9 /* ISO8601DateTransform.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + E910392E480DF8A592D7008A1EA61A83 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BBF2A8127EDF29ABAA8C2FD230237309 /* Foundation.framework */; }; + FDCE519E6BD4BBCF2B77C916CC03D39A /* DateFormatterTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09D876A505779BD7A784A15AFF71738D /* DateFormatterTransform.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + FE8228473A48EAEEA8BCAC34BD19AA5C /* DateTransform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F2E86CC5E4EDCF1ACB7B71EECAE2B97 /* DateTransform.swift */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ - 3303BAB00ED7E2F11A457038A6944E9E /* PBXContainerItemProxy */ = { + 097F39686B79EA39C000E7A84947C94D /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; - remoteInfo = Alamofire; - }; - 35CD6496B316B6C70A67C43CB60ADD7C /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; - proxyType = 1; - remoteGlobalIDString = 2F5622F3B18DF497981AB58C6D1FC72F; - remoteInfo = ObjectMapper; - }; - 3CC807134F88B93086B46E13FDC52A78 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; - proxyType = 1; - remoteGlobalIDString = 9502FB01641FBABB78522037E882757B; - remoteInfo = AlamofireObjectMapper; - }; - 669D6265FFC323BAE23E8ADA58242BBE /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; - proxyType = 1; - remoteGlobalIDString = 9502FB01641FBABB78522037E882757B; - remoteInfo = AlamofireObjectMapper; - }; - 6CFD44F05E8B4C61BB6CB679EE31B7A8 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; - proxyType = 1; - remoteGlobalIDString = F8E946FDC9A09CF02374E2E041304F76; + remoteGlobalIDString = 427EEA9FEC39BBE1D05384CD8362177E; remoteInfo = APNSUtil; }; - 9E872C79DA3A91657A381E45E59E68B7 /* PBXContainerItemProxy */ = { + 3A2935EFF85DBF5E644B48087878968C /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 2F5622F3B18DF497981AB58C6D1FC72F; + remoteGlobalIDString = 4A3627E04D7B66CB45B951C08F6E17E9; remoteInfo = ObjectMapper; }; - A04F064E4A878D0A36386C26C1925C4F /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; - proxyType = 1; - remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; - remoteInfo = Alamofire; - }; - AE9EB015A659C7E42FA0501262FD8E20 /* PBXContainerItemProxy */ = { + 4D3BB247F628845F838C9303B6E3DB9A /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; - remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; - remoteInfo = Alamofire; - }; - C2A743750D8435124390DA2CA737665B /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; - proxyType = 1; - remoteGlobalIDString = 2F5622F3B18DF497981AB58C6D1FC72F; + remoteGlobalIDString = 4A3627E04D7B66CB45B951C08F6E17E9; remoteInfo = ObjectMapper; }; /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 0193825564CFDBD56812D93E90FA2E4D /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 039B70CA50A21D1EC495F81422AE9613 /* AlamofireObjectMapper-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "AlamofireObjectMapper-prefix.pch"; sourceTree = ""; }; - 06D4FD479A75D5161C787905EA1BA4D8 /* IntegerOperators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = IntegerOperators.swift; path = Sources/IntegerOperators.swift; sourceTree = ""; }; + 027C6B65C90B5085666C806F6A5AB721 /* ToJSON.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ToJSON.swift; path = ObjectMapper/Core/ToJSON.swift; sourceTree = ""; }; 09AE27EA9A97A5B89E53D965E992C566 /* APNSUtil.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = APNSUtil.xcconfig; sourceTree = ""; }; - 0CAF45E56B5BAF03813F8B18E348C132 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + 09D876A505779BD7A784A15AFF71738D /* DateFormatterTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DateFormatterTransform.swift; path = ObjectMapper/Transforms/DateFormatterTransform.swift; sourceTree = ""; }; 0D17CC6CD5634D88F677162DE709787C /* Pods-APNSUtil_Example-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-APNSUtil_Example-acknowledgements.markdown"; sourceTree = ""; }; - 10BE86DA3D5E1FC2E267FEB3E5C04B9C /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; - 134430AD6BCC02A45AD7C4DBAF50C6A0 /* SessionManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionManager.swift; path = Source/SessionManager.swift; sourceTree = ""; }; + 112D75C7A5A386F5ABAEF337FB8F57EC /* Mapper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Mapper.swift; path = ObjectMapper/Core/Mapper.swift; sourceTree = ""; }; + 12D80EDCBFDADFEAF83E73B1F4298320 /* TransformOf.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TransformOf.swift; path = ObjectMapper/Transforms/TransformOf.swift; sourceTree = ""; }; 1CD771035EC108995DC9E7BF9872C60A /* Pods-APNSUtil_Example-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-APNSUtil_Example-dummy.m"; sourceTree = ""; }; - 21A82EE9C1C556B2E8BFBA8D068C8401 /* ToJSON.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ToJSON.swift; path = Sources/ToJSON.swift; sourceTree = ""; }; - 2324CD4089FDF77B27D7CE76606D529D /* ObjectMapper.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = ObjectMapper.xcconfig; sourceTree = ""; }; - 269527962433474AA1073F5062B51353 /* ObjectMapper.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = ObjectMapper.framework; path = ObjectMapper.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 21249291725D837BF8985189444FFEBA /* ObjectMapper.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = ObjectMapper.xcconfig; sourceTree = ""; }; 27F0F76988C7FCBF2C7ADD2BE7268A84 /* Pods-APNSUtil_Example-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-APNSUtil_Example-frameworks.sh"; sourceTree = ""; }; - 28B63EE513C824EC50135E751CCC17C3 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = Alamofire.modulemap; sourceTree = ""; }; - 2B40A51A4BCA4B665DFFE8AF136844E7 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; - 2F0C618433CA6E66F8AEC4563D4F8325 /* AlamofireObjectMapper.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = AlamofireObjectMapper.framework; path = AlamofireObjectMapper.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 31B6CED63C84E0DFCF84E4F98778016A /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 320FD2F8732D20C07C0185EEA77D913F /* Pods-APNSUtil_Tests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-APNSUtil_Tests-frameworks.sh"; sourceTree = ""; }; - 380095459E1F371BFB777E5C70EC68B4 /* TransformType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TransformType.swift; path = Sources/TransformType.swift; sourceTree = ""; }; 392D62C79253E56D8D4FC9B77BCEBEC7 /* Pods-APNSUtil_Example.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = "Pods-APNSUtil_Example.modulemap"; sourceTree = ""; }; 3971FD2397168A24DC2BE8DC1CF11C06 /* Pods-APNSUtil_Tests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-APNSUtil_Tests.release.xcconfig"; sourceTree = ""; }; - 3B501F5330D236283AE79D286E8B15FB /* ISO8601DateTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ISO8601DateTransform.swift; path = Sources/ISO8601DateTransform.swift; sourceTree = ""; }; - 3D9F3EB6D49ECFE9A4BC670C59647CBF /* AlamofireObjectMapper.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = AlamofireObjectMapper.xcconfig; sourceTree = ""; }; + 3A5281418FEC9184304F69218872F5CA /* ObjectMapper-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "ObjectMapper-prefix.pch"; sourceTree = ""; }; + 3AB688F03D047D5077D38B60DD99FBAE /* Mappable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Mappable.swift; path = ObjectMapper/Core/Mappable.swift; sourceTree = ""; }; 3DED118962D9F865289E1CE69E407B65 /* APNSUtil-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "APNSUtil-prefix.pch"; sourceTree = ""; }; - 40E85602775D62B1F6118974F3964D37 /* Mappable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Mappable.swift; path = Sources/Mappable.swift; sourceTree = ""; }; + 3E3C40B9A5500F757AE2B4B683445695 /* ObjectMapper-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "ObjectMapper-umbrella.h"; sourceTree = ""; }; 4CB4A28D3BE28D53BF26FFAA7E02BDCE /* Pods-APNSUtil_Example.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-APNSUtil_Example.debug.xcconfig"; sourceTree = ""; }; - 55D544C8A59616D0B71C49516901BC50 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; - 57C7E258AA97278EEE78F48186CB69F5 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire.framework; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 515BB24BCB558A6C6816DC6C1C97492C /* ObjectMapper.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = ObjectMapper.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 56E140897C7688E1E4A1BA84BFBA0658 /* ObjectMapper.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = ObjectMapper.framework; path = ObjectMapper.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 587052262552155C7131469CDD7F8A52 /* APNSManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = APNSManager.swift; path = APNSUtil/Classes/APNSManager.swift; sourceTree = ""; }; - 58842F94DB5A654A43E36EB229E104C5 /* ObjectMapper-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "ObjectMapper-umbrella.h"; sourceTree = ""; }; 59373EB39F10851BE99AC26F256DB1E8 /* Pods-APNSUtil_Tests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-APNSUtil_Tests.debug.xcconfig"; sourceTree = ""; }; - 5AF63DC915CBBB5A6A37C5693618BCE9 /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; - 5CF68ACB68863BBEA9B6AE14A9519895 /* HexColorTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HexColorTransform.swift; path = Sources/HexColorTransform.swift; sourceTree = ""; }; - 600F89005E87894E991AE62B4469D6ED /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; - 6904F2951EDDDF8A86B40E2AAB93527C /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; + 5B44FDBB52336DEED4EE3B4E24A7E0E9 /* ISO8601DateTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ISO8601DateTransform.swift; path = ObjectMapper/Transforms/ISO8601DateTransform.swift; sourceTree = ""; }; + 5F2E86CC5E4EDCF1ACB7B71EECAE2B97 /* DateTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DateTransform.swift; path = ObjectMapper/Transforms/DateTransform.swift; sourceTree = ""; }; + 61998C6866565296C0486EBA1527EA1A /* FromJSON.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FromJSON.swift; path = ObjectMapper/Core/FromJSON.swift; sourceTree = ""; }; + 656C835719301CE6AD3F310BE0A775E3 /* NSDecimalNumberTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NSDecimalNumberTransform.swift; path = ObjectMapper/Transforms/NSDecimalNumberTransform.swift; sourceTree = ""; }; 6CB105BC1AD4C3A47657CB05A517C95C /* Pods-APNSUtil_Tests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-APNSUtil_Tests-dummy.m"; sourceTree = ""; }; - 6E3895EE01AE5EB9B17BF23C9913AF66 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 71533E305DB16ACC9C38A73542590FC0 /* ObjectMapper.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = ObjectMapper.modulemap; sourceTree = ""; }; - 71FED29CF4CC7320DFFB20537E0CD5D5 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + 725C6A197DCDE3F393B6572AC55AFC02 /* Pods_APNSUtil_Example.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_APNSUtil_Example.framework; path = "Pods-APNSUtil_Example.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; 7397B3445CE676557E4265AC8EF876BD /* Pods-APNSUtil_Example-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-APNSUtil_Example-umbrella.h"; sourceTree = ""; }; - 7CF6916D13AB7FD63E2FD155102F52DA /* DataTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DataTransform.swift; path = Sources/DataTransform.swift; sourceTree = ""; }; - 7F484218DAD25EDC42322BDD4D8569AF /* Pods_APNSUtil_Example.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_APNSUtil_Example.framework; path = "Pods-APNSUtil_Example.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; - 80B2426289289A77E7E548DE8EBD7A6B /* TaskDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TaskDelegate.swift; path = Source/TaskDelegate.swift; sourceTree = ""; }; - 84DBEE1354EB2B74C2490CEC876C5E44 /* Operators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Operators.swift; path = Sources/Operators.swift; sourceTree = ""; }; - 869FF2EE9A527F3F19469125B76BE4FE /* AlamofireObjectMapper.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = AlamofireObjectMapper.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 8767D444FE177C59E23970E08CF68225 /* Pods-APNSUtil_Example-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-APNSUtil_Example-acknowledgements.plist"; sourceTree = ""; }; - 8B67422BB4CCE7DF4F1933D8446C5853 /* TransformOf.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TransformOf.swift; path = Sources/TransformOf.swift; sourceTree = ""; }; 8CAA54154B306944E1171E39A9C6DBA9 /* Pods-APNSUtil_Tests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-APNSUtil_Tests-umbrella.h"; sourceTree = ""; }; - 8D11BAFC6A2AC82E2C3D730D6D28B59F /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; - 8F89AA801689E71C17F25FA2A0E93D8B /* AlamofireObjectMapper-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "AlamofireObjectMapper-dummy.m"; sourceTree = ""; }; - 926722659F3F03EDCD52039F064B6A09 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + 8DE9E0EBFB8EC6494211B4FC150DA5B2 /* URLTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLTransform.swift; path = ObjectMapper/Transforms/URLTransform.swift; sourceTree = ""; }; + 8E8359AB8D753A60C5C56B0034310570 /* Map.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Map.swift; path = ObjectMapper/Core/Map.swift; sourceTree = ""; }; + 92CAA0BD4FF82C53F443C5226F9305AA /* APNSUtil.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = APNSUtil.framework; path = APNSUtil.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; - 93B078301421E24725CBDAA939BEB8B3 /* TransformOperators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TransformOperators.swift; path = Sources/TransformOperators.swift; sourceTree = ""; }; - 9732DBE4794B1B0C36BE01801B214034 /* Mapper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Mapper.swift; path = Sources/Mapper.swift; sourceTree = ""; }; - 98C3594063A260A9D022874711741B22 /* APNSUtil.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = APNSUtil.framework; path = APNSUtil.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 9B7CB4C3C0344D0BA34DC49DE9EFDDD8 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + 93F8B9088984CF79F217D0181BD4E544 /* ObjectMapper-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "ObjectMapper-dummy.m"; sourceTree = ""; }; 9C4B45C0912C00EA24AB9369BAE3339F /* APNSUtil-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "APNSUtil-umbrella.h"; sourceTree = ""; }; 9C79093F5C906DC4CB16D970C5816825 /* Pods-APNSUtil_Tests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-APNSUtil_Tests-acknowledgements.markdown"; sourceTree = ""; }; - 9E827D71BF2F91A6742C882EC593324C /* Map.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Map.swift; path = Sources/Map.swift; sourceTree = ""; }; - A42153AB600F91887F98BEDF4BB9A6BC /* EnumOperators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EnumOperators.swift; path = Sources/EnumOperators.swift; sourceTree = ""; }; - A4B4EFDBE0B5BB0C075AAD603A7479FA /* ObjectMapper.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = ObjectMapper.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - A4D5FAB7BB93E73B5DF85A67C0D1BDB9 /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; + A06BAACE3FA7D3CBE72A76C4BA017E48 /* TransformType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TransformType.swift; path = ObjectMapper/Transforms/TransformType.swift; sourceTree = ""; }; A51A6C3FF908D263D09B7AE96F97FE4B /* APNSUtil.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = APNSUtil.modulemap; sourceTree = ""; }; - A8DC92DCD95A2CE28232D27E7222C67C /* ImmutableMappable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImmutableMappable.swift; path = Sources/ImmutableMappable.swift; sourceTree = ""; }; - AA9FAC159DF216DEBC697BBA1C2F3A3F /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; AE3D4EDB6EB4071B87FF7098578B552C /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; AEC3C2FE1CC510FE756FF9F09D6D0C2D /* NSObject+Codable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Codable.swift"; path = "APNSUtil/Classes/NSObject+Codable.swift"; sourceTree = ""; }; - AF1783D7A34EB66A031BF558A3110D78 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; - B264E8DFD26C5EDB5EB2ECB92D655321 /* MapError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MapError.swift; path = Sources/MapError.swift; sourceTree = ""; }; - B339A9D352CAD3A021BE61898B6FB9F8 /* FromJSON.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FromJSON.swift; path = Sources/FromJSON.swift; sourceTree = ""; }; + BBF2A8127EDF29ABAA8C2FD230237309 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; BCB4B5C28ABD64CF463BB5295406D0BD /* Pods-APNSUtil_Tests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-APNSUtil_Tests-acknowledgements.plist"; sourceTree = ""; }; - BCF54625A4DEFD8C62BD62E98ABF3964 /* AlamofireObjectMapper-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "AlamofireObjectMapper-umbrella.h"; sourceTree = ""; }; - C323EFA758A4C140F3E416C76D022843 /* DictionaryTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DictionaryTransform.swift; path = Sources/DictionaryTransform.swift; sourceTree = ""; }; - C586828E4F4612149E740DFB653BF367 /* URLTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLTransform.swift; path = Sources/URLTransform.swift; sourceTree = ""; }; + BE4D02DC965DE9E40147BD31446858DF /* CustomDateFormatTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CustomDateFormatTransform.swift; path = ObjectMapper/Transforms/CustomDateFormatTransform.swift; sourceTree = ""; }; + C37D9B1E53E879BF167168969D1EEAB6 /* DictionaryTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DictionaryTransform.swift; path = ObjectMapper/Transforms/DictionaryTransform.swift; sourceTree = ""; }; C59F825AB4E361ABE6BBAD7933FF5C8F /* Pods-APNSUtil_Tests-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-APNSUtil_Tests-resources.sh"; sourceTree = ""; }; - C5D744537DA1AB15AD87CC74D96215DA /* DateTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DateTransform.swift; path = Sources/DateTransform.swift; sourceTree = ""; }; - CA1366C8D2B3A8AB85467335B347C19C /* ObjectMapper-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "ObjectMapper-dummy.m"; sourceTree = ""; }; CD774CC9E8D702A259B90D2E907EEDFB /* LICENSE */ = {isa = PBXFileReference; includeInIndex = 1; path = LICENSE; sourceTree = ""; }; - CDA993EC8C34829B83B7C527401EA1FF /* DateFormatterTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DateFormatterTransform.swift; path = Sources/DateFormatterTransform.swift; sourceTree = ""; }; - CDE2FB1CB544D67C7A28A45356A6569E /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; - CF0AE397A3983666DD05CCFEBB495D2D /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; - D4EC58A271FB7EC2877AB71ED399BAAF /* ObjectMapper-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "ObjectMapper-prefix.pch"; sourceTree = ""; }; + D7AC23C67BBBDA6981B12C6DE90F51BC /* ObjectMapper.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = ObjectMapper.modulemap; sourceTree = ""; }; D85D4A4452EDE5AA1605B4E8E5F8A09C /* APNSUtil-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "APNSUtil-dummy.m"; sourceTree = ""; }; - DE5E4BD5634AA3F7F9790B3737626EC4 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; - DFBF46735426641B03E3B95AAB9BA5AA /* NSDecimalNumberTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NSDecimalNumberTransform.swift; path = Sources/NSDecimalNumberTransform.swift; sourceTree = ""; }; + DB4229A951C4A418977079EBDF91F868 /* EnumTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EnumTransform.swift; path = ObjectMapper/Transforms/EnumTransform.swift; sourceTree = ""; }; + DCD72DD56EA5A48818EA6E52DF8C3094 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; E040EFB9B0D05472D9D859586664F0B9 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - E06AE9F2E22BFE03BB10112EF79B98E1 /* AlamofireObjectMapper.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = AlamofireObjectMapper.modulemap; sourceTree = ""; }; - E5518B44E6BD587E06A1F14E2B75A375 /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; - E5F45218D36108E9B8FC8CBC403F9567 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; - E9091397C4729B3DCC1CE6856904B976 /* EnumTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EnumTransform.swift; path = Sources/EnumTransform.swift; sourceTree = ""; }; - E93CEC2D065CADBD0FE331918C6BC5BA /* Pods_APNSUtil_Tests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_APNSUtil_Tests.framework; path = "Pods-APNSUtil_Tests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; - EADDCC5720720B7AA5CFF0DC72F3B3F9 /* CustomDateFormatTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CustomDateFormatTransform.swift; path = Sources/CustomDateFormatTransform.swift; sourceTree = ""; }; - EDE70BADC11895812FB2029E6877BAF9 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - F0DCA6A9FCC4B1D65F83A545AF02C612 /* AlamofireObjectMapper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AlamofireObjectMapper.swift; path = AlamofireObjectMapper/AlamofireObjectMapper.swift; sourceTree = ""; }; + E218CD0160F90E89470DAF4345708DE9 /* Pods_APNSUtil_Tests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_APNSUtil_Tests.framework; path = "Pods-APNSUtil_Tests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + E76DA17569AC50A6854CE5717667831D /* DataTransform.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DataTransform.swift; path = ObjectMapper/Transforms/DataTransform.swift; sourceTree = ""; }; + EF0D03B56D4F7FCD2115F600E9B3EBEB /* Operators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Operators.swift; path = ObjectMapper/Core/Operators.swift; sourceTree = ""; }; F11AED055135CDAAF38E6A682B6F7C79 /* Pods-APNSUtil_Tests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = "Pods-APNSUtil_Tests.modulemap"; sourceTree = ""; }; F418F53A54152E9BF9557E1ACFB5B443 /* APNSUtil.podspec */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; path = APNSUtil.podspec; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; F7029C9DB50DDA75466AA7966D21DD26 /* APNSInstance.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = APNSInstance.swift; path = APNSUtil/Classes/APNSInstance.swift; sourceTree = ""; }; F92F50CB3C736800443092405446401B /* README.md */ = {isa = PBXFileReference; includeInIndex = 1; path = README.md; sourceTree = ""; }; - FBBF6A0A78F9806F84CB665EAE59592D /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; FC307F4C23F997DA113D80015F941DBD /* Pods-APNSUtil_Example.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-APNSUtil_Example.release.xcconfig"; sourceTree = ""; }; FCD9E18BC979789AB8186E09BC95A7B3 /* Pods-APNSUtil_Example-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-APNSUtil_Example-resources.sh"; sourceTree = ""; }; FE2FF7AA3A0E537BC4C4161824C84CCD /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ - 07C885E3AA2C1BC94DF8373CE1BEA76F /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 2AE76D7833D5507C28DEB039D1866671 /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 498A93B0A50757ED8922C35F4FF7C169 /* Frameworks */ = { + 4F66BA02F4A9C5518DE9E927B32A203D /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - BF2DA37432E1D9314BE16AC227B5C07D /* Alamofire.framework in Frameworks */, - 25C2F434629DF31A170BEDA7490BF3A9 /* AlamofireObjectMapper.framework in Frameworks */, - 27429B88154F56606E23A9D517D2AC6C /* Foundation.framework in Frameworks */, - BB0BDE136A252F119EB3631B328143FA /* ObjectMapper.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 8562E6EA2DA88FF69C44B2AF77E3EDDD /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 0202E91BD433E428B5ABA0057800D7BD /* Foundation.framework in Frameworks */, + E910392E480DF8A592D7008A1EA61A83 /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -283,21 +148,20 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 99195E4207764744AEC07ECCBCD550EB /* Frameworks */ = { + 8E4EE43734851AD9DE7585F201948BD7 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 73B9C996AED49ED7CF8EC2A6F1738059 /* Foundation.framework in Frameworks */, + CA685C6CACDDCAD80706FE33EF9A1905 /* Foundation.framework in Frameworks */, + 95BF1622195CDF8B8F272F3A09C27B48 /* ObjectMapper.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; - D55863AC11CD93D729F336D4A1837D9C /* Frameworks */ = { + E7E8A9AEF2259F03268A1E07C95020DD /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 4E144A5F6A61AACDFDFF8E00A4E5C17B /* Alamofire.framework in Frameworks */, - 3000EF5DAA54B7B361CE8CC387EC769E /* Foundation.framework in Frameworks */, - 82B33F223516A2AA7DA2985E5A954B88 /* ObjectMapper.framework in Frameworks */, + B06D659923AA2EB173C0C7C442F63EBE /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -336,20 +200,6 @@ path = "Example/Pods/Target Support Files/APNSUtil"; sourceTree = ""; }; - 1DA603A37B19C4DC95FF0B44107DD91B /* Support Files */ = { - isa = PBXGroup; - children = ( - E06AE9F2E22BFE03BB10112EF79B98E1 /* AlamofireObjectMapper.modulemap */, - 3D9F3EB6D49ECFE9A4BC670C59647CBF /* AlamofireObjectMapper.xcconfig */, - 8F89AA801689E71C17F25FA2A0E93D8B /* AlamofireObjectMapper-dummy.m */, - 039B70CA50A21D1EC495F81422AE9613 /* AlamofireObjectMapper-prefix.pch */, - BCF54625A4DEFD8C62BD62E98ABF3964 /* AlamofireObjectMapper-umbrella.h */, - 6E3895EE01AE5EB9B17BF23C9913AF66 /* Info.plist */, - ); - name = "Support Files"; - path = "../Target Support Files/AlamofireObjectMapper"; - sourceTree = ""; - }; 2F59E7BDC76A46F64CB7FE5814C670DA /* Pod */ = { isa = PBXGroup; children = ( @@ -360,19 +210,6 @@ name = Pod; sourceTree = ""; }; - 4BB455C525F38CDF1E7890B90AEB0B38 /* Products */ = { - isa = PBXGroup; - children = ( - 57C7E258AA97278EEE78F48186CB69F5 /* Alamofire.framework */, - 2F0C618433CA6E66F8AEC4563D4F8325 /* AlamofireObjectMapper.framework */, - 98C3594063A260A9D022874711741B22 /* APNSUtil.framework */, - 269527962433474AA1073F5062B51353 /* ObjectMapper.framework */, - 7F484218DAD25EDC42322BDD4D8569AF /* Pods_APNSUtil_Example.framework */, - E93CEC2D065CADBD0FE331918C6BC5BA /* Pods_APNSUtil_Tests.framework */, - ); - name = Products; - sourceTree = ""; - }; 4E103E339AE2E1444F45080D1F1AB2E0 /* Development Pods */ = { isa = PBXGroup; children = ( @@ -381,53 +218,41 @@ name = "Development Pods"; sourceTree = ""; }; - 50CCEE653690BB4103016801EDC2E84B /* Support Files */ = { + 50DA52F9ED8316228A443D4AEB77D3E7 /* ObjectMapper */ = { isa = PBXGroup; children = ( - EDE70BADC11895812FB2029E6877BAF9 /* Info.plist */, - 71533E305DB16ACC9C38A73542590FC0 /* ObjectMapper.modulemap */, - 2324CD4089FDF77B27D7CE76606D529D /* ObjectMapper.xcconfig */, - CA1366C8D2B3A8AB85467335B347C19C /* ObjectMapper-dummy.m */, - D4EC58A271FB7EC2877AB71ED399BAAF /* ObjectMapper-prefix.pch */, - 58842F94DB5A654A43E36EB229E104C5 /* ObjectMapper-umbrella.h */, + BE4D02DC965DE9E40147BD31446858DF /* CustomDateFormatTransform.swift */, + E76DA17569AC50A6854CE5717667831D /* DataTransform.swift */, + 09D876A505779BD7A784A15AFF71738D /* DateFormatterTransform.swift */, + 5F2E86CC5E4EDCF1ACB7B71EECAE2B97 /* DateTransform.swift */, + C37D9B1E53E879BF167168969D1EEAB6 /* DictionaryTransform.swift */, + DB4229A951C4A418977079EBDF91F868 /* EnumTransform.swift */, + 61998C6866565296C0486EBA1527EA1A /* FromJSON.swift */, + 5B44FDBB52336DEED4EE3B4E24A7E0E9 /* ISO8601DateTransform.swift */, + 8E8359AB8D753A60C5C56B0034310570 /* Map.swift */, + 3AB688F03D047D5077D38B60DD99FBAE /* Mappable.swift */, + 112D75C7A5A386F5ABAEF337FB8F57EC /* Mapper.swift */, + 656C835719301CE6AD3F310BE0A775E3 /* NSDecimalNumberTransform.swift */, + EF0D03B56D4F7FCD2115F600E9B3EBEB /* Operators.swift */, + 027C6B65C90B5085666C806F6A5AB721 /* ToJSON.swift */, + 12D80EDCBFDADFEAF83E73B1F4298320 /* TransformOf.swift */, + A06BAACE3FA7D3CBE72A76C4BA017E48 /* TransformType.swift */, + 8DE9E0EBFB8EC6494211B4FC150DA5B2 /* URLTransform.swift */, + F5D91224DF0AE46871245DA803B28C87 /* Support Files */, ); - name = "Support Files"; - path = "../Target Support Files/ObjectMapper"; + name = ObjectMapper; + path = ObjectMapper; sourceTree = ""; }; - 56FF7B91BE0AA544B1507169AE0EEE1B /* Frameworks */ = { + 72A4F101D4D40D3C9EBA12D90663F5FA /* Frameworks */ = { isa = PBXGroup; children = ( - 0193825564CFDBD56812D93E90FA2E4D /* Alamofire.framework */, - 869FF2EE9A527F3F19469125B76BE4FE /* AlamofireObjectMapper.framework */, - A4B4EFDBE0B5BB0C075AAD603A7479FA /* ObjectMapper.framework */, - 574C0678D07A16C50FCD64C176AC5CE4 /* iOS */, + 515BB24BCB558A6C6816DC6C1C97492C /* ObjectMapper.framework */, + B698BE032F2E2D71DEAC2D89C403A556 /* iOS */, ); name = Frameworks; sourceTree = ""; }; - 574C0678D07A16C50FCD64C176AC5CE4 /* iOS */ = { - isa = PBXGroup; - children = ( - CF0AE397A3983666DD05CCFEBB495D2D /* Foundation.framework */, - ); - name = iOS; - sourceTree = ""; - }; - 681F621C78D074CF085045E15FAC5711 /* Support Files */ = { - isa = PBXGroup; - children = ( - 28B63EE513C824EC50135E751CCC17C3 /* Alamofire.modulemap */, - 600F89005E87894E991AE62B4469D6ED /* Alamofire.xcconfig */, - 8D11BAFC6A2AC82E2C3D730D6D28B59F /* Alamofire-dummy.m */, - 71FED29CF4CC7320DFFB20537E0CD5D5 /* Alamofire-prefix.pch */, - 10BE86DA3D5E1FC2E267FEB3E5C04B9C /* Alamofire-umbrella.h */, - 31B6CED63C84E0DFCF84E4F98778016A /* Info.plist */, - ); - name = "Support Files"; - path = "../Target Support Files/Alamofire"; - sourceTree = ""; - }; 77FF15A0C96E2572FA18708AB8AFBBF1 /* Targets Support Files */ = { isa = PBXGroup; children = ( @@ -442,19 +267,17 @@ children = ( 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, 4E103E339AE2E1444F45080D1F1AB2E0 /* Development Pods */, - 56FF7B91BE0AA544B1507169AE0EEE1B /* Frameworks */, - A172490FE49BE11F58859B76C380C3F7 /* Pods */, - 4BB455C525F38CDF1E7890B90AEB0B38 /* Products */, + 72A4F101D4D40D3C9EBA12D90663F5FA /* Frameworks */, + 96AD02A43B8F57AD204B714B82B37037 /* Pods */, + CCCDE2FA6E8947C9F141F9F07D1B7903 /* Products */, 77FF15A0C96E2572FA18708AB8AFBBF1 /* Targets Support Files */, ); sourceTree = ""; }; - A172490FE49BE11F58859B76C380C3F7 /* Pods */ = { + 96AD02A43B8F57AD204B714B82B37037 /* Pods */ = { isa = PBXGroup; children = ( - D07300C86467DEFAC49E323CFE174505 /* Alamofire */, - C65FA3383F60E35FB57891B025464EC5 /* AlamofireObjectMapper */, - A68A43BFB820B5614DA1225F047D9D31 /* ObjectMapper */, + 50DA52F9ED8316228A443D4AEB77D3E7 /* ObjectMapper */, ); name = Pods; sourceTree = ""; @@ -472,72 +295,23 @@ path = ../..; sourceTree = ""; }; - A68A43BFB820B5614DA1225F047D9D31 /* ObjectMapper */ = { + B698BE032F2E2D71DEAC2D89C403A556 /* iOS */ = { isa = PBXGroup; children = ( - EADDCC5720720B7AA5CFF0DC72F3B3F9 /* CustomDateFormatTransform.swift */, - 7CF6916D13AB7FD63E2FD155102F52DA /* DataTransform.swift */, - CDA993EC8C34829B83B7C527401EA1FF /* DateFormatterTransform.swift */, - C5D744537DA1AB15AD87CC74D96215DA /* DateTransform.swift */, - C323EFA758A4C140F3E416C76D022843 /* DictionaryTransform.swift */, - A42153AB600F91887F98BEDF4BB9A6BC /* EnumOperators.swift */, - E9091397C4729B3DCC1CE6856904B976 /* EnumTransform.swift */, - B339A9D352CAD3A021BE61898B6FB9F8 /* FromJSON.swift */, - 5CF68ACB68863BBEA9B6AE14A9519895 /* HexColorTransform.swift */, - A8DC92DCD95A2CE28232D27E7222C67C /* ImmutableMappable.swift */, - 06D4FD479A75D5161C787905EA1BA4D8 /* IntegerOperators.swift */, - 3B501F5330D236283AE79D286E8B15FB /* ISO8601DateTransform.swift */, - 9E827D71BF2F91A6742C882EC593324C /* Map.swift */, - B264E8DFD26C5EDB5EB2ECB92D655321 /* MapError.swift */, - 40E85602775D62B1F6118974F3964D37 /* Mappable.swift */, - 9732DBE4794B1B0C36BE01801B214034 /* Mapper.swift */, - DFBF46735426641B03E3B95AAB9BA5AA /* NSDecimalNumberTransform.swift */, - 84DBEE1354EB2B74C2490CEC876C5E44 /* Operators.swift */, - 21A82EE9C1C556B2E8BFBA8D068C8401 /* ToJSON.swift */, - 8B67422BB4CCE7DF4F1933D8446C5853 /* TransformOf.swift */, - 93B078301421E24725CBDAA939BEB8B3 /* TransformOperators.swift */, - 380095459E1F371BFB777E5C70EC68B4 /* TransformType.swift */, - C586828E4F4612149E740DFB653BF367 /* URLTransform.swift */, - 50CCEE653690BB4103016801EDC2E84B /* Support Files */, + BBF2A8127EDF29ABAA8C2FD230237309 /* Foundation.framework */, ); - name = ObjectMapper; - path = ObjectMapper; - sourceTree = ""; - }; - C65FA3383F60E35FB57891B025464EC5 /* AlamofireObjectMapper */ = { - isa = PBXGroup; - children = ( - F0DCA6A9FCC4B1D65F83A545AF02C612 /* AlamofireObjectMapper.swift */, - 1DA603A37B19C4DC95FF0B44107DD91B /* Support Files */, - ); - name = AlamofireObjectMapper; - path = AlamofireObjectMapper; + name = iOS; sourceTree = ""; }; - D07300C86467DEFAC49E323CFE174505 /* Alamofire */ = { + CCCDE2FA6E8947C9F141F9F07D1B7903 /* Products */ = { isa = PBXGroup; children = ( - E5518B44E6BD587E06A1F14E2B75A375 /* AFError.swift */, - 2B40A51A4BCA4B665DFFE8AF136844E7 /* Alamofire.swift */, - A4D5FAB7BB93E73B5DF85A67C0D1BDB9 /* DispatchQueue+Alamofire.swift */, - 926722659F3F03EDCD52039F064B6A09 /* MultipartFormData.swift */, - 6904F2951EDDDF8A86B40E2AAB93527C /* NetworkReachabilityManager.swift */, - 55D544C8A59616D0B71C49516901BC50 /* Notifications.swift */, - 0CAF45E56B5BAF03813F8B18E348C132 /* ParameterEncoding.swift */, - AF1783D7A34EB66A031BF558A3110D78 /* Request.swift */, - FBBF6A0A78F9806F84CB665EAE59592D /* Response.swift */, - 9B7CB4C3C0344D0BA34DC49DE9EFDDD8 /* ResponseSerialization.swift */, - CDE2FB1CB544D67C7A28A45356A6569E /* Result.swift */, - 5AF63DC915CBBB5A6A37C5693618BCE9 /* ServerTrustPolicy.swift */, - DE5E4BD5634AA3F7F9790B3737626EC4 /* SessionDelegate.swift */, - 134430AD6BCC02A45AD7C4DBAF50C6A0 /* SessionManager.swift */, - 80B2426289289A77E7E548DE8EBD7A6B /* TaskDelegate.swift */, - AA9FAC159DF216DEBC697BBA1C2F3A3F /* Timeline.swift */, - E5F45218D36108E9B8FC8CBC403F9567 /* Validation.swift */, - 681F621C78D074CF085045E15FAC5711 /* Support Files */, + 92CAA0BD4FF82C53F443C5226F9305AA /* APNSUtil.framework */, + 56E140897C7688E1E4A1BA84BFBA0658 /* ObjectMapper.framework */, + 725C6A197DCDE3F393B6572AC55AFC02 /* Pods_APNSUtil_Example.framework */, + E218CD0160F90E89470DAF4345708DE9 /* Pods_APNSUtil_Tests.framework */, ); - name = Alamofire; - path = Alamofire; + name = Products; sourceTree = ""; }; D18000A22969337D1A282A3CEC5AC6C5 /* Pods-APNSUtil_Tests */ = { @@ -558,22 +332,36 @@ path = "Target Support Files/Pods-APNSUtil_Tests"; sourceTree = ""; }; + F5D91224DF0AE46871245DA803B28C87 /* Support Files */ = { + isa = PBXGroup; + children = ( + DCD72DD56EA5A48818EA6E52DF8C3094 /* Info.plist */, + D7AC23C67BBBDA6981B12C6DE90F51BC /* ObjectMapper.modulemap */, + 21249291725D837BF8985189444FFEBA /* ObjectMapper.xcconfig */, + 93F8B9088984CF79F217D0181BD4E544 /* ObjectMapper-dummy.m */, + 3A5281418FEC9184304F69218872F5CA /* ObjectMapper-prefix.pch */, + 3E3C40B9A5500F757AE2B4B683445695 /* ObjectMapper-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/ObjectMapper"; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ - 7A65A8BC5FC8E2F6178E85C852BD5A45 /* Headers */ = { + 6A8887174504558B14F8198E27964B44 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 1674976E5691AC6C3F018C2E42683218 /* ObjectMapper-umbrella.h in Headers */, + 474BC828D1115EB6A350756458E0CD06 /* ObjectMapper-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; - 7DC72D11FA8668EB9BAD6F82FE7F75DF /* Headers */ = { + 8F1995B88DED991E40D157380E756AFC /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - E1FDB8EB49DCBA9C697BF5EE4103D28A /* AlamofireObjectMapper-umbrella.h in Headers */, + 0BB4EF281398F2725F72FDEE1810B637 /* Pods-APNSUtil_Example-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -585,142 +373,86 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - B2FD6FDA61A1B74817718BDBD7DA4ADF /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - A1450B7B54640746CE365C20F3D112EA /* Pods-APNSUtil_Example-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - C4F42B88C2048F59484918B3A38FCF28 /* Headers */ = { + F2E9A9DE370A1B402FE9B2EEEC8B6C8F /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - FA216D830A6BC63572A1BAA766FEF827 /* APNSUtil-umbrella.h in Headers */, + CAC46E189303160EBAB515A335C99D37 /* APNSUtil-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXHeadersBuildPhase section */ /* Begin PBXNativeTarget section */ - 2F5622F3B18DF497981AB58C6D1FC72F /* ObjectMapper */ = { + 427EEA9FEC39BBE1D05384CD8362177E /* APNSUtil */ = { isa = PBXNativeTarget; - buildConfigurationList = EFC80F30E9F21DF4B195270284D4B34F /* Build configuration list for PBXNativeTarget "ObjectMapper" */; - buildPhases = ( - 95DC01AC865B065A1EEF08BAB0CF8450 /* Sources */, - 8562E6EA2DA88FF69C44B2AF77E3EDDD /* Frameworks */, - 7A65A8BC5FC8E2F6178E85C852BD5A45 /* Headers */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = ObjectMapper; - productName = ObjectMapper; - productReference = 269527962433474AA1073F5062B51353 /* ObjectMapper.framework */; - productType = "com.apple.product-type.framework"; - }; - 88C692FC933A79315881ECCD747A0C81 /* Pods-APNSUtil_Tests */ = { - isa = PBXNativeTarget; - buildConfigurationList = 94D2707220C3774620BBEDE8AAD948C4 /* Build configuration list for PBXNativeTarget "Pods-APNSUtil_Tests" */; + buildConfigurationList = 546EEB2C80213DCACC3ECAC3B2221624 /* Build configuration list for PBXNativeTarget "APNSUtil" */; buildPhases = ( - 3B4D08CB7D444814F0003FCC792E49F4 /* Sources */, - 89B5CEB1E3BD7F8B3151620BD4184585 /* Frameworks */, - 9D781A50C1FA72575CEA845CBD4C5AFE /* Headers */, + 7C1A2F57B1F481A6E630EF34FCF58B5D /* Sources */, + 8E4EE43734851AD9DE7585F201948BD7 /* Frameworks */, + F2E9A9DE370A1B402FE9B2EEEC8B6C8F /* Headers */, ); buildRules = ( ); dependencies = ( + F4A1F1E8AAFAE6794E73E1040724EA3F /* PBXTargetDependency */, ); - name = "Pods-APNSUtil_Tests"; - productName = "Pods-APNSUtil_Tests"; - productReference = E93CEC2D065CADBD0FE331918C6BC5BA /* Pods_APNSUtil_Tests.framework */; + name = APNSUtil; + productName = APNSUtil; + productReference = 92CAA0BD4FF82C53F443C5226F9305AA /* APNSUtil.framework */; productType = "com.apple.product-type.framework"; }; - 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */ = { + 4A3627E04D7B66CB45B951C08F6E17E9 /* ObjectMapper */ = { isa = PBXNativeTarget; - buildConfigurationList = 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildConfigurationList = 73BC79ED6F797336AE4EFB58D2283593 /* Build configuration list for PBXNativeTarget "ObjectMapper" */; buildPhases = ( - 32B9974868188C4803318E36329C87FE /* Sources */, - 99195E4207764744AEC07ECCBCD550EB /* Frameworks */, - B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */, + 1C138796FC72E9D76D330DCB81CE191C /* Sources */, + E7E8A9AEF2259F03268A1E07C95020DD /* Frameworks */, + 6A8887174504558B14F8198E27964B44 /* Headers */, ); buildRules = ( ); dependencies = ( ); - name = Alamofire; - productName = Alamofire; - productReference = 57C7E258AA97278EEE78F48186CB69F5 /* Alamofire.framework */; + name = ObjectMapper; + productName = ObjectMapper; + productReference = 56E140897C7688E1E4A1BA84BFBA0658 /* ObjectMapper.framework */; productType = "com.apple.product-type.framework"; }; - 9502FB01641FBABB78522037E882757B /* AlamofireObjectMapper */ = { + 88C692FC933A79315881ECCD747A0C81 /* Pods-APNSUtil_Tests */ = { isa = PBXNativeTarget; - buildConfigurationList = C422E6D5D4D1CBA93636F30E9C630E16 /* Build configuration list for PBXNativeTarget "AlamofireObjectMapper" */; + buildConfigurationList = 94D2707220C3774620BBEDE8AAD948C4 /* Build configuration list for PBXNativeTarget "Pods-APNSUtil_Tests" */; buildPhases = ( - C929734BCFEB7DD628FE897257FF605D /* Sources */, - D55863AC11CD93D729F336D4A1837D9C /* Frameworks */, - 7DC72D11FA8668EB9BAD6F82FE7F75DF /* Headers */, + 3B4D08CB7D444814F0003FCC792E49F4 /* Sources */, + 89B5CEB1E3BD7F8B3151620BD4184585 /* Frameworks */, + 9D781A50C1FA72575CEA845CBD4C5AFE /* Headers */, ); buildRules = ( ); dependencies = ( - 98235C4BCA516C9911E228A502FE834A /* PBXTargetDependency */, - 60F02DEEA23633EE767FA0E4412FEA85 /* PBXTargetDependency */, ); - name = AlamofireObjectMapper; - productName = AlamofireObjectMapper; - productReference = 2F0C618433CA6E66F8AEC4563D4F8325 /* AlamofireObjectMapper.framework */; + name = "Pods-APNSUtil_Tests"; + productName = "Pods-APNSUtil_Tests"; + productReference = E218CD0160F90E89470DAF4345708DE9 /* Pods_APNSUtil_Tests.framework */; productType = "com.apple.product-type.framework"; }; - DCBEC2A7175A2056D92127E339AC9141 /* Pods-APNSUtil_Example */ = { + 91F32B3378812126AF7C2C5F509F611E /* Pods-APNSUtil_Example */ = { isa = PBXNativeTarget; - buildConfigurationList = 819E095D9F8C4B8E63EB01716ED9D74F /* Build configuration list for PBXNativeTarget "Pods-APNSUtil_Example" */; + buildConfigurationList = 8C0341C8C1F8AB1588FFEBA85B33B9BE /* Build configuration list for PBXNativeTarget "Pods-APNSUtil_Example" */; buildPhases = ( - 71F6BEAD8D96670BC5DDBDFCFEFD7F50 /* Sources */, - 07C885E3AA2C1BC94DF8373CE1BEA76F /* Frameworks */, - B2FD6FDA61A1B74817718BDBD7DA4ADF /* Headers */, + 658C1C23C16895806968145FF28D76CA /* Sources */, + 4F66BA02F4A9C5518DE9E927B32A203D /* Frameworks */, + 8F1995B88DED991E40D157380E756AFC /* Headers */, ); buildRules = ( ); dependencies = ( - BD33F893E6371E2E5E884B01FB7DB0B9 /* PBXTargetDependency */, - C09D9F46C0291D819144D65DB89DBDC4 /* PBXTargetDependency */, - 09704A4351413F508BDF68494312046C /* PBXTargetDependency */, - 8972C707E18F80B8543F6DEBE6B5DC8D /* PBXTargetDependency */, + CBA6D0B0D6D1304B2C041FAC76F5185B /* PBXTargetDependency */, + B6505FF31BE0AFCC7CA472617A7F9F5C /* PBXTargetDependency */, ); name = "Pods-APNSUtil_Example"; productName = "Pods-APNSUtil_Example"; - productReference = 7F484218DAD25EDC42322BDD4D8569AF /* Pods_APNSUtil_Example.framework */; - productType = "com.apple.product-type.framework"; - }; - F8E946FDC9A09CF02374E2E041304F76 /* APNSUtil */ = { - isa = PBXNativeTarget; - buildConfigurationList = 3A2604BD1C8294E34133099313A9C1CE /* Build configuration list for PBXNativeTarget "APNSUtil" */; - buildPhases = ( - F4FA18313EBF7AB7BD8407203DDD3CD7 /* Sources */, - 498A93B0A50757ED8922C35F4FF7C169 /* Frameworks */, - C4F42B88C2048F59484918B3A38FCF28 /* Headers */, - ); - buildRules = ( - ); - dependencies = ( - A2F2551AAAB0E3AB085FF9F6773B0FB5 /* PBXTargetDependency */, - 07500CD41631B970912DB8A3D4F9B45B /* PBXTargetDependency */, - FE3D7B3EAE06CC053122A2708B6A2EA9 /* PBXTargetDependency */, - ); - name = APNSUtil; - productName = APNSUtil; - productReference = 98C3594063A260A9D022874711741B22 /* APNSUtil.framework */; + productReference = 725C6A197DCDE3F393B6572AC55AFC02 /* Pods_APNSUtil_Example.framework */; productType = "com.apple.product-type.framework"; }; /* End PBXNativeTarget section */ @@ -740,43 +472,41 @@ en, ); mainGroup = 7DB346D0F39D3F0E887471402A8071AB; - productRefGroup = 4BB455C525F38CDF1E7890B90AEB0B38 /* Products */; + productRefGroup = CCCDE2FA6E8947C9F141F9F07D1B7903 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( - 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */, - 9502FB01641FBABB78522037E882757B /* AlamofireObjectMapper */, - F8E946FDC9A09CF02374E2E041304F76 /* APNSUtil */, - 2F5622F3B18DF497981AB58C6D1FC72F /* ObjectMapper */, - DCBEC2A7175A2056D92127E339AC9141 /* Pods-APNSUtil_Example */, + 427EEA9FEC39BBE1D05384CD8362177E /* APNSUtil */, + 4A3627E04D7B66CB45B951C08F6E17E9 /* ObjectMapper */, + 91F32B3378812126AF7C2C5F509F611E /* Pods-APNSUtil_Example */, 88C692FC933A79315881ECCD747A0C81 /* Pods-APNSUtil_Tests */, ); }; /* End PBXProject section */ /* Begin PBXSourcesBuildPhase section */ - 32B9974868188C4803318E36329C87FE /* Sources */ = { + 1C138796FC72E9D76D330DCB81CE191C /* 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 */, + B2460C7DE53E260EEB686A681FA3B50C /* CustomDateFormatTransform.swift in Sources */, + 8C33A9D0E248A6EA1A49B689CADFAA7E /* DataTransform.swift in Sources */, + FDCE519E6BD4BBCF2B77C916CC03D39A /* DateFormatterTransform.swift in Sources */, + FE8228473A48EAEEA8BCAC34BD19AA5C /* DateTransform.swift in Sources */, + BC8A6A56332550BA8971E030F3D7D8AF /* DictionaryTransform.swift in Sources */, + D21EDFD6C67B02EDF959000665672155 /* EnumTransform.swift in Sources */, + 69B06A09B453136BF0DA5CF0F254F2E7 /* FromJSON.swift in Sources */, + DED06D4BE1E80D6EFE672D8C9432C17F /* ISO8601DateTransform.swift in Sources */, + 482C235C5F03C7EEB6AC3B12245A3BBC /* Map.swift in Sources */, + 946855648446BD41EEB975BCC6E617D0 /* Mappable.swift in Sources */, + 5C8ADD24DF4288FFD90DB7647C1C3D62 /* Mapper.swift in Sources */, + AE9A572F49619A67EA839319EC4D3B52 /* NSDecimalNumberTransform.swift in Sources */, + 5BDAA3E3F32E24BBB3A49A154BD2F566 /* ObjectMapper-dummy.m in Sources */, + 1F2E918A8908D3D92E4182C36753837C /* Operators.swift in Sources */, + 9B5A0B1F3D35B736FBD6DE2D7AEE1AB5 /* ToJSON.swift in Sources */, + 145F6799296F51B9F7873400A3D8A139 /* TransformOf.swift in Sources */, + 93D135DD91E720E4B0E418749FD06299 /* TransformType.swift in Sources */, + A4ABDF7DA8DEFD6C5F902A37F57ACCC6 /* URLTransform.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -788,126 +518,50 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 71F6BEAD8D96670BC5DDBDFCFEFD7F50 /* Sources */ = { + 658C1C23C16895806968145FF28D76CA /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 2BC2003FED13A1D2AB91AA280641691B /* Pods-APNSUtil_Example-dummy.m in Sources */, + D7321A0F3650CDAC522A1CB5D94B2ACD /* Pods-APNSUtil_Example-dummy.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; - 95DC01AC865B065A1EEF08BAB0CF8450 /* Sources */ = { + 7C1A2F57B1F481A6E630EF34FCF58B5D /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - B73D4607C1DB58B06986EF7182EE9D08 /* CustomDateFormatTransform.swift in Sources */, - 765624085108240F1A2952486A60B66F /* DataTransform.swift in Sources */, - 028F7BF3F13D9D6CD093BE577808B1B1 /* DateFormatterTransform.swift in Sources */, - 6561EFAAAFE0E3FB560D8B87D50C0414 /* DateTransform.swift in Sources */, - B0438CAC2C1459719EC744B12F5C91DC /* DictionaryTransform.swift in Sources */, - 6140699B499701C95C16CA9E10A60B10 /* EnumOperators.swift in Sources */, - 35AFBFB34DA1956EF7FCB64BC50946D8 /* EnumTransform.swift in Sources */, - 375AD5B4037B367C74B348C0644C0509 /* FromJSON.swift in Sources */, - 54334A036232F3AD1BD3D9D682EA702D /* HexColorTransform.swift in Sources */, - 8491440E494CAAAE6DB2EA1D8D215903 /* ImmutableMappable.swift in Sources */, - 8F46A5E6F7671EA5EA201315E3A799E6 /* IntegerOperators.swift in Sources */, - 8022FE8243222780F58CDFD44A49F311 /* ISO8601DateTransform.swift in Sources */, - 375698920E797E91DBDB8A3249B56B0E /* Map.swift in Sources */, - 74D7B56EE91ACB42EB352CEF073CF4BB /* MapError.swift in Sources */, - 80FBD965D6160B82CF4B55FB3409C1FD /* Mappable.swift in Sources */, - A22566C71CFE2650BB542C4626477DAA /* Mapper.swift in Sources */, - CA1E06CB00C147AD88B8A721BF00F8D5 /* NSDecimalNumberTransform.swift in Sources */, - 4863B9B382D2BA7A07C414A91E1DD6B0 /* ObjectMapper-dummy.m in Sources */, - 05CB6B5B3A5024A0678959CCBFC2A0F7 /* Operators.swift in Sources */, - 5BEC65F1E64F4BC3B0AD838E60E1C4A9 /* ToJSON.swift in Sources */, - 9C655404E5C7D42907234439EF895BD5 /* TransformOf.swift in Sources */, - 7BE81D28BE233A47AC5BE1B3FA26FDB5 /* TransformOperators.swift in Sources */, - E2B172D4B630FCBD7D61A3FA14892658 /* TransformType.swift in Sources */, - CA2F35983F4B2670A0A195384FF21BD0 /* URLTransform.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - C929734BCFEB7DD628FE897257FF605D /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 260112ED9612CF82C0D3B42913FE73BC /* AlamofireObjectMapper-dummy.m in Sources */, - 3EB9DC3783A4296C8BAAB07AC36C05F3 /* AlamofireObjectMapper.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - F4FA18313EBF7AB7BD8407203DDD3CD7 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 5D0812EFA9986DE3E6336326AF267904 /* APNSInstance.swift in Sources */, - C133DC6459457DE302ECD5B038DC2461 /* APNSManager.swift in Sources */, - 12F7D4AA220E04394209750788551924 /* APNSUtil-dummy.m in Sources */, - 37F2DCED1A444D3923D9D0A6380AB050 /* NSObject+Codable.swift in Sources */, + 44293254A39E424D2CB406C290761A8B /* APNSInstance.swift in Sources */, + 19A895C2151A5A4B52BCD5D5E9797B6F /* APNSManager.swift in Sources */, + BDCD0842F48C5A23486CD1B0E4376D0B /* APNSUtil-dummy.m in Sources */, + C1A7AC15996C3A3B90B73914563CEEB9 /* NSObject+Codable.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ - 07500CD41631B970912DB8A3D4F9B45B /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = AlamofireObjectMapper; - target = 9502FB01641FBABB78522037E882757B /* AlamofireObjectMapper */; - targetProxy = 3CC807134F88B93086B46E13FDC52A78 /* PBXContainerItemProxy */; - }; - 09704A4351413F508BDF68494312046C /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = AlamofireObjectMapper; - target = 9502FB01641FBABB78522037E882757B /* AlamofireObjectMapper */; - targetProxy = 669D6265FFC323BAE23E8ADA58242BBE /* PBXContainerItemProxy */; - }; - 60F02DEEA23633EE767FA0E4412FEA85 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = ObjectMapper; - target = 2F5622F3B18DF497981AB58C6D1FC72F /* ObjectMapper */; - targetProxy = C2A743750D8435124390DA2CA737665B /* PBXContainerItemProxy */; - }; - 8972C707E18F80B8543F6DEBE6B5DC8D /* PBXTargetDependency */ = { + B6505FF31BE0AFCC7CA472617A7F9F5C /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = ObjectMapper; - target = 2F5622F3B18DF497981AB58C6D1FC72F /* ObjectMapper */; - targetProxy = 9E872C79DA3A91657A381E45E59E68B7 /* PBXContainerItemProxy */; + target = 4A3627E04D7B66CB45B951C08F6E17E9 /* ObjectMapper */; + targetProxy = 3A2935EFF85DBF5E644B48087878968C /* PBXContainerItemProxy */; }; - 98235C4BCA516C9911E228A502FE834A /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = Alamofire; - target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; - targetProxy = A04F064E4A878D0A36386C26C1925C4F /* PBXContainerItemProxy */; - }; - A2F2551AAAB0E3AB085FF9F6773B0FB5 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = Alamofire; - target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; - targetProxy = 3303BAB00ED7E2F11A457038A6944E9E /* PBXContainerItemProxy */; - }; - BD33F893E6371E2E5E884B01FB7DB0B9 /* PBXTargetDependency */ = { + CBA6D0B0D6D1304B2C041FAC76F5185B /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = APNSUtil; - target = F8E946FDC9A09CF02374E2E041304F76 /* APNSUtil */; - targetProxy = 6CFD44F05E8B4C61BB6CB679EE31B7A8 /* PBXContainerItemProxy */; + target = 427EEA9FEC39BBE1D05384CD8362177E /* APNSUtil */; + targetProxy = 097F39686B79EA39C000E7A84947C94D /* PBXContainerItemProxy */; }; - C09D9F46C0291D819144D65DB89DBDC4 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = Alamofire; - target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; - targetProxy = AE9EB015A659C7E42FA0501262FD8E20 /* PBXContainerItemProxy */; - }; - FE3D7B3EAE06CC053122A2708B6A2EA9 /* PBXTargetDependency */ = { + F4A1F1E8AAFAE6794E73E1040724EA3F /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = ObjectMapper; - target = 2F5622F3B18DF497981AB58C6D1FC72F /* ObjectMapper */; - targetProxy = 35CD6496B316B6C70A67C43CB60ADD7C /* PBXContainerItemProxy */; + target = 4A3627E04D7B66CB45B951C08F6E17E9 /* ObjectMapper */; + targetProxy = 4D3BB247F628845F838C9303B6E3DB9A /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ - 26D6B838F641140E489C97668911ED19 /* Release */ = { + 1372A2CC8F47148343FD315140A6BEE8 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = FC307F4C23F997DA113D80015F941DBD /* Pods-APNSUtil_Example.release.xcconfig */; buildSettings = { @@ -922,7 +576,7 @@ DYLIB_INSTALL_NAME_BASE = "@rpath"; INFOPLIST_FILE = "Target Support Files/Pods-APNSUtil_Example/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.3; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MACH_O_TYPE = staticlib; MODULEMAP_FILE = "Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example.modulemap"; @@ -941,9 +595,9 @@ }; name = Release; }; - 3246BCD2741569958C394047C9D578AA /* Release */ = { + 24804B90D7775CCE25B22321BFAE266F /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 3D9F3EB6D49ECFE9A4BC670C59647CBF /* AlamofireObjectMapper.xcconfig */; + baseConfigurationReference = 21249291725D837BF8985189444FFEBA /* ObjectMapper.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; @@ -954,18 +608,49 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/AlamofireObjectMapper/AlamofireObjectMapper-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/AlamofireObjectMapper/Info.plist"; + GCC_PREFIX_HEADER = "Target Support Files/ObjectMapper/ObjectMapper-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/ObjectMapper/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/AlamofireObjectMapper/AlamofireObjectMapper.modulemap"; - PRODUCT_NAME = AlamofireObjectMapper; + MODULEMAP_FILE = "Target Support Files/ObjectMapper/ObjectMapper.modulemap"; + PRODUCT_NAME = ObjectMapper; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 24A56D7C972D40FFB907E0F145607D8A /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 21249291725D837BF8985189444FFEBA /* ObjectMapper.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/ObjectMapper/ObjectMapper-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/ObjectMapper/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/ObjectMapper/ObjectMapper.modulemap"; + PRODUCT_NAME = ObjectMapper; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; @@ -973,9 +658,9 @@ }; name = Release; }; - 32E423DAE323652F4EEA3FC140A4338C /* Debug */ = { + 559307B8AB4CCDD474746ED406FEA0BF /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 59373EB39F10851BE99AC26F256DB1E8 /* Pods-APNSUtil_Tests.debug.xcconfig */; + baseConfigurationReference = 4CB4A28D3BE28D53BF26FFAA7E02BDCE /* Pods-APNSUtil_Example.debug.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; @@ -986,86 +671,28 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-APNSUtil_Tests/Info.plist"; + INFOPLIST_FILE = "Target Support Files/Pods-APNSUtil_Example/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.3; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-APNSUtil_Tests/Pods-APNSUtil_Tests.modulemap"; + MODULEMAP_FILE = "Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example.modulemap"; OTHER_LDFLAGS = ""; OTHER_LIBTOOLFLAGS = ""; PODS_ROOT = "$(SRCROOT)"; PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = Pods_APNSUtil_Tests; + PRODUCT_NAME = Pods_APNSUtil_Example; 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; }; - 33DA7F43A1D2FA3C74A8C8FC246E1FA6 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - CODE_SIGNING_REQUIRED = NO; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "POD_CONFIGURATION_DEBUG=1", - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.3; - MTL_ENABLE_DEBUG_INFO = YES; - ONLY_ACTIVE_ARCH = YES; - PRODUCT_NAME = "$(TARGET_NAME)"; - PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; - STRIP_INSTALLED_PRODUCT = NO; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SYMROOT = "${SRCROOT}/../build"; - }; - name = Debug; - }; - 731DC216E1A58545B559F6E0A2418060 /* Release */ = { + 6F9224530522DD3C735EC96CF142642E /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; @@ -1111,7 +738,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.3; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; @@ -1120,40 +747,7 @@ }; name = Release; }; - 82D934E7A73D06160255E51FF0E8798E /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 3971FD2397168A24DC2BE8DC1CF11C06 /* Pods-APNSUtil_Tests.release.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"; - INFOPLIST_FILE = "Target Support Files/Pods-APNSUtil_Tests/Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.3; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-APNSUtil_Tests/Pods-APNSUtil_Tests.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = Pods_APNSUtil_Tests; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - 8B92EC3955C3F8B1567FA3F74A9F5202 /* Debug */ = { + 81718501A2D15D4D8FD99948DDABC235 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 09AE27EA9A97A5B89E53D965E992C566 /* APNSUtil.xcconfig */; buildSettings = { @@ -1169,77 +763,15 @@ GCC_PREFIX_HEADER = "Target Support Files/APNSUtil/APNSUtil-prefix.pch"; INFOPLIST_FILE = "Target Support Files/APNSUtil/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/APNSUtil/APNSUtil.modulemap"; PRODUCT_NAME = APNSUtil; SDKROOT = iphoneos; SKIP_INSTALL = YES; 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 = ""; - }; - name = Debug; - }; - B0F5F1530D3F4E518BE2B1A52F98487A /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 600F89005E87894E991AE62B4469D6ED /* 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_NAME = Alamofire; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - 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 = ""; - }; - name = Debug; - }; - B8CA02655A4B738D82484691EE8CA58F /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 600F89005E87894E991AE62B4469D6ED /* 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_NAME = Alamofire; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; @@ -1247,9 +779,9 @@ }; name = Release; }; - BA8BEB97818343477560ECA301A408B1 /* Debug */ = { + A3C56B9052A7C21616CD03199AA251EF /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 4CB4A28D3BE28D53BF26FFAA7E02BDCE /* Pods-APNSUtil_Example.debug.xcconfig */; + baseConfigurationReference = 59373EB39F10851BE99AC26F256DB1E8 /* Pods-APNSUtil_Tests.debug.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; @@ -1260,30 +792,28 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-APNSUtil_Example/Info.plist"; + INFOPLIST_FILE = "Target Support Files/Pods-APNSUtil_Tests/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.3; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example.modulemap"; + MODULEMAP_FILE = "Target Support Files/Pods-APNSUtil_Tests/Pods-APNSUtil_Tests.modulemap"; OTHER_LDFLAGS = ""; OTHER_LIBTOOLFLAGS = ""; PODS_ROOT = "$(SRCROOT)"; PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = Pods_APNSUtil_Example; + PRODUCT_NAME = Pods_APNSUtil_Tests; 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; }; - BB6F1F3E008EF58CA3C56D670C1409E6 /* Debug */ = { + B02C73AE5CD14A85966A8D59DF129E93 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 3D9F3EB6D49ECFE9A4BC670C59647CBF /* AlamofireObjectMapper.xcconfig */; + baseConfigurationReference = 3971FD2397168A24DC2BE8DC1CF11C06 /* Pods-APNSUtil_Tests.release.xcconfig */; buildSettings = { CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; @@ -1294,57 +824,87 @@ DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/AlamofireObjectMapper/AlamofireObjectMapper-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/AlamofireObjectMapper/Info.plist"; + INFOPLIST_FILE = "Target Support Files/Pods-APNSUtil_Tests/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/AlamofireObjectMapper/AlamofireObjectMapper.modulemap"; - PRODUCT_NAME = AlamofireObjectMapper; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-APNSUtil_Tests/Pods-APNSUtil_Tests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_APNSUtil_Tests; 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 = Debug; + name = Release; }; - DD95352EF642D4818F151586C11EDF79 /* Release */ = { + B57951D085A1B98A97F8A1062A5E5C5B /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 2324CD4089FDF77B27D7CE76606D529D /* ObjectMapper.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/ObjectMapper/ObjectMapper-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/ObjectMapper/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/ObjectMapper/ObjectMapper.modulemap"; - PRODUCT_NAME = ObjectMapper; - 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 = ""; + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_REQUIRED = NO; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SYMROOT = "${SRCROOT}/../build"; }; - name = Release; + name = Debug; }; - E95B01DB053B2429F1FBE364F9E8BF4C /* Release */ = { + CF7CE5E1763CB75A53FA25E866520B1A /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 09AE27EA9A97A5B89E53D965E992C566 /* APNSUtil.xcconfig */; buildSettings = { @@ -1360,47 +920,15 @@ GCC_PREFIX_HEADER = "Target Support Files/APNSUtil/APNSUtil-prefix.pch"; INFOPLIST_FILE = "Target Support Files/APNSUtil/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/APNSUtil/APNSUtil.modulemap"; PRODUCT_NAME = APNSUtil; 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; - }; - EF83D8C6264740A99E623F75C1CCB1E7 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 2324CD4089FDF77B27D7CE76606D529D /* ObjectMapper.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/ObjectMapper/ObjectMapper-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/ObjectMapper/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/ObjectMapper/ObjectMapper.modulemap"; - PRODUCT_NAME = ObjectMapper; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; @@ -1413,35 +941,35 @@ 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { isa = XCConfigurationList; buildConfigurations = ( - 33DA7F43A1D2FA3C74A8C8FC246E1FA6 /* Debug */, - 731DC216E1A58545B559F6E0A2418060 /* Release */, + B57951D085A1B98A97F8A1062A5E5C5B /* Debug */, + 6F9224530522DD3C735EC96CF142642E /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 3A2604BD1C8294E34133099313A9C1CE /* Build configuration list for PBXNativeTarget "APNSUtil" */ = { + 546EEB2C80213DCACC3ECAC3B2221624 /* Build configuration list for PBXNativeTarget "APNSUtil" */ = { isa = XCConfigurationList; buildConfigurations = ( - 8B92EC3955C3F8B1567FA3F74A9F5202 /* Debug */, - E95B01DB053B2429F1FBE364F9E8BF4C /* Release */, + CF7CE5E1763CB75A53FA25E866520B1A /* Debug */, + 81718501A2D15D4D8FD99948DDABC235 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + 73BC79ED6F797336AE4EFB58D2283593 /* Build configuration list for PBXNativeTarget "ObjectMapper" */ = { isa = XCConfigurationList; buildConfigurations = ( - B0F5F1530D3F4E518BE2B1A52F98487A /* Debug */, - B8CA02655A4B738D82484691EE8CA58F /* Release */, + 24804B90D7775CCE25B22321BFAE266F /* Debug */, + 24A56D7C972D40FFB907E0F145607D8A /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 819E095D9F8C4B8E63EB01716ED9D74F /* Build configuration list for PBXNativeTarget "Pods-APNSUtil_Example" */ = { + 8C0341C8C1F8AB1588FFEBA85B33B9BE /* Build configuration list for PBXNativeTarget "Pods-APNSUtil_Example" */ = { isa = XCConfigurationList; buildConfigurations = ( - BA8BEB97818343477560ECA301A408B1 /* Debug */, - 26D6B838F641140E489C97668911ED19 /* Release */, + 559307B8AB4CCDD474746ED406FEA0BF /* Debug */, + 1372A2CC8F47148343FD315140A6BEE8 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -1449,26 +977,8 @@ 94D2707220C3774620BBEDE8AAD948C4 /* Build configuration list for PBXNativeTarget "Pods-APNSUtil_Tests" */ = { isa = XCConfigurationList; buildConfigurations = ( - 32E423DAE323652F4EEA3FC140A4338C /* Debug */, - 82D934E7A73D06160255E51FF0E8798E /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - C422E6D5D4D1CBA93636F30E9C630E16 /* Build configuration list for PBXNativeTarget "AlamofireObjectMapper" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - BB6F1F3E008EF58CA3C56D670C1409E6 /* Debug */, - 3246BCD2741569958C394047C9D578AA /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - EFC80F30E9F21DF4B195270284D4B34F /* Build configuration list for PBXNativeTarget "ObjectMapper" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - EF83D8C6264740A99E623F75C1CCB1E7 /* Debug */, - DD95352EF642D4818F151586C11EDF79 /* Release */, + A3C56B9052A7C21616CD03199AA251EF /* Debug */, + B02C73AE5CD14A85966A8D59DF129E93 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; diff --git a/Example/Pods/Target Support Files/APNSUtil/APNSUtil.xcconfig b/Example/Pods/Target Support Files/APNSUtil/APNSUtil.xcconfig index 6949155..f5741ce 100644 --- a/Example/Pods/Target Support Files/APNSUtil/APNSUtil.xcconfig +++ b/Example/Pods/Target Support Files/APNSUtil/APNSUtil.xcconfig @@ -1,5 +1,5 @@ CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/APNSUtil -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/AlamofireObjectMapper" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" diff --git a/Example/Pods/Target Support Files/Alamofire/Alamofire-dummy.m b/Example/Pods/Target Support Files/Alamofire/Alamofire-dummy.m deleted file mode 100644 index a6c4594..0000000 --- a/Example/Pods/Target Support Files/Alamofire/Alamofire-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_Alamofire : NSObject -@end -@implementation PodsDummy_Alamofire -@end diff --git a/Example/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch b/Example/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch deleted file mode 100644 index beb2a24..0000000 --- a/Example/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch +++ /dev/null @@ -1,12 +0,0 @@ -#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/Example/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h b/Example/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h deleted file mode 100644 index 00014e3..0000000 --- a/Example/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#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/Example/Pods/Target Support Files/Alamofire/Alamofire.modulemap b/Example/Pods/Target Support Files/Alamofire/Alamofire.modulemap deleted file mode 100644 index d1f125f..0000000 --- a/Example/Pods/Target Support Files/Alamofire/Alamofire.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module Alamofire { - umbrella header "Alamofire-umbrella.h" - - export * - module * { export * } -} diff --git a/Example/Pods/Target Support Files/Alamofire/Alamofire.xcconfig b/Example/Pods/Target Support Files/Alamofire/Alamofire.xcconfig deleted file mode 100644 index 881c8ca..0000000 --- a/Example/Pods/Target Support Files/Alamofire/Alamofire.xcconfig +++ /dev/null @@ -1,10 +0,0 @@ -CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Alamofire -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" -OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_ROOT = ${SRCROOT} -PODS_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire -PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} -SKIP_INSTALL = YES diff --git a/Example/Pods/Target Support Files/Alamofire/Info.plist b/Example/Pods/Target Support Files/Alamofire/Info.plist deleted file mode 100644 index 3d018f8..0000000 --- a/Example/Pods/Target Support Files/Alamofire/Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - ${PRODUCT_BUNDLE_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 4.6.0 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - - - diff --git a/Example/Pods/Target Support Files/AlamofireObjectMapper/AlamofireObjectMapper-dummy.m b/Example/Pods/Target Support Files/AlamofireObjectMapper/AlamofireObjectMapper-dummy.m deleted file mode 100644 index 0a65788..0000000 --- a/Example/Pods/Target Support Files/AlamofireObjectMapper/AlamofireObjectMapper-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_AlamofireObjectMapper : NSObject -@end -@implementation PodsDummy_AlamofireObjectMapper -@end diff --git a/Example/Pods/Target Support Files/AlamofireObjectMapper/AlamofireObjectMapper-prefix.pch b/Example/Pods/Target Support Files/AlamofireObjectMapper/AlamofireObjectMapper-prefix.pch deleted file mode 100644 index beb2a24..0000000 --- a/Example/Pods/Target Support Files/AlamofireObjectMapper/AlamofireObjectMapper-prefix.pch +++ /dev/null @@ -1,12 +0,0 @@ -#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/Example/Pods/Target Support Files/AlamofireObjectMapper/AlamofireObjectMapper-umbrella.h b/Example/Pods/Target Support Files/AlamofireObjectMapper/AlamofireObjectMapper-umbrella.h deleted file mode 100644 index 39f5a35..0000000 --- a/Example/Pods/Target Support Files/AlamofireObjectMapper/AlamofireObjectMapper-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#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 AlamofireObjectMapperVersionNumber; -FOUNDATION_EXPORT const unsigned char AlamofireObjectMapperVersionString[]; - diff --git a/Example/Pods/Target Support Files/AlamofireObjectMapper/AlamofireObjectMapper.modulemap b/Example/Pods/Target Support Files/AlamofireObjectMapper/AlamofireObjectMapper.modulemap deleted file mode 100644 index b4ff79f..0000000 --- a/Example/Pods/Target Support Files/AlamofireObjectMapper/AlamofireObjectMapper.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module AlamofireObjectMapper { - umbrella header "AlamofireObjectMapper-umbrella.h" - - export * - module * { export * } -} diff --git a/Example/Pods/Target Support Files/AlamofireObjectMapper/AlamofireObjectMapper.xcconfig b/Example/Pods/Target Support Files/AlamofireObjectMapper/AlamofireObjectMapper.xcconfig deleted file mode 100644 index 6395e3f..0000000 --- a/Example/Pods/Target Support Files/AlamofireObjectMapper/AlamofireObjectMapper.xcconfig +++ /dev/null @@ -1,11 +0,0 @@ -CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/AlamofireObjectMapper -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" -OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_ROOT = ${SRCROOT} -PODS_TARGET_SRCROOT = ${PODS_ROOT}/AlamofireObjectMapper -PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} -SKIP_INSTALL = YES diff --git a/Example/Pods/Target Support Files/AlamofireObjectMapper/Info.plist b/Example/Pods/Target Support Files/AlamofireObjectMapper/Info.plist deleted file mode 100644 index e2771ff..0000000 --- a/Example/Pods/Target Support Files/AlamofireObjectMapper/Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - ${PRODUCT_BUNDLE_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 5.0.0 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - - - diff --git a/Example/Pods/Target Support Files/ObjectMapper/Info.plist b/Example/Pods/Target Support Files/ObjectMapper/Info.plist index 90db36a..0a12077 100644 --- a/Example/Pods/Target Support Files/ObjectMapper/Info.plist +++ b/Example/Pods/Target Support Files/ObjectMapper/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 3.1.0 + 2.0.0 CFBundleSignature ???? CFBundleVersion diff --git a/Example/Pods/Target Support Files/ObjectMapper/ObjectMapper.xcconfig b/Example/Pods/Target Support Files/ObjectMapper/ObjectMapper.xcconfig index 565bced..66d1729 100644 --- a/Example/Pods/Target Support Files/ObjectMapper/ObjectMapper.xcconfig +++ b/Example/Pods/Target Support Files/ObjectMapper/ObjectMapper.xcconfig @@ -8,4 +8,3 @@ PODS_ROOT = ${SRCROOT} PODS_TARGET_SRCROOT = ${PODS_ROOT}/ObjectMapper PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} SKIP_INSTALL = YES -SWIFT_VERSION = 4.0 diff --git a/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example-acknowledgements.markdown b/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example-acknowledgements.markdown index 9576725..6c5d9cc 100644 --- a/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example-acknowledgements.markdown +++ b/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example-acknowledgements.markdown @@ -26,55 +26,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -## Alamofire - -Copyright (c) 2014-2017 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. - - -## AlamofireObjectMapper - -The MIT License (MIT) - -Copyright (c) 2015 Tristan Himmelman - -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. - - - ## ObjectMapper The MIT License (MIT) diff --git a/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example-acknowledgements.plist b/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example-acknowledgements.plist index 98dc0f4..7f7d2dd 100644 --- a/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example-acknowledgements.plist +++ b/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example-acknowledgements.plist @@ -43,67 +43,6 @@ SOFTWARE. Type PSGroupSpecifier - - FooterText - Copyright (c) 2014-2017 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 - The MIT License (MIT) - -Copyright (c) 2015 Tristan Himmelman - -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 - AlamofireObjectMapper - Type - PSGroupSpecifier - FooterText The MIT License (MIT) diff --git a/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example-frameworks.sh b/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example-frameworks.sh index 4ef79ce..cb15728 100755 --- a/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example-frameworks.sh +++ b/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example-frameworks.sh @@ -135,14 +135,10 @@ strip_invalid_archs() { if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/APNSUtil/APNSUtil.framework" - install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" - install_framework "${BUILT_PRODUCTS_DIR}/AlamofireObjectMapper/AlamofireObjectMapper.framework" install_framework "${BUILT_PRODUCTS_DIR}/ObjectMapper/ObjectMapper.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/APNSUtil/APNSUtil.framework" - install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" - install_framework "${BUILT_PRODUCTS_DIR}/AlamofireObjectMapper/AlamofireObjectMapper.framework" install_framework "${BUILT_PRODUCTS_DIR}/ObjectMapper/ObjectMapper.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then diff --git a/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example.debug.xcconfig b/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example.debug.xcconfig index 179fdb5..97dc3b7 100644 --- a/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example.debug.xcconfig +++ b/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example.debug.xcconfig @@ -1,9 +1,9 @@ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/APNSUtil" "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/AlamofireObjectMapper" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/APNSUtil" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" 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}/APNSUtil/APNSUtil.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/AlamofireObjectMapper/AlamofireObjectMapper.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.framework/Headers" -OTHER_LDFLAGS = $(inherited) -framework "APNSUtil" -framework "Alamofire" -framework "AlamofireObjectMapper" -framework "ObjectMapper" +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/APNSUtil/APNSUtil.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "APNSUtil" -framework "ObjectMapper" 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/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example.release.xcconfig b/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example.release.xcconfig index 179fdb5..97dc3b7 100644 --- a/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example.release.xcconfig +++ b/Example/Pods/Target Support Files/Pods-APNSUtil_Example/Pods-APNSUtil_Example.release.xcconfig @@ -1,9 +1,9 @@ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/APNSUtil" "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/AlamofireObjectMapper" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/APNSUtil" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" 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}/APNSUtil/APNSUtil.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/AlamofireObjectMapper/AlamofireObjectMapper.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.framework/Headers" -OTHER_LDFLAGS = $(inherited) -framework "APNSUtil" -framework "Alamofire" -framework "AlamofireObjectMapper" -framework "ObjectMapper" +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/APNSUtil/APNSUtil.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "APNSUtil" -framework "ObjectMapper" 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/Example/Pods/Target Support Files/Pods-APNSUtil_Tests/Pods-APNSUtil_Tests.debug.xcconfig b/Example/Pods/Target Support Files/Pods-APNSUtil_Tests/Pods-APNSUtil_Tests.debug.xcconfig index e5fe725..6f255a7 100644 --- a/Example/Pods/Target Support Files/Pods-APNSUtil_Tests/Pods-APNSUtil_Tests.debug.xcconfig +++ b/Example/Pods/Target Support Files/Pods-APNSUtil_Tests/Pods-APNSUtil_Tests.debug.xcconfig @@ -1,7 +1,7 @@ -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/APNSUtil" "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/AlamofireObjectMapper" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/APNSUtil" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" 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}/APNSUtil/APNSUtil.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/AlamofireObjectMapper/AlamofireObjectMapper.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.framework/Headers" +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/APNSUtil/APNSUtil.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.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/Example/Pods/Target Support Files/Pods-APNSUtil_Tests/Pods-APNSUtil_Tests.release.xcconfig b/Example/Pods/Target Support Files/Pods-APNSUtil_Tests/Pods-APNSUtil_Tests.release.xcconfig index e5fe725..6f255a7 100644 --- a/Example/Pods/Target Support Files/Pods-APNSUtil_Tests/Pods-APNSUtil_Tests.release.xcconfig +++ b/Example/Pods/Target Support Files/Pods-APNSUtil_Tests/Pods-APNSUtil_Tests.release.xcconfig @@ -1,7 +1,7 @@ -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/APNSUtil" "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/AlamofireObjectMapper" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/APNSUtil" "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper" 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}/APNSUtil/APNSUtil.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/AlamofireObjectMapper/AlamofireObjectMapper.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.framework/Headers" +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/APNSUtil/APNSUtil.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/ObjectMapper/ObjectMapper.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/README.md b/README.md index d343b17..3c2fabd 100644 --- a/README.md +++ b/README.md @@ -66,10 +66,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { APNSManager.shared.registerDeviceToken(deviceToken) - // TODO: write code to update devicetoken with your api server + // TODO: write code to update device token with your api server } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { - // TODO: write code to update devicetoken with your api server + // TODO: write code to update device token with your api server } // MARK: - Push Notification for iOS 9 @@ -78,18 +78,18 @@ class AppDelegate: UIResponder, UIApplicationDelegate { application.registerForRemoteNotifications() } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) { - APNSManager.shared.received(APNSPayload.self, userInfo: userInfo, isInactive: application.applicationState == .inactive) + APNSManager.shared.didReceive(userInfo: userInfo, as: APNSPayload.self, isInactive: application.applicationState == .inactive) } // MARK: - Push Notification for iOS 10 or higher @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { - APNSManager.shared.received(APNSPayload.self, userInfo: notification.request.content.userInfo, isInactive: false) + APNSManager.shared.didReceive(userInfo: notification.request.content.userInfo, as: APNSPayload.self, isInactive: false) } @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { - APNSManager.shared.received(APNSPayload.self, userInfo: response.notification.request.content.userInfo, isInactive: true) + APNSManager.shared.didReceive(userInfo: response.notification.request.content.userInfo, as: APNSPayload.self, isInactive: true) } } ```