├── .gitignore ├── SwiftyCryptoDisco ├── Supporting Files │ ├── Assets.xcassets │ │ ├── Contents.json │ │ ├── arrow.imageset │ │ │ ├── arrow.png │ │ │ ├── arrow@2x.png │ │ │ ├── arrow@3x.png │ │ │ └── Contents.json │ │ ├── AppIcon.appiconset │ │ │ ├── Icon-1024.png │ │ │ ├── Icon-120.png │ │ │ ├── Icon-121.png │ │ │ ├── Icon-152.png │ │ │ ├── Icon-167.png │ │ │ ├── Icon-180.png │ │ │ ├── Icon-20.png │ │ │ ├── Icon-29.png │ │ │ ├── Icon-40.png │ │ │ ├── Icon-41.png │ │ │ ├── Icon-42.png │ │ │ ├── Icon-58.png │ │ │ ├── Icon-59.png │ │ │ ├── Icon-60.png │ │ │ ├── Icon-76.png │ │ │ ├── Icon-80.png │ │ │ ├── Icon-81.png │ │ │ ├── Icon-87.png │ │ │ └── Contents.json │ │ ├── settings.imageset │ │ │ ├── settings.png │ │ │ ├── settings@2x.png │ │ │ ├── settings@3x.png │ │ │ └── Contents.json │ │ ├── DarkCellBG.colorset │ │ │ └── Contents.json │ │ ├── flatBlue.colorset │ │ │ └── Contents.json │ │ ├── flatRed.colorset │ │ │ └── Contents.json │ │ └── fluoGreen.colorset │ │ │ └── Contents.json │ ├── ConnectionManager.swift │ ├── GlobalsEnumsExtensions.swift │ └── Base.lproj │ │ └── LaunchScreen.storyboard ├── Model │ ├── MarketExchange.swift │ ├── OHLCV.swift │ └── Currency.swift ├── Views │ ├── SliderTableViewCell.swift │ ├── OHLCVTableViewCell.swift │ ├── CoinTableViewCell.swift │ └── SliderTableViewCell.xib ├── Info.plist ├── Client │ ├── CurrencyDataFetcher.swift │ └── MarketDataFetcher.swift ├── AppDelegate.swift └── View Controllers │ ├── ContainerViewController.swift │ ├── AddCoinTableViewController.swift │ ├── SettingsTableViewController.swift │ ├── CurrencyTableViewController.swift │ └── CoinDataViewController.swift ├── Pods ├── Target Support Files │ ├── Alamofire │ │ ├── Alamofire.modulemap │ │ ├── Alamofire-dummy.m │ │ ├── Alamofire-prefix.pch │ │ ├── Alamofire-umbrella.h │ │ ├── Alamofire.xcconfig │ │ └── Info.plist │ ├── SwiftyJSON │ │ ├── SwiftyJSON.modulemap │ │ ├── SwiftyJSON-dummy.m │ │ ├── SwiftyJSON-prefix.pch │ │ ├── SwiftyJSON-umbrella.h │ │ ├── SwiftyJSON.xcconfig │ │ └── Info.plist │ └── Pods-SwiftyCryptoDisco │ │ ├── Pods-SwiftyCryptoDisco.modulemap │ │ ├── Pods-SwiftyCryptoDisco-dummy.m │ │ ├── Pods-SwiftyCryptoDisco-umbrella.h │ │ ├── Pods-SwiftyCryptoDisco.debug.xcconfig │ │ ├── Pods-SwiftyCryptoDisco.release.xcconfig │ │ ├── Info.plist │ │ ├── Pods-SwiftyCryptoDisco-acknowledgements.markdown │ │ ├── Pods-SwiftyCryptoDisco-acknowledgements.plist │ │ ├── Pods-SwiftyCryptoDisco-frameworks.sh │ │ └── Pods-SwiftyCryptoDisco-resources.sh ├── Manifest.lock ├── Pods.xcodeproj │ └── xcuserdata │ │ └── matschmid.xcuserdatad │ │ └── xcschemes │ │ ├── xcschememanagement.plist │ │ ├── Alamofire.xcscheme │ │ ├── SwiftyJSON.xcscheme │ │ └── Pods-SwiftyCryptoDisco.xcscheme ├── SwiftyJSON │ ├── LICENSE │ └── README.md └── Alamofire │ ├── LICENSE │ └── Source │ ├── DispatchQueue+Alamofire.swift │ ├── Notifications.swift │ ├── Timeline.swift │ ├── NetworkReachabilityManager.swift │ ├── Result.swift │ ├── Validation.swift │ ├── ServerTrustPolicy.swift │ └── TaskDelegate.swift ├── README.md ├── SwiftyCryptoDisco.xcodeproj ├── project.xcworkspace │ └── contents.xcworkspacedata └── xcuserdata │ └── matschmid.xcuserdatad │ └── xcschemes │ └── xcschememanagement.plist ├── SwiftyCryptoDisco.xcworkspace ├── contents.xcworkspacedata └── xcuserdata │ └── matschmid.xcuserdatad │ └── xcdebugger │ └── Breakpoints_v2.xcbkptlist ├── Podfile ├── Podfile.lock ├── SwiftyCryptoDiscoUnitTests ├── Info.plist └── SwiftyCryptoDiscoUnitTests.swift └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | Pods/ 2 | 3 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } -------------------------------------------------------------------------------- /Pods/Target Support Files/Alamofire/Alamofire.modulemap: -------------------------------------------------------------------------------- 1 | framework module Alamofire { 2 | umbrella header "Alamofire-umbrella.h" 3 | 4 | export * 5 | module * { export * } 6 | } 7 | -------------------------------------------------------------------------------- /Pods/Target Support Files/SwiftyJSON/SwiftyJSON.modulemap: -------------------------------------------------------------------------------- 1 | framework module SwiftyJSON { 2 | umbrella header "SwiftyJSON-umbrella.h" 3 | 4 | export * 5 | module * { export * } 6 | } 7 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Alamofire/Alamofire-dummy.m: -------------------------------------------------------------------------------- 1 | #import 2 | @interface PodsDummy_Alamofire : NSObject 3 | @end 4 | @implementation PodsDummy_Alamofire 5 | @end 6 | -------------------------------------------------------------------------------- /Pods/Target Support Files/SwiftyJSON/SwiftyJSON-dummy.m: -------------------------------------------------------------------------------- 1 | #import 2 | @interface PodsDummy_SwiftyJSON : NSObject 3 | @end 4 | @implementation PodsDummy_SwiftyJSON 5 | @end 6 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/arrow.imageset/arrow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/arrow.imageset/arrow.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/arrow.imageset/arrow@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/arrow.imageset/arrow@2x.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/arrow.imageset/arrow@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/arrow.imageset/arrow@3x.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SwiftyCryptoDisco 2 | Minimal cryptocurrency tracking iOS App using RESTful API provided by https://coinmarketcap.com/api/ 3 | 4 | 5 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-1024.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-1024.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-120.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-120.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-121.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-121.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-152.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-152.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-167.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-167.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-180.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-180.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-20.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-20.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-29.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-29.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-40.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-40.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-41.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-41.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-42.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-42.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-58.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-58.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-59.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-59.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-60.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-60.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-76.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-76.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-80.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-80.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-81.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-81.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-87.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Icon-87.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/settings.imageset/settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/settings.imageset/settings.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/settings.imageset/settings@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/settings.imageset/settings@2x.png -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/settings.imageset/settings@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/schmidyy/SwiftyCryptoDisco/HEAD/SwiftyCryptoDisco/Supporting Files/Assets.xcassets/settings.imageset/settings@3x.png -------------------------------------------------------------------------------- /Pods/Target Support Files/Pods-SwiftyCryptoDisco/Pods-SwiftyCryptoDisco.modulemap: -------------------------------------------------------------------------------- 1 | framework module Pods_SwiftyCryptoDisco { 2 | umbrella header "Pods-SwiftyCryptoDisco-umbrella.h" 3 | 4 | export * 5 | module * { export * } 6 | } 7 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Pods-SwiftyCryptoDisco/Pods-SwiftyCryptoDisco-dummy.m: -------------------------------------------------------------------------------- 1 | #import 2 | @interface PodsDummy_Pods_SwiftyCryptoDisco : NSObject 3 | @end 4 | @implementation PodsDummy_Pods_SwiftyCryptoDisco 5 | @end 6 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Alamofire/Alamofire-prefix.pch: -------------------------------------------------------------------------------- 1 | #ifdef __OBJC__ 2 | #import 3 | #else 4 | #ifndef FOUNDATION_EXPORT 5 | #if defined(__cplusplus) 6 | #define FOUNDATION_EXPORT extern "C" 7 | #else 8 | #define FOUNDATION_EXPORT extern 9 | #endif 10 | #endif 11 | #endif 12 | 13 | -------------------------------------------------------------------------------- /Pods/Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch: -------------------------------------------------------------------------------- 1 | #ifdef __OBJC__ 2 | #import 3 | #else 4 | #ifndef FOUNDATION_EXPORT 5 | #if defined(__cplusplus) 6 | #define FOUNDATION_EXPORT extern "C" 7 | #else 8 | #define FOUNDATION_EXPORT extern 9 | #endif 10 | #endif 11 | #endif 12 | 13 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Podfile: -------------------------------------------------------------------------------- 1 | # Uncomment the next line to define a global platform for your project 2 | # platform :ios, '9.0' 3 | 4 | target 'SwiftyCryptoDisco' do 5 | # Comment the next line if you're not using Swift and don't want to use dynamic frameworks 6 | use_frameworks! 7 | 8 | # Pods for SwiftyCryptoDisco 9 | pod 'Alamofire' 10 | pod 'SwiftyJSON' 11 | 12 | end 13 | -------------------------------------------------------------------------------- /Podfile.lock: -------------------------------------------------------------------------------- 1 | PODS: 2 | - Alamofire (4.5.1) 3 | - SwiftyJSON (4.0.0) 4 | 5 | DEPENDENCIES: 6 | - Alamofire 7 | - SwiftyJSON 8 | 9 | SPEC CHECKSUMS: 10 | Alamofire: 2d95912bf4c34f164fdfc335872e8c312acaea4a 11 | SwiftyJSON: 070dabdcb1beb81b247c65ffa3a79dbbfb3b48aa 12 | 13 | PODFILE CHECKSUM: bd8605b4c7f98a5a913ec301a3cb77b78a80170d 14 | 15 | COCOAPODS: 1.3.1 16 | -------------------------------------------------------------------------------- /Pods/Manifest.lock: -------------------------------------------------------------------------------- 1 | PODS: 2 | - Alamofire (4.5.1) 3 | - SwiftyJSON (4.0.0) 4 | 5 | DEPENDENCIES: 6 | - Alamofire 7 | - SwiftyJSON 8 | 9 | SPEC CHECKSUMS: 10 | Alamofire: 2d95912bf4c34f164fdfc335872e8c312acaea4a 11 | SwiftyJSON: 070dabdcb1beb81b247c65ffa3a79dbbfb3b48aa 12 | 13 | PODFILE CHECKSUM: bd8605b4c7f98a5a913ec301a3cb77b78a80170d 14 | 15 | COCOAPODS: 1.3.1 16 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Alamofire/Alamofire-umbrella.h: -------------------------------------------------------------------------------- 1 | #ifdef __OBJC__ 2 | #import 3 | #else 4 | #ifndef FOUNDATION_EXPORT 5 | #if defined(__cplusplus) 6 | #define FOUNDATION_EXPORT extern "C" 7 | #else 8 | #define FOUNDATION_EXPORT extern 9 | #endif 10 | #endif 11 | #endif 12 | 13 | 14 | FOUNDATION_EXPORT double AlamofireVersionNumber; 15 | FOUNDATION_EXPORT const unsigned char AlamofireVersionString[]; 16 | 17 | -------------------------------------------------------------------------------- /Pods/Target Support Files/SwiftyJSON/SwiftyJSON-umbrella.h: -------------------------------------------------------------------------------- 1 | #ifdef __OBJC__ 2 | #import 3 | #else 4 | #ifndef FOUNDATION_EXPORT 5 | #if defined(__cplusplus) 6 | #define FOUNDATION_EXPORT extern "C" 7 | #else 8 | #define FOUNDATION_EXPORT extern 9 | #endif 10 | #endif 11 | #endif 12 | 13 | 14 | FOUNDATION_EXPORT double SwiftyJSONVersionNumber; 15 | FOUNDATION_EXPORT const unsigned char SwiftyJSONVersionString[]; 16 | 17 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/ConnectionManager.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ConnectionManager.swift 3 | // SwiftyCryptoDisco 4 | // 5 | // Created by Mat Schmid on 2018-02-11. 6 | // Copyright © 2018 Mat Schmid. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import Alamofire 11 | 12 | class ConnectionManager { 13 | class func isConnectedToInternet() -> Bool { 14 | return NetworkReachabilityManager()!.isReachable 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Pods-SwiftyCryptoDisco/Pods-SwiftyCryptoDisco-umbrella.h: -------------------------------------------------------------------------------- 1 | #ifdef __OBJC__ 2 | #import 3 | #else 4 | #ifndef FOUNDATION_EXPORT 5 | #if defined(__cplusplus) 6 | #define FOUNDATION_EXPORT extern "C" 7 | #else 8 | #define FOUNDATION_EXPORT extern 9 | #endif 10 | #endif 11 | #endif 12 | 13 | 14 | FOUNDATION_EXPORT double Pods_SwiftyCryptoDiscoVersionNumber; 15 | FOUNDATION_EXPORT const unsigned char Pods_SwiftyCryptoDiscoVersionString[]; 16 | 17 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco.xcodeproj/xcuserdata/matschmid.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | SwiftyCryptoDisco.xcscheme 8 | 9 | orderHint 10 | 3 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/DarkCellBG.colorset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | }, 6 | "colors" : [ 7 | { 8 | "idiom" : "universal", 9 | "color" : { 10 | "color-space" : "srgb", 11 | "components" : { 12 | "red" : "0.106", 13 | "alpha" : "1.000", 14 | "blue" : "0.106", 15 | "green" : "0.106" 16 | } 17 | } 18 | } 19 | ] 20 | } -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/flatBlue.colorset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | }, 6 | "colors" : [ 7 | { 8 | "idiom" : "universal", 9 | "color" : { 10 | "color-space" : "srgb", 11 | "components" : { 12 | "red" : "0.204", 13 | "alpha" : "1.000", 14 | "blue" : "0.859", 15 | "green" : "0.596" 16 | } 17 | } 18 | } 19 | ] 20 | } -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/flatRed.colorset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | }, 6 | "colors" : [ 7 | { 8 | "idiom" : "universal", 9 | "color" : { 10 | "color-space" : "srgb", 11 | "components" : { 12 | "red" : "0.906", 13 | "alpha" : "1.000", 14 | "blue" : "0.235", 15 | "green" : "0.298" 16 | } 17 | } 18 | } 19 | ] 20 | } -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/fluoGreen.colorset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | }, 6 | "colors" : [ 7 | { 8 | "idiom" : "universal", 9 | "color" : { 10 | "color-space" : "srgb", 11 | "components" : { 12 | "red" : "0.184", 13 | "alpha" : "1.000", 14 | "blue" : "0.537", 15 | "green" : "1.000" 16 | } 17 | } 18 | } 19 | ] 20 | } -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/settings.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "settings.png", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "filename" : "settings@2x.png", 11 | "scale" : "2x" 12 | }, 13 | { 14 | "idiom" : "universal", 15 | "filename" : "settings@3x.png", 16 | "scale" : "3x" 17 | } 18 | ], 19 | "info" : { 20 | "version" : 1, 21 | "author" : "xcode" 22 | } 23 | } -------------------------------------------------------------------------------- /Pods/Target Support Files/Alamofire/Alamofire.xcconfig: -------------------------------------------------------------------------------- 1 | CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Alamofire 2 | GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 3 | HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" 4 | OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" 5 | PODS_BUILD_DIR = $BUILD_DIR 6 | PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) 7 | PODS_ROOT = ${SRCROOT} 8 | PODS_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire 9 | PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} 10 | SKIP_INSTALL = YES 11 | -------------------------------------------------------------------------------- /Pods/Target Support Files/SwiftyJSON/SwiftyJSON.xcconfig: -------------------------------------------------------------------------------- 1 | CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON 2 | GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 3 | HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" 4 | OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" 5 | PODS_BUILD_DIR = $BUILD_DIR 6 | PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) 7 | PODS_ROOT = ${SRCROOT} 8 | PODS_TARGET_SRCROOT = ${PODS_ROOT}/SwiftyJSON 9 | PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} 10 | SKIP_INSTALL = YES 11 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/arrow.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "arrow.png", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "filename" : "arrow@2x.png", 11 | "scale" : "2x" 12 | }, 13 | { 14 | "idiom" : "universal", 15 | "filename" : "arrow@3x.png", 16 | "scale" : "3x" 17 | } 18 | ], 19 | "info" : { 20 | "version" : 1, 21 | "author" : "xcode" 22 | }, 23 | "properties" : { 24 | "template-rendering-intent" : "template" 25 | } 26 | } -------------------------------------------------------------------------------- /SwiftyCryptoDiscoUnitTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleVersion 20 | 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Model/MarketExchange.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MarketExchange.swift 3 | // SwiftyCryptoDisco 4 | // 5 | // Created by Mat Schmid on 2018-01-25. 6 | // Copyright © 2018 Mat Schmid. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import SwiftyJSON 11 | 12 | struct MarketExchange { 13 | let symbolID : String 14 | let exchangeID : String 15 | let baseCurrencyID : String 16 | let quoteCurrencyID : String 17 | 18 | init(withDictionary marketDictionary: JSON) { 19 | self.symbolID = marketDictionary["symbol_id"].stringValue 20 | self.exchangeID = marketDictionary["exchange_id"].stringValue 21 | self.baseCurrencyID = marketDictionary["asset_id_base"].stringValue 22 | self.quoteCurrencyID = marketDictionary["asset_id_quote"].stringValue 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Pods/Pods.xcodeproj/xcuserdata/matschmid.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | Alamofire.xcscheme 8 | 9 | isShown 10 | 11 | orderHint 12 | 0 13 | 14 | Pods-SwiftyCryptoDisco.xcscheme 15 | 16 | isShown 17 | 18 | orderHint 19 | 1 20 | 21 | SwiftyJSON.xcscheme 22 | 23 | isShown 24 | 25 | orderHint 26 | 2 27 | 28 | 29 | SuppressBuildableAutocreation 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Pods-SwiftyCryptoDisco/Pods-SwiftyCryptoDisco.debug.xcconfig: -------------------------------------------------------------------------------- 1 | ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES 2 | FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON" 3 | GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 4 | LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' 5 | OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON/SwiftyJSON.framework/Headers" 6 | OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "SwiftyJSON" 7 | OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" 8 | PODS_BUILD_DIR = $BUILD_DIR 9 | PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) 10 | PODS_PODFILE_DIR_PATH = ${SRCROOT}/. 11 | PODS_ROOT = ${SRCROOT}/Pods 12 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Pods-SwiftyCryptoDisco/Pods-SwiftyCryptoDisco.release.xcconfig: -------------------------------------------------------------------------------- 1 | ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES 2 | FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON" 3 | GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 4 | LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' 5 | OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON/SwiftyJSON.framework/Headers" 6 | OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "SwiftyJSON" 7 | OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" 8 | PODS_BUILD_DIR = $BUILD_DIR 9 | PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) 10 | PODS_PODFILE_DIR_PATH = ${SRCROOT}/. 11 | PODS_ROOT = ${SRCROOT}/Pods 12 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Views/SliderTableViewCell.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SliderTableViewCell.swift 3 | // SwiftyCryptoDisco 4 | // 5 | // Created by Mat Schmid on 2018-01-08. 6 | // Copyright © 2018 Mat Schmid. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | 11 | protocol SliderCellDelegate: class { 12 | func cellSliderValueDidChange(value: Int) 13 | } 14 | 15 | class SliderTableViewCell: UITableViewCell { 16 | 17 | @IBOutlet weak var numSearchableCoinsLabel: UILabel! 18 | @IBOutlet weak var numSearchableCoinsSlider: UISlider! 19 | 20 | var delegate: SliderCellDelegate? 21 | 22 | @IBAction func sliderValueChanged(_ sender: UISlider) { 23 | let step: Float = 5.0 24 | let roundedValue = round(sender.value / step) * step 25 | sender.value = roundedValue 26 | numSearchableCoinsLabel.text = "TOP \(Int(roundedValue))" 27 | delegate?.cellSliderValueDidChange(value: Int(roundedValue)) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Alamofire/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | ${EXECUTABLE_NAME} 9 | CFBundleIdentifier 10 | ${PRODUCT_BUNDLE_IDENTIFIER} 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | ${PRODUCT_NAME} 15 | CFBundlePackageType 16 | FMWK 17 | CFBundleShortVersionString 18 | 4.5.1 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | ${CURRENT_PROJECT_VERSION} 23 | NSPrincipalClass 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Pods/Target Support Files/SwiftyJSON/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | ${EXECUTABLE_NAME} 9 | CFBundleIdentifier 10 | ${PRODUCT_BUNDLE_IDENTIFIER} 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | ${PRODUCT_NAME} 15 | CFBundlePackageType 16 | FMWK 17 | CFBundleShortVersionString 18 | 4.0.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | ${CURRENT_PROJECT_VERSION} 23 | NSPrincipalClass 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Pods-SwiftyCryptoDisco/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | ${EXECUTABLE_NAME} 9 | CFBundleIdentifier 10 | ${PRODUCT_BUNDLE_IDENTIFIER} 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | ${PRODUCT_NAME} 15 | CFBundlePackageType 16 | FMWK 17 | CFBundleShortVersionString 18 | 1.0.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | ${CURRENT_PROJECT_VERSION} 23 | NSPrincipalClass 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /SwiftyCryptoDiscoUnitTests/SwiftyCryptoDiscoUnitTests.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SwiftyCryptoDiscoUnitTests.swift 3 | // SwiftyCryptoDiscoUnitTests 4 | // 5 | // Created by Mat Schmid on 2018-02-12. 6 | // Copyright © 2018 Mat Schmid. All rights reserved. 7 | // 8 | 9 | import XCTest 10 | 11 | class SwiftyCryptoDiscoUnitTests: XCTestCase { 12 | 13 | override func setUp() { 14 | super.setUp() 15 | // Put setup code here. This method is called before the invocation of each test method in the class. 16 | } 17 | 18 | override func tearDown() { 19 | // Put teardown code here. This method is called after the invocation of each test method in the class. 20 | super.tearDown() 21 | } 22 | 23 | func testISO8601StringConverter() { 24 | 25 | let iso8601Date = "2017-11-05T00:00:00.0000000Z" 26 | let formattedString: String = iso8601Date.getStringRepresentableFromISO8601String() 27 | 28 | XCTAssertEqual(formattedString, "Nov 5 12:00") 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Model/OHLCV.swift: -------------------------------------------------------------------------------- 1 | // 2 | // OHLCV.swift 3 | // SwiftyCryptoDisco 4 | // 5 | // Created by Mat Schmid on 2018-01-25. 6 | // Copyright © 2018 Mat Schmid. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import SwiftyJSON 11 | 12 | struct OHLCV { 13 | let timePeriodStart : String 14 | let priceOpen : NSNumber 15 | let priceHigh : NSNumber 16 | let priceLow : NSNumber 17 | let priceClose : NSNumber 18 | let volume : NSNumber 19 | 20 | init(withDictionary ohlcvDictionary: JSON) { 21 | self.timePeriodStart = ohlcvDictionary["time_period_start"].stringValue 22 | self.priceOpen = ohlcvDictionary["price_open"].numberValue 23 | self.priceHigh = ohlcvDictionary["price_high"].numberValue 24 | self.priceLow = ohlcvDictionary["price_low"].numberValue 25 | self.priceClose = ohlcvDictionary["price_close"].numberValue 26 | self.volume = ohlcvDictionary["volume_traded"].numberValue 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Mat Schmid 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Views/OHLCVTableViewCell.swift: -------------------------------------------------------------------------------- 1 | // 2 | // OHLCVTableViewCell.swift 3 | // SwiftyCryptoDisco 4 | // 5 | // Created by Mat Schmid on 2018-02-06. 6 | // Copyright © 2018 Mat Schmid. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | 11 | class OHLCVTableViewCell: UITableViewCell { 12 | 13 | @IBOutlet weak var timeLabel: UILabel! 14 | @IBOutlet weak var volumeLabel: UILabel! 15 | @IBOutlet weak var openLabel: UILabel! 16 | @IBOutlet weak var highLabel: UILabel! 17 | @IBOutlet weak var lowLabel: UILabel! 18 | @IBOutlet weak var closeLabel: UILabel! 19 | 20 | func formatCellWithOHLCV(ohlcv: OHLCV) { 21 | timeLabel.text = ohlcv.timePeriodStart.getStringRepresentableFromISO8601String() 22 | volumeLabel.text = String(format: "%.4f", ohlcv.volume.floatValue) 23 | openLabel.text = String(format: "%.f", ohlcv.priceOpen.floatValue) 24 | highLabel.text = String(format: "%.f", ohlcv.priceHigh.floatValue) 25 | lowLabel.text = String(format: "%.f", ohlcv.priceLow.floatValue) 26 | closeLabel.text = String(format: "%.f", ohlcv.priceClose.floatValue) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Pods/SwiftyJSON/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2017 Ruoyu Fu 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /Pods/Alamofire/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco.xcworkspace/xcuserdata/matschmid.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 8 | 20 | 21 | 22 | 24 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleVersion 20 | 1.1 21 | LSRequiresIPhoneOS 22 | 23 | UILaunchStoryboardName 24 | LaunchScreen 25 | UIMainStoryboardFile 26 | Main 27 | UIRequiredDeviceCapabilities 28 | 29 | armv7 30 | 31 | UIStatusBarStyle 32 | UIStatusBarStyleDefault 33 | UISupportedInterfaceOrientations 34 | 35 | UIInterfaceOrientationPortrait 36 | UIInterfaceOrientationLandscapeLeft 37 | UIInterfaceOrientationLandscapeRight 38 | 39 | UISupportedInterfaceOrientations~ipad 40 | 41 | UIInterfaceOrientationPortrait 42 | UIInterfaceOrientationPortraitUpsideDown 43 | UIInterfaceOrientationLandscapeLeft 44 | UIInterfaceOrientationLandscapeRight 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /Pods/Alamofire/Source/DispatchQueue+Alamofire.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DispatchQueue+Alamofire.swift 3 | // 4 | // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | // 24 | 25 | import Dispatch 26 | import Foundation 27 | 28 | extension DispatchQueue { 29 | static var userInteractive: DispatchQueue { return DispatchQueue.global(qos: .userInteractive) } 30 | static var userInitiated: DispatchQueue { return DispatchQueue.global(qos: .userInitiated) } 31 | static var utility: DispatchQueue { return DispatchQueue.global(qos: .utility) } 32 | static var background: DispatchQueue { return DispatchQueue.global(qos: .background) } 33 | 34 | func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { 35 | asyncAfter(deadline: .now() + delay, execute: closure) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Client/CurrencyDataFetcher.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CurrencyDataFetcher.swift 3 | // SwiftyCryptoDisco 4 | // 5 | // Created by Mat Schmid on 2017-12-22. 6 | // Copyright © 2017 Mat Schmid. All rights reserved. 7 | // 8 | 9 | import Alamofire 10 | import SwiftyJSON 11 | 12 | class CurrencyDataFetcher { 13 | 14 | // RESTful Coin data API provided by CoinMarketCap 15 | // See documentation at https://coinmarketcap.com/api/ 16 | 17 | func getDataForCurrency(currency: String, completion: @escaping(_ coin: Currency?) -> Void) { 18 | let currencyURL = "https://api.coinmarketcap.com/v1/ticker/\(currency)/?convert=CAD" 19 | Alamofire.request(currencyURL).responseJSON { (response) in 20 | if let data = response.data { 21 | let json = JSON(data) 22 | let coin = Currency(withDictionary: json[0]) 23 | completion(coin) 24 | } else { 25 | completion(nil) 26 | } 27 | } 28 | } 29 | 30 | func getDataForAllCurencies(completion: @escaping(_ coins: [Currency]?) -> Void) { 31 | let coinLimit = getSearchableCoinsLimit() 32 | let apiURL = "https://api.coinmarketcap.com/v1/ticker/?convert=CAD&limit=\(coinLimit)" 33 | var coins : [Currency] = [] 34 | Alamofire.request(apiURL).responseJSON { (response) in 35 | if let data = response.data { 36 | let json = JSON(data) 37 | for subJson in json { 38 | let coin = Currency(withDictionary: subJson.1) 39 | coins.append(coin) 40 | } 41 | completion(coins) 42 | } else { 43 | completion(nil) 44 | } 45 | } 46 | } 47 | 48 | func getSearchableCoinsLimit() -> Int { 49 | if let numSearchableCoinsLimit = defaults.value(forKey: kSearchableCurrenciesKey) { 50 | return numSearchableCoinsLimit as! Int 51 | } 52 | return 100 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/GlobalsEnumsExtensions.swift: -------------------------------------------------------------------------------- 1 | // 2 | // GlobalsEnumsExtensions.swift 3 | // SwiftyCryptoDisco 4 | // 5 | // Created by Mat Schmid on 2018-02-06. 6 | // Copyright © 2018 Mat Schmid. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | //MARK: - Global properties 12 | let defaults = UserDefaults.standard 13 | 14 | //MARK: - Enums 15 | enum Period: String { 16 | case ONEHOUR = "1HRS" 17 | case TWELVEHOURS = "12HRS" 18 | case ONEDAY = "1DAY" 19 | case ONEWEEK = "7DAY" 20 | case ONEMONTH = "1MTH" 21 | case ONEYEAR = "1YRS" 22 | static let allValues = [ONEHOUR, TWELVEHOURS, ONEDAY, ONEWEEK, ONEMONTH, ONEYEAR] 23 | } 24 | 25 | //MARK: - Extensions 26 | extension NSNumber { 27 | var formattedCurrencyString: String? { 28 | let formatter = NumberFormatter() 29 | formatter.locale = Locale(identifier: "en_US") 30 | formatter.numberStyle = .currency 31 | return formatter.string(from: self) 32 | } 33 | } 34 | 35 | extension String { 36 | func getStringRepresentableFromISO8601String() -> String { 37 | if (!self.isEmpty) { 38 | let dateSplit = self.split(separator: "-") 39 | let timeSeperatorSplit = dateSplit[dateSplit.count - 1].split(separator: "T") 40 | let timeSplit = timeSeperatorSplit[timeSeperatorSplit.count - 1].split(separator: ":") 41 | 42 | let year = dateSplit[0] 43 | let month = dateSplit[1] 44 | let day = timeSeperatorSplit[0] 45 | let hour = timeSplit[0] 46 | let minute = timeSplit[1] 47 | 48 | var dateComponents = DateComponents() 49 | dateComponents.year = Int(year) 50 | dateComponents.month = Int(month) 51 | dateComponents.day = Int(day) 52 | dateComponents.hour = Int(hour) 53 | dateComponents.minute = Int(minute) 54 | let date = Calendar.current.date(from: dateComponents)! 55 | 56 | let formatter = DateFormatter() 57 | formatter.dateFormat = "MMM d h:mm" 58 | let dateString = formatter.string(from: date) 59 | return dateString 60 | } 61 | return "" 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.swift 3 | // SwiftyCryptoDisco 4 | // 5 | // Created by Mat Schmid on 2017-12-22. 6 | // Copyright © 2017 Mat Schmid. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | 11 | @UIApplicationMain 12 | class AppDelegate: UIResponder, UIApplicationDelegate { 13 | 14 | var window: UIWindow? 15 | 16 | 17 | func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 18 | UIApplication.shared.statusBarStyle = .lightContent 19 | return true 20 | } 21 | 22 | func applicationWillResignActive(_ application: UIApplication) { 23 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 24 | // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. 25 | } 26 | 27 | func applicationDidEnterBackground(_ application: UIApplication) { 28 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 29 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 30 | } 31 | 32 | func applicationWillEnterForeground(_ application: UIApplication) { 33 | // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. 34 | } 35 | 36 | func applicationDidBecomeActive(_ application: UIApplication) { 37 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 38 | } 39 | 40 | func applicationWillTerminate(_ application: UIApplication) { 41 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 42 | } 43 | 44 | 45 | } 46 | 47 | -------------------------------------------------------------------------------- /Pods/Pods.xcodeproj/xcuserdata/matschmid.xcuserdatad/xcschemes/Alamofire.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 32 | 33 | 43 | 44 | 45 | 46 | 52 | 53 | 55 | 56 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /Pods/Pods.xcodeproj/xcuserdata/matschmid.xcuserdatad/xcschemes/SwiftyJSON.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 32 | 33 | 43 | 44 | 45 | 46 | 52 | 53 | 55 | 56 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Client/MarketDataFetcher.swift: -------------------------------------------------------------------------------- 1 | // 2 | // MarketDataFetcher.swift 3 | // SwiftyCryptoDisco 4 | // 5 | // Created by Mat Schmid on 2018-01-25. 6 | // Copyright © 2018 Mat Schmid. All rights reserved. 7 | // 8 | 9 | import Alamofire 10 | import SwiftyJSON 11 | 12 | class MarketDataFetcher { 13 | 14 | // RESTful Market data provided by CoinAPI 15 | // Reference documentation can be found at https://docs.coinapi.io/#rest-api 16 | 17 | let APIKey = "55DCAFC7-20C7-4099-8BDA-2C4421377405" 18 | 19 | func getMarketDataForBaseCurrency(coinCurrency: String, baseCurrency: String, completion: @escaping(_ exchanges: [MarketExchange]?) -> Void) { 20 | let header : HTTPHeaders = [ 21 | "X-CoinAPI-Key": APIKey 22 | ] 23 | Alamofire.request("https://rest.coinapi.io/v1/symbols/", headers: header).responseJSON { (response) in 24 | if let data = response.data { 25 | let json = JSON(data) 26 | print(json) 27 | var marketArray: [MarketExchange] = [] 28 | for subJson in json { 29 | if subJson.1["asset_id_base"].stringValue == coinCurrency, subJson.1["asset_id_quote"].stringValue == baseCurrency { 30 | let marketExchange = MarketExchange(withDictionary: subJson.1) 31 | marketArray.append(marketExchange) 32 | break 33 | } 34 | } 35 | completion(marketArray) 36 | } else { 37 | completion(nil) 38 | } 39 | } 40 | } 41 | 42 | func getOHLCVDataForSymbol(symbol: String, period: Period, completion: @escaping(_ ohlcvs: [OHLCV]?) -> Void) { 43 | let header : HTTPHeaders = [ 44 | "X-CoinAPI-Key": APIKey 45 | ] 46 | Alamofire.request("https://rest.coinapi.io/v1/ohlcv/\(symbol)/latest?period_id=\(period.rawValue)", headers: header).responseJSON { (response) in 47 | if let data = response.data { 48 | let json = JSON(data) 49 | var ohlcvArray: [OHLCV] = [] 50 | for subJson in json { 51 | print(subJson) 52 | let ohlcv = OHLCV(withDictionary: subJson.1) 53 | ohlcvArray.append(ohlcv) 54 | } 55 | completion(ohlcvArray) 56 | } else { 57 | completion(nil) 58 | } 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Model/Currency.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Currency.swift 3 | // SwiftyCryptoDisco 4 | // 5 | // Created by Mat Schmid on 2017-12-23. 6 | // Copyright © 2017 Mat Schmid. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import SwiftyJSON 11 | 12 | struct Currency: Equatable { 13 | 14 | let id : String 15 | let name : String 16 | let symbol : String 17 | let rank : Int 18 | let priceUSD : NSNumber 19 | let priceBTC : Double 20 | let priceCAD : NSNumber? 21 | let dailyVolume : Double 22 | let marketCapUSD : Double 23 | let availableSupply : Double 24 | let totalSupply : Double 25 | let maxSupply : Double? 26 | let percentChangeHourly : Double 27 | let percentChangeDaily : Double 28 | let percentChangeWeekly : Double 29 | let lastUpdated : TimeInterval 30 | 31 | init(withDictionary currencyDictionary: JSON) { 32 | self.id = currencyDictionary["id"].stringValue 33 | self.name = currencyDictionary["name"].stringValue 34 | self.symbol = currencyDictionary["symbol"].stringValue 35 | self.rank = currencyDictionary["rank"].intValue 36 | self.priceUSD = currencyDictionary["price_usd"].numberValue 37 | self.priceBTC = currencyDictionary["price_btc"].doubleValue 38 | self.priceCAD = currencyDictionary["price_cad"].numberValue 39 | self.dailyVolume = currencyDictionary["24h_volume_usd"].doubleValue 40 | self.marketCapUSD = currencyDictionary["market_cap_usd"].doubleValue 41 | self.availableSupply = currencyDictionary["available_supply"].doubleValue 42 | self.totalSupply = currencyDictionary["total_supply"].doubleValue 43 | self.maxSupply = currencyDictionary["max_supply"].doubleValue 44 | self.percentChangeHourly = currencyDictionary["percent_change_1h"].doubleValue 45 | self.percentChangeDaily = currencyDictionary["percent_change_24h"].doubleValue 46 | self.percentChangeWeekly = currencyDictionary["percent_change_7d"].doubleValue 47 | self.lastUpdated = currencyDictionary["last_updated"].doubleValue as TimeInterval 48 | } 49 | 50 | static func ==(lhs: Currency, rhs: Currency) -> Bool { 51 | return lhs.id == rhs.id 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Pods-SwiftyCryptoDisco/Pods-SwiftyCryptoDisco-acknowledgements.markdown: -------------------------------------------------------------------------------- 1 | # Acknowledgements 2 | This application makes use of the following third party libraries: 3 | 4 | ## Alamofire 5 | 6 | Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) 7 | 8 | Permission is hereby granted, free of charge, to any person obtaining a copy 9 | of this software and associated documentation files (the "Software"), to deal 10 | in the Software without restriction, including without limitation the rights 11 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | copies of the Software, and to permit persons to whom the Software is 13 | furnished to do so, subject to the following conditions: 14 | 15 | The above copyright notice and this permission notice shall be included in 16 | all copies or substantial portions of the Software. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | THE SOFTWARE. 25 | 26 | 27 | ## SwiftyJSON 28 | 29 | The MIT License (MIT) 30 | 31 | Copyright (c) 2017 Ruoyu Fu 32 | 33 | Permission is hereby granted, free of charge, to any person obtaining a copy 34 | of this software and associated documentation files (the "Software"), to deal 35 | in the Software without restriction, including without limitation the rights 36 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 37 | copies of the Software, and to permit persons to whom the Software is 38 | furnished to do so, subject to the following conditions: 39 | 40 | The above copyright notice and this permission notice shall be included in 41 | all copies or substantial portions of the Software. 42 | 43 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 44 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 45 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 46 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 47 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 48 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 49 | THE SOFTWARE. 50 | 51 | Generated by CocoaPods - https://cocoapods.org 52 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/View Controllers/ContainerViewController.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ContainerViewController.swift 3 | // SwiftyCryptoDisco 4 | // 5 | // Created by Mat Schmid on 2017-12-22. 6 | // Copyright © 2017 Mat Schmid. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | 11 | class ContainerViewController: UIViewController, UINavigationControllerDelegate , CurrencyTableViewDelegate { 12 | 13 | @IBOutlet weak var refreshDateLabel: UILabel! 14 | @IBOutlet weak var addCoinButton: UIButton! 15 | 16 | var mainNavigationController: UINavigationController! 17 | var currencyTableViewController: CurrencyTableViewController! 18 | 19 | //MARK: - Lifecycle Methods 20 | override func viewDidLoad() { 21 | super.viewDidLoad() 22 | addCoinButton.layer.cornerRadius = addCoinButton.frame.width / 2 23 | refreshDate() 24 | } 25 | 26 | override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 27 | if segue.identifier == "CryptoVC" { 28 | mainNavigationController = segue.destination as! UINavigationController 29 | mainNavigationController.delegate = self 30 | currencyTableViewController = mainNavigationController.childViewControllers.first as! CurrencyTableViewController! 31 | currencyTableViewController.delegate = self 32 | } 33 | } 34 | 35 | override var preferredStatusBarStyle: UIStatusBarStyle { 36 | return .lightContent 37 | } 38 | 39 | //MARK: - Supporting Class Methods 40 | func refreshDate() { 41 | let dateFormatter = DateFormatter() 42 | dateFormatter.dateStyle = .medium 43 | dateFormatter.timeStyle = .medium 44 | let date = Date() 45 | let dateString = dateFormatter.string(from: date) 46 | refreshDateLabel.text = dateString 47 | } 48 | 49 | //MARK: - Event Handlers 50 | @IBAction func addCoinButtonTapped(_ sender: UIButton) { 51 | let addCoinVC = storyboard?.instantiateViewController(withIdentifier: "addCoinVC") as! AddCoinTableViewController 52 | addCoinVC.delegate = currencyTableViewController 53 | mainNavigationController.pushViewController(addCoinVC, animated: true) 54 | } 55 | 56 | //MARK: - CurrencyTableViewDelegate 57 | func didTapRefreshButton() { 58 | refreshDate() 59 | } 60 | 61 | //MARK: - UINavigationControllerDelegate 62 | func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { 63 | if let title = viewController.title { 64 | if title != "Crypto Disco" { 65 | addCoinButton.isHidden = true 66 | } else { 67 | addCoinButton.isHidden = false 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Pods/Alamofire/Source/Notifications.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Notifications.swift 3 | // 4 | // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | // 24 | 25 | import Foundation 26 | 27 | extension Notification.Name { 28 | /// Used as a namespace for all `URLSessionTask` related notifications. 29 | public struct Task { 30 | /// Posted when a `URLSessionTask` is resumed. The notification `object` contains the resumed `URLSessionTask`. 31 | public static let DidResume = Notification.Name(rawValue: "org.alamofire.notification.name.task.didResume") 32 | 33 | /// Posted when a `URLSessionTask` is suspended. The notification `object` contains the suspended `URLSessionTask`. 34 | public static let DidSuspend = Notification.Name(rawValue: "org.alamofire.notification.name.task.didSuspend") 35 | 36 | /// Posted when a `URLSessionTask` is cancelled. The notification `object` contains the cancelled `URLSessionTask`. 37 | public static let DidCancel = Notification.Name(rawValue: "org.alamofire.notification.name.task.didCancel") 38 | 39 | /// Posted when a `URLSessionTask` is completed. The notification `object` contains the completed `URLSessionTask`. 40 | public static let DidComplete = Notification.Name(rawValue: "org.alamofire.notification.name.task.didComplete") 41 | } 42 | } 43 | 44 | // MARK: - 45 | 46 | extension Notification { 47 | /// Used as a namespace for all `Notification` user info dictionary keys. 48 | public struct Key { 49 | /// User info dictionary key representing the `URLSessionTask` associated with the notification. 50 | public static let Task = "org.alamofire.notification.key.task" 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "size" : "20x20", 5 | "idiom" : "iphone", 6 | "filename" : "Icon-40.png", 7 | "scale" : "2x" 8 | }, 9 | { 10 | "size" : "20x20", 11 | "idiom" : "iphone", 12 | "filename" : "Icon-60.png", 13 | "scale" : "3x" 14 | }, 15 | { 16 | "size" : "29x29", 17 | "idiom" : "iphone", 18 | "filename" : "Icon-58.png", 19 | "scale" : "2x" 20 | }, 21 | { 22 | "size" : "29x29", 23 | "idiom" : "iphone", 24 | "filename" : "Icon-87.png", 25 | "scale" : "3x" 26 | }, 27 | { 28 | "size" : "40x40", 29 | "idiom" : "iphone", 30 | "filename" : "Icon-80.png", 31 | "scale" : "2x" 32 | }, 33 | { 34 | "size" : "40x40", 35 | "idiom" : "iphone", 36 | "filename" : "Icon-120.png", 37 | "scale" : "3x" 38 | }, 39 | { 40 | "size" : "60x60", 41 | "idiom" : "iphone", 42 | "filename" : "Icon-121.png", 43 | "scale" : "2x" 44 | }, 45 | { 46 | "size" : "60x60", 47 | "idiom" : "iphone", 48 | "filename" : "Icon-180.png", 49 | "scale" : "3x" 50 | }, 51 | { 52 | "size" : "20x20", 53 | "idiom" : "ipad", 54 | "filename" : "Icon-20.png", 55 | "scale" : "1x" 56 | }, 57 | { 58 | "size" : "20x20", 59 | "idiom" : "ipad", 60 | "filename" : "Icon-41.png", 61 | "scale" : "2x" 62 | }, 63 | { 64 | "size" : "29x29", 65 | "idiom" : "ipad", 66 | "filename" : "Icon-29.png", 67 | "scale" : "1x" 68 | }, 69 | { 70 | "size" : "29x29", 71 | "idiom" : "ipad", 72 | "filename" : "Icon-59.png", 73 | "scale" : "2x" 74 | }, 75 | { 76 | "size" : "40x40", 77 | "idiom" : "ipad", 78 | "filename" : "Icon-42.png", 79 | "scale" : "1x" 80 | }, 81 | { 82 | "size" : "40x40", 83 | "idiom" : "ipad", 84 | "filename" : "Icon-81.png", 85 | "scale" : "2x" 86 | }, 87 | { 88 | "size" : "76x76", 89 | "idiom" : "ipad", 90 | "filename" : "Icon-76.png", 91 | "scale" : "1x" 92 | }, 93 | { 94 | "size" : "76x76", 95 | "idiom" : "ipad", 96 | "filename" : "Icon-152.png", 97 | "scale" : "2x" 98 | }, 99 | { 100 | "size" : "83.5x83.5", 101 | "idiom" : "ipad", 102 | "filename" : "Icon-167.png", 103 | "scale" : "2x" 104 | }, 105 | { 106 | "size" : "1024x1024", 107 | "idiom" : "ios-marketing", 108 | "filename" : "Icon-1024.png", 109 | "scale" : "1x" 110 | } 111 | ], 112 | "info" : { 113 | "version" : 1, 114 | "author" : "xcode" 115 | } 116 | } -------------------------------------------------------------------------------- /Pods/Pods.xcodeproj/xcuserdata/matschmid.xcuserdatad/xcschemes/Pods-SwiftyCryptoDisco.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 31 | 32 | 33 | 34 | 35 | 36 | 47 | 48 | 54 | 55 | 56 | 57 | 58 | 59 | 65 | 66 | 68 | 69 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/View Controllers/AddCoinTableViewController.swift: -------------------------------------------------------------------------------- 1 | 2 | // 3 | // AddCoinTableViewController.swift 4 | // SwiftyCryptoDisco 5 | // 6 | // Created by Mat Schmid on 2017-12-24. 7 | // Copyright © 2017 Mat Schmid. All rights reserved. 8 | // 9 | 10 | import UIKit 11 | 12 | protocol AddCoinDelegate { 13 | func didTapCoinWithID(id: String) 14 | } 15 | 16 | class AddCoinTableViewController: UITableViewController, UISearchBarDelegate { 17 | 18 | let kCoinCellReuseIdentifier = "CoinCell" 19 | var delegate : AddCoinDelegate? 20 | var coins: [Currency]? 21 | var filteredCoins : [Currency]? 22 | 23 | let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) 24 | 25 | @IBOutlet weak var currencySearchBar: UISearchBar! 26 | var isSearching = false 27 | 28 | override func viewDidLoad() { 29 | super.viewDidLoad() 30 | 31 | activityIndicator.hidesWhenStopped = true 32 | activityIndicator.center = CGPoint(x: tableView.frame.width / 2, y: tableView.frame.height / 2 - 56) 33 | self.view.addSubview(activityIndicator) 34 | self.activityIndicator.startAnimating() 35 | 36 | currencySearchBar.delegate = self 37 | let dataFetcher = CurrencyDataFetcher() 38 | dataFetcher.getDataForAllCurencies { (coinArray) in 39 | guard let coinArray = coinArray else { 40 | return 41 | } 42 | let sortedCoins = coinArray.sorted { $0.name < $1.name } 43 | self.coins = sortedCoins 44 | self.activityIndicator.stopAnimating() 45 | self.tableView.reloadData() 46 | } 47 | } 48 | 49 | // MARK: - Table view data source 50 | override func numberOfSections(in tableView: UITableView) -> Int { 51 | return 1 52 | } 53 | 54 | override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 55 | if coins != nil { 56 | return (isSearching) ? (filteredCoins?.count)! : (coins?.count)! 57 | } else { 58 | return 0 59 | } 60 | } 61 | 62 | override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 63 | return 66 64 | } 65 | 66 | override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 67 | let cell = self.tableView.dequeueReusableCell(withIdentifier: kCoinCellReuseIdentifier, for: indexPath) as! CoinTableViewCell 68 | cell.formatCellFor(coin: (isSearching) ? filteredCoins![indexPath.row] : coins![indexPath.row]) 69 | return cell 70 | } 71 | 72 | override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 73 | let coin = isSearching ? filteredCoins![indexPath.row] : coins![indexPath.row] 74 | delegate?.didTapCoinWithID(id: coin.id) 75 | navigationController?.popToRootViewController(animated: true) 76 | } 77 | 78 | // MARK: - Search Bar Delegate 79 | func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { 80 | if (currencySearchBar.text?.isEmpty)! { 81 | isSearching = false 82 | view.endEditing(true) 83 | tableView.reloadData() 84 | } else { 85 | isSearching = true 86 | filteredCoins = coins?.filter({ $0.name.lowercased().range(of: currencySearchBar.text!.lowercased()) != nil }) 87 | tableView.reloadData() 88 | } 89 | } 90 | 91 | func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { 92 | view.endEditing(true) 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Pods-SwiftyCryptoDisco/Pods-SwiftyCryptoDisco-acknowledgements.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PreferenceSpecifiers 6 | 7 | 8 | FooterText 9 | This application makes use of the following third party libraries: 10 | Title 11 | Acknowledgements 12 | Type 13 | PSGroupSpecifier 14 | 15 | 16 | FooterText 17 | Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) 18 | 19 | Permission is hereby granted, free of charge, to any person obtaining a copy 20 | of this software and associated documentation files (the "Software"), to deal 21 | in the Software without restriction, including without limitation the rights 22 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 23 | copies of the Software, and to permit persons to whom the Software is 24 | furnished to do so, subject to the following conditions: 25 | 26 | The above copyright notice and this permission notice shall be included in 27 | all copies or substantial portions of the Software. 28 | 29 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 30 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 31 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 32 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 33 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 34 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 35 | THE SOFTWARE. 36 | 37 | License 38 | MIT 39 | Title 40 | Alamofire 41 | Type 42 | PSGroupSpecifier 43 | 44 | 45 | FooterText 46 | The MIT License (MIT) 47 | 48 | Copyright (c) 2017 Ruoyu Fu 49 | 50 | Permission is hereby granted, free of charge, to any person obtaining a copy 51 | of this software and associated documentation files (the "Software"), to deal 52 | in the Software without restriction, including without limitation the rights 53 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 54 | copies of the Software, and to permit persons to whom the Software is 55 | furnished to do so, subject to the following conditions: 56 | 57 | The above copyright notice and this permission notice shall be included in 58 | all copies or substantial portions of the Software. 59 | 60 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 61 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 62 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 63 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 64 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 65 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 66 | THE SOFTWARE. 67 | 68 | License 69 | MIT 70 | Title 71 | SwiftyJSON 72 | Type 73 | PSGroupSpecifier 74 | 75 | 76 | FooterText 77 | Generated by CocoaPods - https://cocoapods.org 78 | Title 79 | 80 | Type 81 | PSGroupSpecifier 82 | 83 | 84 | StringsTable 85 | Acknowledgements 86 | Title 87 | Acknowledgements 88 | 89 | 90 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Supporting Files/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | HelveticaNeue 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 33 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Views/CoinTableViewCell.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CoinTableViewCell.swift 3 | // SwiftyCryptoDisco 4 | // 5 | // Created by Mat Schmid on 2017-12-22. 6 | // Copyright © 2017 Mat Schmid. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | import SwiftyJSON 11 | 12 | class CoinTableViewCell: UITableViewCell { 13 | 14 | @IBOutlet weak var currencyNameLabel: UILabel! 15 | @IBOutlet weak var currencyPriceLabel: UILabel! 16 | @IBOutlet weak var currencyRankLabel: UILabel! 17 | @IBOutlet weak var currency24hrChangeLabel: UILabel! 18 | @IBOutlet weak var currencyArrowImageView: UIImageView! 19 | @IBOutlet weak var currencyDotSeperatorLabel: UILabel! 20 | @IBOutlet weak var currenceConversionLabel: UILabel! 21 | 22 | var coinSymbol: String? 23 | var coinName : String? 24 | var baseCurrency: BaseCurrency? 25 | 26 | func formatCellFor(currencyName: String) { 27 | 28 | let dataFetcher = CurrencyDataFetcher() 29 | dataFetcher.getDataForCurrency(currency: currencyName) { (coin) in 30 | guard let coin = coin else { 31 | print("Unable to get data for currency: \(currencyName)") 32 | return 33 | } 34 | self.currencyNameLabel.text = coin.name 35 | self.currencyRankLabel.text = "\(coin.rank)" 36 | self.currency24hrChangeLabel.text = String(format: "%0.2f%%", coin.percentChangeDaily) 37 | self.getBaseCurrency(coin: coin) 38 | self.coinSymbol = coin.symbol 39 | self.coinName = coin.name 40 | 41 | if coin.percentChangeDaily >= 0 { 42 | DispatchQueue.main.async { 43 | self.currency24hrChangeLabel.textColor = UIColor(named: "fluoGreen") 44 | self.currencyArrowImageView.tintColor = UIColor(named: "fluoGreen") 45 | self.currencyDotSeperatorLabel.textColor = UIColor(named: "fluoGreen") 46 | self.currencyArrowImageView.transform = CGAffineTransform(scaleX: 1, y: -1) 47 | } 48 | } else { 49 | DispatchQueue.main.async { 50 | self.currency24hrChangeLabel.textColor = UIColor(named: "flatRed") 51 | self.currencyArrowImageView.tintColor = UIColor(named: "flatRed") 52 | self.currencyDotSeperatorLabel.textColor = UIColor(named: "flatRed") 53 | //self.currencyArrowImageView.transform = CGAffineTransform(scaleX: 1, y: -1) 54 | } 55 | } 56 | } 57 | } 58 | 59 | func formatCellFor(coin: Currency) { 60 | self.currencyNameLabel.text = coin.name 61 | self.currencyPriceLabel.text = coin.priceCAD?.formattedCurrencyString 62 | self.currencyRankLabel.text = "\(coin.rank)" 63 | self.currency24hrChangeLabel.text = String(format: "%0.2f%%", coin.percentChangeDaily) 64 | self.getBaseCurrency(coin: coin) 65 | 66 | if coin.percentChangeDaily >= 0 { 67 | DispatchQueue.main.async { 68 | self.currency24hrChangeLabel.textColor = UIColor(named: "fluoGreen") 69 | self.currencyArrowImageView.tintColor = UIColor(named: "fluoGreen") 70 | self.currencyDotSeperatorLabel.textColor = UIColor(named: "fluoGreen") 71 | self.currencyArrowImageView.transform = CGAffineTransform(scaleX: 1, y: -1) 72 | } 73 | } else { 74 | DispatchQueue.main.async { 75 | self.currency24hrChangeLabel.textColor = UIColor(named: "flatRed") 76 | self.currencyArrowImageView.tintColor = UIColor(named: "flatRed") 77 | self.currencyDotSeperatorLabel.textColor = UIColor(named: "flatRed") 78 | //self.currencyArrowImageView.transform = CGAffineTransform(scaleX: 1, y: -1) 79 | } 80 | 81 | } 82 | } 83 | 84 | func getBaseCurrency(coin: Currency){ 85 | if let fetchedBaseCurrency = defaults.object(forKey: kBaseCurrencyKey) { 86 | self.baseCurrency = BaseCurrency(rawValue: (fetchedBaseCurrency as? String)!) 87 | } else { 88 | self.baseCurrency = BaseCurrency.CAD 89 | } 90 | 91 | switch self.baseCurrency! { 92 | case .CAD: 93 | self.currencyPriceLabel.text = coin.priceCAD?.formattedCurrencyString 94 | self.currenceConversionLabel.text = coin.symbol + "/CAD" 95 | case .USD: 96 | self.currencyPriceLabel.text = coin.priceUSD.formattedCurrencyString 97 | self.currenceConversionLabel.text = coin.symbol + "/USD" 98 | case .BTC: 99 | self.currencyPriceLabel.text = "\(coin.priceBTC)" 100 | self.currenceConversionLabel.text = coin.symbol + "/BTC" 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /Pods/Target Support Files/Pods-SwiftyCryptoDisco/Pods-SwiftyCryptoDisco-frameworks.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | 4 | echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" 5 | mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" 6 | 7 | SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" 8 | 9 | # This protects against multiple targets copying the same framework dependency at the same time. The solution 10 | # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html 11 | RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") 12 | 13 | install_framework() 14 | { 15 | if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then 16 | local source="${BUILT_PRODUCTS_DIR}/$1" 17 | elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then 18 | local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" 19 | elif [ -r "$1" ]; then 20 | local source="$1" 21 | fi 22 | 23 | local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" 24 | 25 | if [ -L "${source}" ]; then 26 | echo "Symlinked..." 27 | source="$(readlink "${source}")" 28 | fi 29 | 30 | # Use filter instead of exclude so missing patterns don't throw errors. 31 | echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" 32 | rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" 33 | 34 | local basename 35 | basename="$(basename -s .framework "$1")" 36 | binary="${destination}/${basename}.framework/${basename}" 37 | if ! [ -r "$binary" ]; then 38 | binary="${destination}/${basename}" 39 | fi 40 | 41 | # Strip invalid architectures so "fat" simulator / device frameworks work on device 42 | if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then 43 | strip_invalid_archs "$binary" 44 | fi 45 | 46 | # Resign the code if required by the build settings to avoid unstable apps 47 | code_sign_if_enabled "${destination}/$(basename "$1")" 48 | 49 | # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. 50 | if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then 51 | local swift_runtime_libs 52 | swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) 53 | for lib in $swift_runtime_libs; do 54 | echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" 55 | rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" 56 | code_sign_if_enabled "${destination}/${lib}" 57 | done 58 | fi 59 | } 60 | 61 | # Copies the dSYM of a vendored framework 62 | install_dsym() { 63 | local source="$1" 64 | if [ -r "$source" ]; then 65 | echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DWARF_DSYM_FOLDER_PATH}\"" 66 | rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DWARF_DSYM_FOLDER_PATH}" 67 | fi 68 | } 69 | 70 | # Signs a framework with the provided identity 71 | code_sign_if_enabled() { 72 | if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then 73 | # Use the current code_sign_identitiy 74 | echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" 75 | local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements '$1'" 76 | 77 | if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then 78 | code_sign_cmd="$code_sign_cmd &" 79 | fi 80 | echo "$code_sign_cmd" 81 | eval "$code_sign_cmd" 82 | fi 83 | } 84 | 85 | # Strip invalid architectures 86 | strip_invalid_archs() { 87 | binary="$1" 88 | # Get architectures for current file 89 | archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" 90 | stripped="" 91 | for arch in $archs; do 92 | if ! [[ "${ARCHS}" == *"$arch"* ]]; then 93 | # Strip non-valid architectures in-place 94 | lipo -remove "$arch" -output "$binary" "$binary" || exit 1 95 | stripped="$stripped $arch" 96 | fi 97 | done 98 | if [[ "$stripped" ]]; then 99 | echo "Stripped $binary of architectures:$stripped" 100 | fi 101 | } 102 | 103 | 104 | if [[ "$CONFIGURATION" == "Debug" ]]; then 105 | install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" 106 | install_framework "${BUILT_PRODUCTS_DIR}/SwiftyJSON/SwiftyJSON.framework" 107 | fi 108 | if [[ "$CONFIGURATION" == "Release" ]]; then 109 | install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" 110 | install_framework "${BUILT_PRODUCTS_DIR}/SwiftyJSON/SwiftyJSON.framework" 111 | fi 112 | if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then 113 | wait 114 | fi 115 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/View Controllers/SettingsTableViewController.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SettingsTableViewController.swift 3 | // SwiftyCryptoDisco 4 | // 5 | // Created by Mat Schmid on 2018-01-05. 6 | // Copyright © 2018 Mat Schmid. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | 11 | let kBaseCurrencyKey = "BaseCurrency" 12 | let kSearchableCurrenciesKey = "SearchableCurrencies" 13 | 14 | enum BaseCurrency: String { 15 | case BTC = "BTC" 16 | case USD = "USD" 17 | case CAD = "CAD" 18 | static let allValues = [BTC, USD, CAD] 19 | } 20 | 21 | protocol SettingsDelegate: class { 22 | func didChangeDefaultCurrency() 23 | } 24 | 25 | class SettingsTableViewController: UITableViewController { 26 | 27 | let NUM_SECTIONS = 2 28 | let NUM_ROWS_BASECURRENCY_SECTION = BaseCurrency.allValues.count 29 | let NUM_ROWS_SLIDER_SECTION = 1 30 | 31 | var baseCurrency: BaseCurrency? 32 | var searchableCurrencies: Int? 33 | var delegate: SettingsDelegate? 34 | 35 | let sliderCellID = "SliderCell" 36 | 37 | override func viewDidLoad() { 38 | super.viewDidLoad() 39 | 40 | let sliderCell = UINib(nibName: "SliderTableViewCell", bundle: nil) 41 | tableView.register(sliderCell, forCellReuseIdentifier: sliderCellID) 42 | 43 | getUserBaseCurrency() 44 | getUserSearchableCurrencies() 45 | } 46 | 47 | // MARK: - Table view data source 48 | override func numberOfSections(in tableView: UITableView) -> Int { 49 | return NUM_SECTIONS 50 | } 51 | 52 | override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 53 | switch section { 54 | case 0: 55 | return NUM_ROWS_BASECURRENCY_SECTION 56 | case 1: 57 | return NUM_ROWS_SLIDER_SECTION 58 | default: 59 | return 0 60 | } 61 | } 62 | 63 | override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 64 | if section == 0 { 65 | return "Select a base currency" 66 | } else if section == 1 { 67 | return "Top coins on CMC to index" 68 | } 69 | return nil 70 | } 71 | 72 | override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 73 | if indexPath.section == 0 { 74 | let cell = UITableViewCell() 75 | cell.textLabel?.text = BaseCurrency.allValues[indexPath.row].rawValue 76 | cell.backgroundColor = .black 77 | cell.textLabel?.textColor = .white 78 | if cell.textLabel?.text == baseCurrency?.rawValue { 79 | cell.accessoryType = .checkmark 80 | cell.tintColor = UIColor(named: "fluoGreen") 81 | } 82 | return cell 83 | } else { 84 | let cell = tableView.dequeueReusableCell(withIdentifier: sliderCellID, for: indexPath) as! SliderTableViewCell 85 | if searchableCurrencies == nil { 86 | getUserSearchableCurrencies() 87 | } 88 | cell.delegate = self 89 | cell.selectionStyle = .none 90 | cell.numSearchableCoinsSlider.value = Float(searchableCurrencies!) 91 | cell.numSearchableCoinsLabel.text = "TOP \(searchableCurrencies!)" 92 | return cell 93 | } 94 | } 95 | 96 | 97 | override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 98 | tableView.deselectRow(at: indexPath, animated: true) 99 | if let cell = tableView.cellForRow(at: indexPath) { 100 | if cell.accessoryType == .none, indexPath.section == 0 { 101 | resetChecks(forSection: 0) 102 | cell.accessoryType = .checkmark 103 | cell.tintColor = UIColor(named: "fluoGreen") 104 | baseCurrency = BaseCurrency.allValues[indexPath.row] 105 | defaults.set(baseCurrency?.rawValue, forKey: kBaseCurrencyKey) 106 | delegate?.didChangeDefaultCurrency() 107 | } 108 | } 109 | } 110 | 111 | //MARK: - Class Methods 112 | func resetChecks(forSection section: Int) { 113 | for j in 0.. "$RESOURCES_TO_COPY" 8 | 9 | XCASSET_FILES=() 10 | 11 | # This protects against multiple targets copying the same framework dependency at the same time. The solution 12 | # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html 13 | RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") 14 | 15 | case "${TARGETED_DEVICE_FAMILY}" in 16 | 1,2) 17 | TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" 18 | ;; 19 | 1) 20 | TARGET_DEVICE_ARGS="--target-device iphone" 21 | ;; 22 | 2) 23 | TARGET_DEVICE_ARGS="--target-device ipad" 24 | ;; 25 | 3) 26 | TARGET_DEVICE_ARGS="--target-device tv" 27 | ;; 28 | 4) 29 | TARGET_DEVICE_ARGS="--target-device watch" 30 | ;; 31 | *) 32 | TARGET_DEVICE_ARGS="--target-device mac" 33 | ;; 34 | esac 35 | 36 | install_resource() 37 | { 38 | if [[ "$1" = /* ]] ; then 39 | RESOURCE_PATH="$1" 40 | else 41 | RESOURCE_PATH="${PODS_ROOT}/$1" 42 | fi 43 | if [[ ! -e "$RESOURCE_PATH" ]] ; then 44 | cat << EOM 45 | error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. 46 | EOM 47 | exit 1 48 | fi 49 | case $RESOURCE_PATH in 50 | *.storyboard) 51 | echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" || true 52 | ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} 53 | ;; 54 | *.xib) 55 | echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" || true 56 | ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} 57 | ;; 58 | *.framework) 59 | echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true 60 | mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" 61 | echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true 62 | rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" 63 | ;; 64 | *.xcdatamodel) 65 | echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" || true 66 | xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" 67 | ;; 68 | *.xcdatamodeld) 69 | echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" || true 70 | xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" 71 | ;; 72 | *.xcmappingmodel) 73 | echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" || true 74 | xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" 75 | ;; 76 | *.xcassets) 77 | ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH" 78 | XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") 79 | ;; 80 | *) 81 | echo "$RESOURCE_PATH" || true 82 | echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" 83 | ;; 84 | esac 85 | } 86 | 87 | mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" 88 | rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" 89 | if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then 90 | mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" 91 | rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" 92 | fi 93 | rm -f "$RESOURCES_TO_COPY" 94 | 95 | if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ] 96 | then 97 | # Find all other xcassets (this unfortunately includes those of path pods and other targets). 98 | OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) 99 | while read line; do 100 | if [[ $line != "${PODS_ROOT}*" ]]; then 101 | XCASSET_FILES+=("$line") 102 | fi 103 | done <<<"$OTHER_XCASSETS" 104 | 105 | printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" 106 | fi 107 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/View Controllers/CurrencyTableViewController.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CurrencyTableViewController.swift 3 | // SwiftyCryptoDisco 4 | // 5 | // Created by Mat Schmid on 2017-12-22. 6 | // Copyright © 2017 Mat Schmid. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | 11 | protocol CurrencyTableViewDelegate: class { 12 | func didTapRefreshButton() 13 | } 14 | 15 | class CurrencyTableViewController: UITableViewController, AddCoinDelegate, SettingsDelegate { 16 | 17 | var watchedCurrencies: [String]? 18 | let kCoinCellReuseIdentifier = "CoinCell" 19 | let kDefaultCurrencyNameArrayKey = "CurrencyNames" 20 | var refreshController: UIRefreshControl? 21 | var delegate : CurrencyTableViewDelegate? 22 | var addCoinVC: AddCoinTableViewController! 23 | var settingsVC: SettingsTableViewController! 24 | 25 | //MARK: - Lifecycle methods 26 | override func viewDidLoad() { 27 | super.viewDidLoad() 28 | setupRefreshController() 29 | checkForConnection() 30 | 31 | if let userSavedCurrencies = defaults.value(forKey: kDefaultCurrencyNameArrayKey) { 32 | watchedCurrencies = userSavedCurrencies as? [String] 33 | } else { 34 | watchedCurrencies = ["bitcoin", "ethereum"] 35 | defaults.set(watchedCurrencies, forKey: kDefaultCurrencyNameArrayKey) 36 | } 37 | } 38 | 39 | override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 40 | if segue.identifier == "addVC" { 41 | addCoinVC = segue.destination as! AddCoinTableViewController 42 | addCoinVC.delegate = self 43 | } else if segue.identifier == "settingsVC" { 44 | settingsVC = segue.destination as! SettingsTableViewController 45 | settingsVC.delegate = self 46 | } 47 | } 48 | 49 | //MARK: - Class methods 50 | func checkForConnection() { 51 | tableView.isHidden = true 52 | if ConnectionManager.isConnectedToInternet() { 53 | tableView.isHidden = false 54 | } else { 55 | let alert = UIAlertController(title: "Error", message: "No internet connection detected. Please refresh the app when an internet connection is available.", preferredStyle: .alert) 56 | let okAction = UIAlertAction(title: "Okay", style: .default, handler: nil) 57 | alert.addAction(okAction) 58 | present(alert, animated: true, completion: nil) 59 | } 60 | } 61 | 62 | func setupRefreshController() { 63 | refreshController = UIRefreshControl() 64 | refreshController?.tintColor = UIColor(named: "flatBlue") 65 | refreshController?.addTarget(self, action: #selector(handleRefresh(_:)), for: UIControlEvents.valueChanged) 66 | tableView.refreshControl = refreshController 67 | } 68 | 69 | func handleRefresh(_ sender: Any?) { 70 | checkForConnection() 71 | tableView.reloadData() 72 | delegate?.didTapRefreshButton() 73 | refreshController?.endRefreshing() 74 | } 75 | 76 | // MARK: - Table view data source & delegate 77 | override func numberOfSections(in tableView: UITableView) -> Int { 78 | return 1 79 | } 80 | 81 | override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 82 | return watchedCurrencies!.count 83 | } 84 | 85 | override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 86 | return 66 87 | } 88 | 89 | override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 90 | let cell = self.tableView.dequeueReusableCell(withIdentifier: kCoinCellReuseIdentifier) as! CoinTableViewCell 91 | cell.formatCellFor(currencyName: watchedCurrencies![indexPath.row]) 92 | return cell 93 | } 94 | 95 | override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { 96 | let deleteAction = UITableViewRowAction(style: .normal, title: "Delete") { (action: UITableViewRowAction, indexPath:IndexPath) in 97 | self.watchedCurrencies!.remove(at: indexPath.row) 98 | defaults.set(self.watchedCurrencies, forKey: self.kDefaultCurrencyNameArrayKey) 99 | self.tableView.reloadData() 100 | } 101 | deleteAction.backgroundColor = UIColor(named: "flatRed") 102 | 103 | let watchAction = UITableViewRowAction(style: .normal, title: "Share") { (action: UITableViewRowAction, indexPath:IndexPath) in 104 | //TODO: add watch functionality 105 | } 106 | watchAction.backgroundColor = UIColor(named: "flatBlue") 107 | return [deleteAction, watchAction] 108 | } 109 | 110 | override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 111 | let coinDataVC = storyboard?.instantiateViewController(withIdentifier: "coinDataVC") as! CoinDataViewController 112 | let cell = tableView.cellForRow(at: indexPath) as! CoinTableViewCell 113 | coinDataVC.coinSymbol = cell.coinSymbol! 114 | coinDataVC.coinName = cell.coinName! 115 | navigationController?.pushViewController(coinDataVC, animated: true) 116 | } 117 | 118 | //MARK: - AddCoinDelegate 119 | func didTapCoinWithID(id: String) { 120 | if !(watchedCurrencies?.contains(id))! { 121 | watchedCurrencies!.append(id) 122 | defaults.set(watchedCurrencies, forKey: kDefaultCurrencyNameArrayKey) 123 | tableView.reloadData() 124 | } else { 125 | let alert = UIAlertController(title: "Error", message: "Currency already being monitored", preferredStyle: .alert) 126 | let okAction = UIAlertAction(title: "Okay", style: .default, handler: nil) 127 | alert.addAction(okAction) 128 | present(alert, animated: true, completion: nil) 129 | } 130 | } 131 | 132 | //MARK: - SettingsDelegate 133 | func didChangeDefaultCurrency() { 134 | handleRefresh(nil) 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/Views/SliderTableViewCell.xib: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 43 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /SwiftyCryptoDisco/View Controllers/CoinDataViewController.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CoinDataViewController.swift 3 | // SwiftyCryptoDisco 4 | // 5 | // Created by Mat Schmid on 2018-01-09. 6 | // Copyright © 2018 Mat Schmid. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | 11 | class CoinDataViewController: UIViewController { 12 | 13 | @IBOutlet weak var ohlcvTableView: UITableView! 14 | @IBOutlet weak var coinTableView: UITableView! 15 | @IBOutlet weak var sellButton: UIButton! 16 | @IBOutlet weak var buyButton: UIButton! 17 | @IBOutlet weak var timeSpanStackView: UIStackView! 18 | @IBOutlet weak var selectedTimeSpanView: UIView! 19 | @IBOutlet weak var selectedTimeSpanXConstraint: NSLayoutConstraint! 20 | 21 | let kOHLCVCellReuseIdentifier = "OHLCVCell" 22 | let kCoinCellReuseIdentifier = "CoinCell" 23 | var coinSymbol: String? 24 | var coinName: String? 25 | var baseCurrency: BaseCurrency? 26 | var currentMarket: MarketExchange? 27 | var currentOHLCVValues: [OHLCV]? 28 | let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) 29 | var selectedTimeSpan: Period? 30 | 31 | //MARK: - Lifecycle Methods 32 | override func viewDidLoad() { 33 | super.viewDidLoad() 34 | 35 | setupNavBarTitle() 36 | setupUIElementsAndProperties() 37 | receiveMarketDataForSymbol(coinSymbol: coinSymbol!) 38 | } 39 | 40 | //MARK: - Setup methods 41 | func setupNavBarTitle() { 42 | if let fetchedBaseCurrency = defaults.object(forKey: kBaseCurrencyKey) { 43 | baseCurrency = BaseCurrency(rawValue: (fetchedBaseCurrency as? String)!)! 44 | } else { 45 | baseCurrency = BaseCurrency.CAD 46 | } 47 | self.title = "\(coinSymbol!)/\(baseCurrency!.rawValue)" 48 | } 49 | 50 | func setupUIElementsAndProperties() { 51 | activityIndicator.hidesWhenStopped = true 52 | activityIndicator.center = CGPoint(x: view.frame.width / 2, y: view.frame.height / 2 - 78) 53 | self.view.addSubview(activityIndicator) 54 | activityIndicator.startAnimating() 55 | 56 | sellButton.layer.cornerRadius = 4 57 | buyButton.layer.cornerRadius = 4 58 | selectedTimeSpanView.layer.cornerRadius = 1 59 | 60 | ohlcvTableView.dataSource = self 61 | ohlcvTableView.delegate = self 62 | coinTableView.dataSource = self 63 | coinTableView.delegate = self 64 | coinTableView.isScrollEnabled = false 65 | 66 | selectedTimeSpan = Period.ONEDAY 67 | self.ohlcvTableView.isHidden = true 68 | } 69 | 70 | //MARK: - Data Retrieval 71 | func receiveMarketDataForSymbol(coinSymbol: String) { 72 | let marketDataFetcher = MarketDataFetcher() 73 | marketDataFetcher.getMarketDataForBaseCurrency(coinCurrency: coinSymbol, baseCurrency: baseCurrency!.rawValue) { (markets) in 74 | guard let marketsForCoin = markets, marketsForCoin.count > 0 else { 75 | let alert = UIAlertController(title: "Error", message: "No exchanges available for currency \(self.coinSymbol!)", preferredStyle: .alert) 76 | let okAction = UIAlertAction(title: "Okay", style: .default, handler: { (action) in 77 | self.navigationController?.popToRootViewController(animated: true) 78 | self.activityIndicator.stopAnimating() 79 | }) 80 | alert.addAction(okAction) 81 | self.present(alert, animated: true, completion: nil) 82 | return 83 | } 84 | self.currentMarket = marketsForCoin[0] 85 | self.receiveOHLCVDataFromMarket(market: self.currentMarket!) 86 | } 87 | } 88 | 89 | func receiveOHLCVDataFromMarket(market: MarketExchange) { 90 | let marketDataFetcher = MarketDataFetcher() 91 | marketDataFetcher.getOHLCVDataForSymbol(symbol: market.symbolID, period: selectedTimeSpan!) { (OHLCVArray) in 92 | guard let arrayOfOHLCV = OHLCVArray else { 93 | let alert = UIAlertController(title: "Error", message: "No market data available for currency \(self.coinSymbol!)", preferredStyle: .alert) 94 | let okAction = UIAlertAction(title: "Okay", style: .default, handler: { (action) in 95 | self.navigationController?.popToRootViewController(animated: true) 96 | self.activityIndicator.stopAnimating() 97 | }) 98 | alert.addAction(okAction) 99 | self.present(alert, animated: true, completion: nil) 100 | return 101 | } 102 | self.currentOHLCVValues = arrayOfOHLCV 103 | self.activityIndicator.stopAnimating() 104 | self.ohlcvTableView.reloadData() 105 | self.coinTableView.reloadData() 106 | self.ohlcvTableView.isHidden = false 107 | } 108 | } 109 | 110 | //MARK: - Event Handlers 111 | @IBAction func didTapTimeSpanButton(_ sender: UIButton) { 112 | DispatchQueue.main.async { 113 | self.selectedTimeSpanXConstraint.isActive = false 114 | self.selectedTimeSpanXConstraint = self.selectedTimeSpanView.centerXAnchor.constraint(equalTo: (self.timeSpanStackView.viewWithTag(sender.tag) as! UIButton).centerXAnchor) 115 | self.selectedTimeSpanXConstraint.isActive = true 116 | UIView.animate(withDuration: 0.5) { 117 | self.view.layoutIfNeeded() 118 | } 119 | } 120 | selectedTimeSpan = Period.allValues[sender.tag - 1] 121 | ohlcvTableView.isHidden = true 122 | activityIndicator.startAnimating() 123 | receiveOHLCVDataFromMarket(market: currentMarket!) 124 | } 125 | 126 | } 127 | 128 | //MARK: - TableView Delegata & Data Source Methods 129 | extension CoinDataViewController: UITableViewDataSource, UITableViewDelegate { 130 | func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 131 | if tableView == ohlcvTableView { 132 | if currentOHLCVValues != nil { 133 | return (currentOHLCVValues?.count)! 134 | } 135 | return 0 136 | } else { 137 | return 1 138 | } 139 | } 140 | 141 | func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 142 | if tableView == ohlcvTableView { 143 | let cell = ohlcvTableView.dequeueReusableCell(withIdentifier: kOHLCVCellReuseIdentifier, for: indexPath) as! OHLCVTableViewCell 144 | cell.formatCellWithOHLCV(ohlcv: currentOHLCVValues![indexPath.row]) 145 | return cell 146 | } else { 147 | let cell = coinTableView.dequeueReusableCell(withIdentifier: kCoinCellReuseIdentifier) as! CoinTableViewCell 148 | cell.formatCellFor(currencyName: coinName!) 149 | return cell 150 | } 151 | } 152 | 153 | func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 154 | if tableView == ohlcvTableView { 155 | return 72 156 | } else { 157 | return 66 158 | } 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /Pods/Alamofire/Source/Timeline.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Timeline.swift 3 | // 4 | // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | // 24 | 25 | import Foundation 26 | 27 | /// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. 28 | public struct Timeline { 29 | /// The time the request was initialized. 30 | public let requestStartTime: CFAbsoluteTime 31 | 32 | /// The time the first bytes were received from or sent to the server. 33 | public let initialResponseTime: CFAbsoluteTime 34 | 35 | /// The time when the request was completed. 36 | public let requestCompletedTime: CFAbsoluteTime 37 | 38 | /// The time when the response serialization was completed. 39 | public let serializationCompletedTime: CFAbsoluteTime 40 | 41 | /// The time interval in seconds from the time the request started to the initial response from the server. 42 | public let latency: TimeInterval 43 | 44 | /// The time interval in seconds from the time the request started to the time the request completed. 45 | public let requestDuration: TimeInterval 46 | 47 | /// The time interval in seconds from the time the request completed to the time response serialization completed. 48 | public let serializationDuration: TimeInterval 49 | 50 | /// The time interval in seconds from the time the request started to the time response serialization completed. 51 | public let totalDuration: TimeInterval 52 | 53 | /// Creates a new `Timeline` instance with the specified request times. 54 | /// 55 | /// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. 56 | /// - parameter initialResponseTime: The time the first bytes were received from or sent to the server. 57 | /// Defaults to `0.0`. 58 | /// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. 59 | /// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults 60 | /// to `0.0`. 61 | /// 62 | /// - returns: The new `Timeline` instance. 63 | public init( 64 | requestStartTime: CFAbsoluteTime = 0.0, 65 | initialResponseTime: CFAbsoluteTime = 0.0, 66 | requestCompletedTime: CFAbsoluteTime = 0.0, 67 | serializationCompletedTime: CFAbsoluteTime = 0.0) 68 | { 69 | self.requestStartTime = requestStartTime 70 | self.initialResponseTime = initialResponseTime 71 | self.requestCompletedTime = requestCompletedTime 72 | self.serializationCompletedTime = serializationCompletedTime 73 | 74 | self.latency = initialResponseTime - requestStartTime 75 | self.requestDuration = requestCompletedTime - requestStartTime 76 | self.serializationDuration = serializationCompletedTime - requestCompletedTime 77 | self.totalDuration = serializationCompletedTime - requestStartTime 78 | } 79 | } 80 | 81 | // MARK: - CustomStringConvertible 82 | 83 | extension Timeline: CustomStringConvertible { 84 | /// The textual representation used when written to an output stream, which includes the latency, the request 85 | /// duration and the total duration. 86 | public var description: String { 87 | let latency = String(format: "%.3f", self.latency) 88 | let requestDuration = String(format: "%.3f", self.requestDuration) 89 | let serializationDuration = String(format: "%.3f", self.serializationDuration) 90 | let totalDuration = String(format: "%.3f", self.totalDuration) 91 | 92 | // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is 93 | // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. 94 | let timings = [ 95 | "\"Latency\": " + latency + " secs", 96 | "\"Request Duration\": " + requestDuration + " secs", 97 | "\"Serialization Duration\": " + serializationDuration + " secs", 98 | "\"Total Duration\": " + totalDuration + " secs" 99 | ] 100 | 101 | return "Timeline: { " + timings.joined(separator: ", ") + " }" 102 | } 103 | } 104 | 105 | // MARK: - CustomDebugStringConvertible 106 | 107 | extension Timeline: CustomDebugStringConvertible { 108 | /// The textual representation used when written to an output stream, which includes the request start time, the 109 | /// initial response time, the request completed time, the serialization completed time, the latency, the request 110 | /// duration and the total duration. 111 | public var debugDescription: String { 112 | let requestStartTime = String(format: "%.3f", self.requestStartTime) 113 | let initialResponseTime = String(format: "%.3f", self.initialResponseTime) 114 | let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) 115 | let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) 116 | let latency = String(format: "%.3f", self.latency) 117 | let requestDuration = String(format: "%.3f", self.requestDuration) 118 | let serializationDuration = String(format: "%.3f", self.serializationDuration) 119 | let totalDuration = String(format: "%.3f", self.totalDuration) 120 | 121 | // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is 122 | // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. 123 | let timings = [ 124 | "\"Request Start Time\": " + requestStartTime, 125 | "\"Initial Response Time\": " + initialResponseTime, 126 | "\"Request Completed Time\": " + requestCompletedTime, 127 | "\"Serialization Completed Time\": " + serializationCompletedTime, 128 | "\"Latency\": " + latency + " secs", 129 | "\"Request Duration\": " + requestDuration + " secs", 130 | "\"Serialization Duration\": " + serializationDuration + " secs", 131 | "\"Total Duration\": " + totalDuration + " secs" 132 | ] 133 | 134 | return "Timeline: { " + timings.joined(separator: ", ") + " }" 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /Pods/Alamofire/Source/NetworkReachabilityManager.swift: -------------------------------------------------------------------------------- 1 | // 2 | // NetworkReachabilityManager.swift 3 | // 4 | // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | // 24 | 25 | #if !os(watchOS) 26 | 27 | import Foundation 28 | import SystemConfiguration 29 | 30 | /// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and 31 | /// WiFi network interfaces. 32 | /// 33 | /// Reachability can be used to determine background information about why a network operation failed, or to retry 34 | /// network requests when a connection is established. It should not be used to prevent a user from initiating a network 35 | /// request, as it's possible that an initial request may be required to establish reachability. 36 | public class NetworkReachabilityManager { 37 | /// Defines the various states of network reachability. 38 | /// 39 | /// - unknown: It is unknown whether the network is reachable. 40 | /// - notReachable: The network is not reachable. 41 | /// - reachable: The network is reachable. 42 | public enum NetworkReachabilityStatus { 43 | case unknown 44 | case notReachable 45 | case reachable(ConnectionType) 46 | } 47 | 48 | /// Defines the various connection types detected by reachability flags. 49 | /// 50 | /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi. 51 | /// - wwan: The connection type is a WWAN connection. 52 | public enum ConnectionType { 53 | case ethernetOrWiFi 54 | case wwan 55 | } 56 | 57 | /// A closure executed when the network reachability status changes. The closure takes a single argument: the 58 | /// network reachability status. 59 | public typealias Listener = (NetworkReachabilityStatus) -> Void 60 | 61 | // MARK: - Properties 62 | 63 | /// Whether the network is currently reachable. 64 | public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } 65 | 66 | /// Whether the network is currently reachable over the WWAN interface. 67 | public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) } 68 | 69 | /// Whether the network is currently reachable over Ethernet or WiFi interface. 70 | public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } 71 | 72 | /// The current network reachability status. 73 | public var networkReachabilityStatus: NetworkReachabilityStatus { 74 | guard let flags = self.flags else { return .unknown } 75 | return networkReachabilityStatusForFlags(flags) 76 | } 77 | 78 | /// The dispatch queue to execute the `listener` closure on. 79 | public var listenerQueue: DispatchQueue = DispatchQueue.main 80 | 81 | /// A closure executed when the network reachability status changes. 82 | public var listener: Listener? 83 | 84 | private var flags: SCNetworkReachabilityFlags? { 85 | var flags = SCNetworkReachabilityFlags() 86 | 87 | if SCNetworkReachabilityGetFlags(reachability, &flags) { 88 | return flags 89 | } 90 | 91 | return nil 92 | } 93 | 94 | private let reachability: SCNetworkReachability 95 | private var previousFlags: SCNetworkReachabilityFlags 96 | 97 | // MARK: - Initialization 98 | 99 | /// Creates a `NetworkReachabilityManager` instance with the specified host. 100 | /// 101 | /// - parameter host: The host used to evaluate network reachability. 102 | /// 103 | /// - returns: The new `NetworkReachabilityManager` instance. 104 | public convenience init?(host: String) { 105 | guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } 106 | self.init(reachability: reachability) 107 | } 108 | 109 | /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. 110 | /// 111 | /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing 112 | /// status of the device, both IPv4 and IPv6. 113 | /// 114 | /// - returns: The new `NetworkReachabilityManager` instance. 115 | public convenience init?() { 116 | var address = sockaddr_in() 117 | address.sin_len = UInt8(MemoryLayout.size) 118 | address.sin_family = sa_family_t(AF_INET) 119 | 120 | guard let reachability = withUnsafePointer(to: &address, { pointer in 121 | return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout.size) { 122 | return SCNetworkReachabilityCreateWithAddress(nil, $0) 123 | } 124 | }) else { return nil } 125 | 126 | self.init(reachability: reachability) 127 | } 128 | 129 | private init(reachability: SCNetworkReachability) { 130 | self.reachability = reachability 131 | self.previousFlags = SCNetworkReachabilityFlags() 132 | } 133 | 134 | deinit { 135 | stopListening() 136 | } 137 | 138 | // MARK: - Listening 139 | 140 | /// Starts listening for changes in network reachability status. 141 | /// 142 | /// - returns: `true` if listening was started successfully, `false` otherwise. 143 | @discardableResult 144 | public func startListening() -> Bool { 145 | var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) 146 | context.info = Unmanaged.passUnretained(self).toOpaque() 147 | 148 | let callbackEnabled = SCNetworkReachabilitySetCallback( 149 | reachability, 150 | { (_, flags, info) in 151 | let reachability = Unmanaged.fromOpaque(info!).takeUnretainedValue() 152 | reachability.notifyListener(flags) 153 | }, 154 | &context 155 | ) 156 | 157 | let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) 158 | 159 | listenerQueue.async { 160 | self.previousFlags = SCNetworkReachabilityFlags() 161 | self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) 162 | } 163 | 164 | return callbackEnabled && queueEnabled 165 | } 166 | 167 | /// Stops listening for changes in network reachability status. 168 | public func stopListening() { 169 | SCNetworkReachabilitySetCallback(reachability, nil, nil) 170 | SCNetworkReachabilitySetDispatchQueue(reachability, nil) 171 | } 172 | 173 | // MARK: - Internal - Listener Notification 174 | 175 | func notifyListener(_ flags: SCNetworkReachabilityFlags) { 176 | guard previousFlags != flags else { return } 177 | previousFlags = flags 178 | 179 | listener?(networkReachabilityStatusForFlags(flags)) 180 | } 181 | 182 | // MARK: - Internal - Network Reachability Status 183 | 184 | func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { 185 | guard isNetworkReachable(with: flags) else { return .notReachable } 186 | 187 | var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) 188 | 189 | #if os(iOS) 190 | if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) } 191 | #endif 192 | 193 | return networkStatus 194 | } 195 | 196 | func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool { 197 | let isReachable = flags.contains(.reachable) 198 | let needsConnection = flags.contains(.connectionRequired) 199 | let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) 200 | let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired) 201 | 202 | return isReachable && (!needsConnection || canConnectWithoutUserInteraction) 203 | } 204 | } 205 | 206 | // MARK: - 207 | 208 | extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} 209 | 210 | /// Returns whether the two network reachability status values are equal. 211 | /// 212 | /// - parameter lhs: The left-hand side value to compare. 213 | /// - parameter rhs: The right-hand side value to compare. 214 | /// 215 | /// - returns: `true` if the two values are equal, `false` otherwise. 216 | public func ==( 217 | lhs: NetworkReachabilityManager.NetworkReachabilityStatus, 218 | rhs: NetworkReachabilityManager.NetworkReachabilityStatus) 219 | -> Bool 220 | { 221 | switch (lhs, rhs) { 222 | case (.unknown, .unknown): 223 | return true 224 | case (.notReachable, .notReachable): 225 | return true 226 | case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)): 227 | return lhsConnectionType == rhsConnectionType 228 | default: 229 | return false 230 | } 231 | } 232 | 233 | #endif 234 | -------------------------------------------------------------------------------- /Pods/Alamofire/Source/Result.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Result.swift 3 | // 4 | // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | // 24 | 25 | import Foundation 26 | 27 | /// Used to represent whether a request was successful or encountered an error. 28 | /// 29 | /// - success: The request and all post processing operations were successful resulting in the serialization of the 30 | /// provided associated value. 31 | /// 32 | /// - failure: The request encountered an error resulting in a failure. The associated values are the original data 33 | /// provided by the server as well as the error that caused the failure. 34 | public enum Result { 35 | case success(Value) 36 | case failure(Error) 37 | 38 | /// Returns `true` if the result is a success, `false` otherwise. 39 | public var isSuccess: Bool { 40 | switch self { 41 | case .success: 42 | return true 43 | case .failure: 44 | return false 45 | } 46 | } 47 | 48 | /// Returns `true` if the result is a failure, `false` otherwise. 49 | public var isFailure: Bool { 50 | return !isSuccess 51 | } 52 | 53 | /// Returns the associated value if the result is a success, `nil` otherwise. 54 | public var value: Value? { 55 | switch self { 56 | case .success(let value): 57 | return value 58 | case .failure: 59 | return nil 60 | } 61 | } 62 | 63 | /// Returns the associated error value if the result is a failure, `nil` otherwise. 64 | public var error: Error? { 65 | switch self { 66 | case .success: 67 | return nil 68 | case .failure(let error): 69 | return error 70 | } 71 | } 72 | } 73 | 74 | // MARK: - CustomStringConvertible 75 | 76 | extension Result: CustomStringConvertible { 77 | /// The textual representation used when written to an output stream, which includes whether the result was a 78 | /// success or failure. 79 | public var description: String { 80 | switch self { 81 | case .success: 82 | return "SUCCESS" 83 | case .failure: 84 | return "FAILURE" 85 | } 86 | } 87 | } 88 | 89 | // MARK: - CustomDebugStringConvertible 90 | 91 | extension Result: CustomDebugStringConvertible { 92 | /// The debug textual representation used when written to an output stream, which includes whether the result was a 93 | /// success or failure in addition to the value or error. 94 | public var debugDescription: String { 95 | switch self { 96 | case .success(let value): 97 | return "SUCCESS: \(value)" 98 | case .failure(let error): 99 | return "FAILURE: \(error)" 100 | } 101 | } 102 | } 103 | 104 | // MARK: - Functional APIs 105 | 106 | extension Result { 107 | /// Creates a `Result` instance from the result of a closure. 108 | /// 109 | /// A failure result is created when the closure throws, and a success result is created when the closure 110 | /// succeeds without throwing an error. 111 | /// 112 | /// func someString() throws -> String { ... } 113 | /// 114 | /// let result = Result(value: { 115 | /// return try someString() 116 | /// }) 117 | /// 118 | /// // The type of result is Result 119 | /// 120 | /// The trailing closure syntax is also supported: 121 | /// 122 | /// let result = Result { try someString() } 123 | /// 124 | /// - parameter value: The closure to execute and create the result for. 125 | public init(value: () throws -> Value) { 126 | do { 127 | self = try .success(value()) 128 | } catch { 129 | self = .failure(error) 130 | } 131 | } 132 | 133 | /// Returns the success value, or throws the failure error. 134 | /// 135 | /// let possibleString: Result = .success("success") 136 | /// try print(possibleString.unwrap()) 137 | /// // Prints "success" 138 | /// 139 | /// let noString: Result = .failure(error) 140 | /// try print(noString.unwrap()) 141 | /// // Throws error 142 | public func unwrap() throws -> Value { 143 | switch self { 144 | case .success(let value): 145 | return value 146 | case .failure(let error): 147 | throw error 148 | } 149 | } 150 | 151 | /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. 152 | /// 153 | /// Use the `map` method with a closure that does not throw. For example: 154 | /// 155 | /// let possibleData: Result = .success(Data()) 156 | /// let possibleInt = possibleData.map { $0.count } 157 | /// try print(possibleInt.unwrap()) 158 | /// // Prints "0" 159 | /// 160 | /// let noData: Result = .failure(error) 161 | /// let noInt = noData.map { $0.count } 162 | /// try print(noInt.unwrap()) 163 | /// // Throws error 164 | /// 165 | /// - parameter transform: A closure that takes the success value of the `Result` instance. 166 | /// 167 | /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the 168 | /// same failure. 169 | public func map(_ transform: (Value) -> T) -> Result { 170 | switch self { 171 | case .success(let value): 172 | return .success(transform(value)) 173 | case .failure(let error): 174 | return .failure(error) 175 | } 176 | } 177 | 178 | /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. 179 | /// 180 | /// Use the `flatMap` method with a closure that may throw an error. For example: 181 | /// 182 | /// let possibleData: Result = .success(Data(...)) 183 | /// let possibleObject = possibleData.flatMap { 184 | /// try JSONSerialization.jsonObject(with: $0) 185 | /// } 186 | /// 187 | /// - parameter transform: A closure that takes the success value of the instance. 188 | /// 189 | /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the 190 | /// same failure. 191 | public func flatMap(_ transform: (Value) throws -> T) -> Result { 192 | switch self { 193 | case .success(let value): 194 | do { 195 | return try .success(transform(value)) 196 | } catch { 197 | return .failure(error) 198 | } 199 | case .failure(let error): 200 | return .failure(error) 201 | } 202 | } 203 | 204 | /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. 205 | /// 206 | /// Use the `mapError` function with a closure that does not throw. For example: 207 | /// 208 | /// let possibleData: Result = .failure(someError) 209 | /// let withMyError: Result = possibleData.mapError { MyError.error($0) } 210 | /// 211 | /// - Parameter transform: A closure that takes the error of the instance. 212 | /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns 213 | /// the same instance. 214 | public func mapError(_ transform: (Error) -> T) -> Result { 215 | switch self { 216 | case .failure(let error): 217 | return .failure(transform(error)) 218 | case .success: 219 | return self 220 | } 221 | } 222 | 223 | /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. 224 | /// 225 | /// Use the `flatMapError` function with a closure that may throw an error. For example: 226 | /// 227 | /// let possibleData: Result = .success(Data(...)) 228 | /// let possibleObject = possibleData.flatMapError { 229 | /// try someFailableFunction(taking: $0) 230 | /// } 231 | /// 232 | /// - Parameter transform: A throwing closure that takes the error of the instance. 233 | /// 234 | /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns 235 | /// the same instance. 236 | public func flatMapError(_ transform: (Error) throws -> T) -> Result { 237 | switch self { 238 | case .failure(let error): 239 | do { 240 | return try .failure(transform(error)) 241 | } catch { 242 | return .failure(error) 243 | } 244 | case .success: 245 | return self 246 | } 247 | } 248 | 249 | /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. 250 | /// 251 | /// Use the `withValue` function to evaluate the passed closure without modifying the `Result` instance. 252 | /// 253 | /// - Parameter closure: A closure that takes the success value of this instance. 254 | /// - Returns: This `Result` instance, unmodified. 255 | @discardableResult 256 | public func withValue(_ closure: (Value) -> Void) -> Result { 257 | if case let .success(value) = self { closure(value) } 258 | 259 | return self 260 | } 261 | 262 | /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. 263 | /// 264 | /// Use the `withError` function to evaluate the passed closure without modifying the `Result` instance. 265 | /// 266 | /// - Parameter closure: A closure that takes the success value of this instance. 267 | /// - Returns: This `Result` instance, unmodified. 268 | @discardableResult 269 | public func withError(_ closure: (Error) -> Void) -> Result { 270 | if case let .failure(error) = self { closure(error) } 271 | 272 | return self 273 | } 274 | 275 | /// Evaluates the specified closure when the `Result` is a success. 276 | /// 277 | /// Use the `ifSuccess` function to evaluate the passed closure without modifying the `Result` instance. 278 | /// 279 | /// - Parameter closure: A `Void` closure. 280 | /// - Returns: This `Result` instance, unmodified. 281 | @discardableResult 282 | public func ifSuccess(_ closure: () -> Void) -> Result { 283 | if isSuccess { closure() } 284 | 285 | return self 286 | } 287 | 288 | /// Evaluates the specified closure when the `Result` is a failure. 289 | /// 290 | /// Use the `ifFailure` function to evaluate the passed closure without modifying the `Result` instance. 291 | /// 292 | /// - Parameter closure: A `Void` closure. 293 | /// - Returns: This `Result` instance, unmodified. 294 | @discardableResult 295 | public func ifFailure(_ closure: () -> Void) -> Result { 296 | if isFailure { closure() } 297 | 298 | return self 299 | } 300 | } 301 | -------------------------------------------------------------------------------- /Pods/Alamofire/Source/Validation.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Validation.swift 3 | // 4 | // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | // 24 | 25 | import Foundation 26 | 27 | extension Request { 28 | 29 | // MARK: Helper Types 30 | 31 | fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason 32 | 33 | /// Used to represent whether validation was successful or encountered an error resulting in a failure. 34 | /// 35 | /// - success: The validation was successful. 36 | /// - failure: The validation failed encountering the provided error. 37 | public enum ValidationResult { 38 | case success 39 | case failure(Error) 40 | } 41 | 42 | fileprivate struct MIMEType { 43 | let type: String 44 | let subtype: String 45 | 46 | var isWildcard: Bool { return type == "*" && subtype == "*" } 47 | 48 | init?(_ string: String) { 49 | let components: [String] = { 50 | let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) 51 | 52 | #if swift(>=3.2) 53 | let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)] 54 | #else 55 | let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex) 56 | #endif 57 | 58 | return split.components(separatedBy: "/") 59 | }() 60 | 61 | if let type = components.first, let subtype = components.last { 62 | self.type = type 63 | self.subtype = subtype 64 | } else { 65 | return nil 66 | } 67 | } 68 | 69 | func matches(_ mime: MIMEType) -> Bool { 70 | switch (type, subtype) { 71 | case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): 72 | return true 73 | default: 74 | return false 75 | } 76 | } 77 | } 78 | 79 | // MARK: Properties 80 | 81 | fileprivate var acceptableStatusCodes: [Int] { return Array(200..<300) } 82 | 83 | fileprivate var acceptableContentTypes: [String] { 84 | if let accept = request?.value(forHTTPHeaderField: "Accept") { 85 | return accept.components(separatedBy: ",") 86 | } 87 | 88 | return ["*/*"] 89 | } 90 | 91 | // MARK: Status Code 92 | 93 | fileprivate func validate( 94 | statusCode acceptableStatusCodes: S, 95 | response: HTTPURLResponse) 96 | -> ValidationResult 97 | where S.Iterator.Element == Int 98 | { 99 | if acceptableStatusCodes.contains(response.statusCode) { 100 | return .success 101 | } else { 102 | let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) 103 | return .failure(AFError.responseValidationFailed(reason: reason)) 104 | } 105 | } 106 | 107 | // MARK: Content Type 108 | 109 | fileprivate func validate( 110 | contentType acceptableContentTypes: S, 111 | response: HTTPURLResponse, 112 | data: Data?) 113 | -> ValidationResult 114 | where S.Iterator.Element == String 115 | { 116 | guard let data = data, data.count > 0 else { return .success } 117 | 118 | guard 119 | let responseContentType = response.mimeType, 120 | let responseMIMEType = MIMEType(responseContentType) 121 | else { 122 | for contentType in acceptableContentTypes { 123 | if let mimeType = MIMEType(contentType), mimeType.isWildcard { 124 | return .success 125 | } 126 | } 127 | 128 | let error: AFError = { 129 | let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) 130 | return AFError.responseValidationFailed(reason: reason) 131 | }() 132 | 133 | return .failure(error) 134 | } 135 | 136 | for contentType in acceptableContentTypes { 137 | if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { 138 | return .success 139 | } 140 | } 141 | 142 | let error: AFError = { 143 | let reason: ErrorReason = .unacceptableContentType( 144 | acceptableContentTypes: Array(acceptableContentTypes), 145 | responseContentType: responseContentType 146 | ) 147 | 148 | return AFError.responseValidationFailed(reason: reason) 149 | }() 150 | 151 | return .failure(error) 152 | } 153 | } 154 | 155 | // MARK: - 156 | 157 | extension DataRequest { 158 | /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the 159 | /// request was valid. 160 | public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult 161 | 162 | /// Validates the request, using the specified closure. 163 | /// 164 | /// If validation fails, subsequent calls to response handlers will have an associated error. 165 | /// 166 | /// - parameter validation: A closure to validate the request. 167 | /// 168 | /// - returns: The request. 169 | @discardableResult 170 | public func validate(_ validation: @escaping Validation) -> Self { 171 | let validationExecution: () -> Void = { [unowned self] in 172 | if 173 | let response = self.response, 174 | self.delegate.error == nil, 175 | case let .failure(error) = validation(self.request, response, self.delegate.data) 176 | { 177 | self.delegate.error = error 178 | } 179 | } 180 | 181 | validations.append(validationExecution) 182 | 183 | return self 184 | } 185 | 186 | /// Validates that the response has a status code in the specified sequence. 187 | /// 188 | /// If validation fails, subsequent calls to response handlers will have an associated error. 189 | /// 190 | /// - parameter range: The range of acceptable status codes. 191 | /// 192 | /// - returns: The request. 193 | @discardableResult 194 | public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { 195 | return validate { [unowned self] _, response, _ in 196 | return self.validate(statusCode: acceptableStatusCodes, response: response) 197 | } 198 | } 199 | 200 | /// Validates that the response has a content type in the specified sequence. 201 | /// 202 | /// If validation fails, subsequent calls to response handlers will have an associated error. 203 | /// 204 | /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. 205 | /// 206 | /// - returns: The request. 207 | @discardableResult 208 | public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { 209 | return validate { [unowned self] _, response, data in 210 | return self.validate(contentType: acceptableContentTypes, response: response, data: data) 211 | } 212 | } 213 | 214 | /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content 215 | /// type matches any specified in the Accept HTTP header field. 216 | /// 217 | /// If validation fails, subsequent calls to response handlers will have an associated error. 218 | /// 219 | /// - returns: The request. 220 | @discardableResult 221 | public func validate() -> Self { 222 | return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) 223 | } 224 | } 225 | 226 | // MARK: - 227 | 228 | extension DownloadRequest { 229 | /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a 230 | /// destination URL, and returns whether the request was valid. 231 | public typealias Validation = ( 232 | _ request: URLRequest?, 233 | _ response: HTTPURLResponse, 234 | _ temporaryURL: URL?, 235 | _ destinationURL: URL?) 236 | -> ValidationResult 237 | 238 | /// Validates the request, using the specified closure. 239 | /// 240 | /// If validation fails, subsequent calls to response handlers will have an associated error. 241 | /// 242 | /// - parameter validation: A closure to validate the request. 243 | /// 244 | /// - returns: The request. 245 | @discardableResult 246 | public func validate(_ validation: @escaping Validation) -> Self { 247 | let validationExecution: () -> Void = { [unowned self] in 248 | let request = self.request 249 | let temporaryURL = self.downloadDelegate.temporaryURL 250 | let destinationURL = self.downloadDelegate.destinationURL 251 | 252 | if 253 | let response = self.response, 254 | self.delegate.error == nil, 255 | case let .failure(error) = validation(request, response, temporaryURL, destinationURL) 256 | { 257 | self.delegate.error = error 258 | } 259 | } 260 | 261 | validations.append(validationExecution) 262 | 263 | return self 264 | } 265 | 266 | /// Validates that the response has a status code in the specified sequence. 267 | /// 268 | /// If validation fails, subsequent calls to response handlers will have an associated error. 269 | /// 270 | /// - parameter range: The range of acceptable status codes. 271 | /// 272 | /// - returns: The request. 273 | @discardableResult 274 | public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { 275 | return validate { [unowned self] _, response, _, _ in 276 | return self.validate(statusCode: acceptableStatusCodes, response: response) 277 | } 278 | } 279 | 280 | /// Validates that the response has a content type in the specified sequence. 281 | /// 282 | /// If validation fails, subsequent calls to response handlers will have an associated error. 283 | /// 284 | /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. 285 | /// 286 | /// - returns: The request. 287 | @discardableResult 288 | public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { 289 | return validate { [unowned self] _, response, _, _ in 290 | let fileURL = self.downloadDelegate.fileURL 291 | 292 | guard let validFileURL = fileURL else { 293 | return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) 294 | } 295 | 296 | do { 297 | let data = try Data(contentsOf: validFileURL) 298 | return self.validate(contentType: acceptableContentTypes, response: response, data: data) 299 | } catch { 300 | return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) 301 | } 302 | } 303 | } 304 | 305 | /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content 306 | /// type matches any specified in the Accept HTTP header field. 307 | /// 308 | /// If validation fails, subsequent calls to response handlers will have an associated error. 309 | /// 310 | /// - returns: The request. 311 | @discardableResult 312 | public func validate() -> Self { 313 | return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) 314 | } 315 | } 316 | -------------------------------------------------------------------------------- /Pods/Alamofire/Source/ServerTrustPolicy.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ServerTrustPolicy.swift 3 | // 4 | // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | // 24 | 25 | import Foundation 26 | 27 | /// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. 28 | open class ServerTrustPolicyManager { 29 | /// The dictionary of policies mapped to a particular host. 30 | open let policies: [String: ServerTrustPolicy] 31 | 32 | /// Initializes the `ServerTrustPolicyManager` instance with the given policies. 33 | /// 34 | /// Since different servers and web services can have different leaf certificates, intermediate and even root 35 | /// certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This 36 | /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key 37 | /// pinning for host3 and disabling evaluation for host4. 38 | /// 39 | /// - parameter policies: A dictionary of all policies mapped to a particular host. 40 | /// 41 | /// - returns: The new `ServerTrustPolicyManager` instance. 42 | public init(policies: [String: ServerTrustPolicy]) { 43 | self.policies = policies 44 | } 45 | 46 | /// Returns the `ServerTrustPolicy` for the given host if applicable. 47 | /// 48 | /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override 49 | /// this method and implement more complex mapping implementations such as wildcards. 50 | /// 51 | /// - parameter host: The host to use when searching for a matching policy. 52 | /// 53 | /// - returns: The server trust policy for the given host if found. 54 | open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { 55 | return policies[host] 56 | } 57 | } 58 | 59 | // MARK: - 60 | 61 | extension URLSession { 62 | private struct AssociatedKeys { 63 | static var managerKey = "URLSession.ServerTrustPolicyManager" 64 | } 65 | 66 | var serverTrustPolicyManager: ServerTrustPolicyManager? { 67 | get { 68 | return objc_getAssociatedObject(self, &AssociatedKeys.managerKey) as? ServerTrustPolicyManager 69 | } 70 | set (manager) { 71 | objc_setAssociatedObject(self, &AssociatedKeys.managerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) 72 | } 73 | } 74 | } 75 | 76 | // MARK: - ServerTrustPolicy 77 | 78 | /// The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when 79 | /// connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust 80 | /// with a given set of criteria to determine whether the server trust is valid and the connection should be made. 81 | /// 82 | /// Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other 83 | /// vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged 84 | /// to route all communication over an HTTPS connection with pinning enabled. 85 | /// 86 | /// - performDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to 87 | /// validate the host provided by the challenge. Applications are encouraged to always 88 | /// validate the host in production environments to guarantee the validity of the server's 89 | /// certificate chain. 90 | /// 91 | /// - performRevokedEvaluation: Uses the default and revoked server trust evaluations allowing you to control whether to 92 | /// validate the host provided by the challenge as well as specify the revocation flags for 93 | /// testing for revoked certificates. Apple platforms did not start testing for revoked 94 | /// certificates automatically until iOS 10.1, macOS 10.12 and tvOS 10.1 which is 95 | /// demonstrated in our TLS tests. Applications are encouraged to always validate the host 96 | /// in production environments to guarantee the validity of the server's certificate chain. 97 | /// 98 | /// - pinCertificates: Uses the pinned certificates to validate the server trust. The server trust is 99 | /// considered valid if one of the pinned certificates match one of the server certificates. 100 | /// By validating both the certificate chain and host, certificate pinning provides a very 101 | /// secure form of server trust validation mitigating most, if not all, MITM attacks. 102 | /// Applications are encouraged to always validate the host and require a valid certificate 103 | /// chain in production environments. 104 | /// 105 | /// - pinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered 106 | /// valid if one of the pinned public keys match one of the server certificate public keys. 107 | /// By validating both the certificate chain and host, public key pinning provides a very 108 | /// secure form of server trust validation mitigating most, if not all, MITM attacks. 109 | /// Applications are encouraged to always validate the host and require a valid certificate 110 | /// chain in production environments. 111 | /// 112 | /// - disableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. 113 | /// 114 | /// - customEvaluation: Uses the associated closure to evaluate the validity of the server trust. 115 | public enum ServerTrustPolicy { 116 | case performDefaultEvaluation(validateHost: Bool) 117 | case performRevokedEvaluation(validateHost: Bool, revocationFlags: CFOptionFlags) 118 | case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) 119 | case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) 120 | case disableEvaluation 121 | case customEvaluation((_ serverTrust: SecTrust, _ host: String) -> Bool) 122 | 123 | // MARK: - Bundle Location 124 | 125 | /// Returns all certificates within the given bundle with a `.cer` file extension. 126 | /// 127 | /// - parameter bundle: The bundle to search for all `.cer` files. 128 | /// 129 | /// - returns: All certificates within the given bundle. 130 | public static func certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] { 131 | var certificates: [SecCertificate] = [] 132 | 133 | let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in 134 | bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil) 135 | }.joined()) 136 | 137 | for path in paths { 138 | if 139 | let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, 140 | let certificate = SecCertificateCreateWithData(nil, certificateData) 141 | { 142 | certificates.append(certificate) 143 | } 144 | } 145 | 146 | return certificates 147 | } 148 | 149 | /// Returns all public keys within the given bundle with a `.cer` file extension. 150 | /// 151 | /// - parameter bundle: The bundle to search for all `*.cer` files. 152 | /// 153 | /// - returns: All public keys within the given bundle. 154 | public static func publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] { 155 | var publicKeys: [SecKey] = [] 156 | 157 | for certificate in certificates(in: bundle) { 158 | if let publicKey = publicKey(for: certificate) { 159 | publicKeys.append(publicKey) 160 | } 161 | } 162 | 163 | return publicKeys 164 | } 165 | 166 | // MARK: - Evaluation 167 | 168 | /// Evaluates whether the server trust is valid for the given host. 169 | /// 170 | /// - parameter serverTrust: The server trust to evaluate. 171 | /// - parameter host: The host of the challenge protection space. 172 | /// 173 | /// - returns: Whether the server trust is valid. 174 | public func evaluate(_ serverTrust: SecTrust, forHost host: String) -> Bool { 175 | var serverTrustIsValid = false 176 | 177 | switch self { 178 | case let .performDefaultEvaluation(validateHost): 179 | let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) 180 | SecTrustSetPolicies(serverTrust, policy) 181 | 182 | serverTrustIsValid = trustIsValid(serverTrust) 183 | case let .performRevokedEvaluation(validateHost, revocationFlags): 184 | let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) 185 | let revokedPolicy = SecPolicyCreateRevocation(revocationFlags) 186 | SecTrustSetPolicies(serverTrust, [defaultPolicy, revokedPolicy] as CFTypeRef) 187 | 188 | serverTrustIsValid = trustIsValid(serverTrust) 189 | case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost): 190 | if validateCertificateChain { 191 | let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) 192 | SecTrustSetPolicies(serverTrust, policy) 193 | 194 | SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates as CFArray) 195 | SecTrustSetAnchorCertificatesOnly(serverTrust, true) 196 | 197 | serverTrustIsValid = trustIsValid(serverTrust) 198 | } else { 199 | let serverCertificatesDataArray = certificateData(for: serverTrust) 200 | let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates) 201 | 202 | outerLoop: for serverCertificateData in serverCertificatesDataArray { 203 | for pinnedCertificateData in pinnedCertificatesDataArray { 204 | if serverCertificateData == pinnedCertificateData { 205 | serverTrustIsValid = true 206 | break outerLoop 207 | } 208 | } 209 | } 210 | } 211 | case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): 212 | var certificateChainEvaluationPassed = true 213 | 214 | if validateCertificateChain { 215 | let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) 216 | SecTrustSetPolicies(serverTrust, policy) 217 | 218 | certificateChainEvaluationPassed = trustIsValid(serverTrust) 219 | } 220 | 221 | if certificateChainEvaluationPassed { 222 | outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeys(for: serverTrust) as [AnyObject] { 223 | for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { 224 | if serverPublicKey.isEqual(pinnedPublicKey) { 225 | serverTrustIsValid = true 226 | break outerLoop 227 | } 228 | } 229 | } 230 | } 231 | case .disableEvaluation: 232 | serverTrustIsValid = true 233 | case let .customEvaluation(closure): 234 | serverTrustIsValid = closure(serverTrust, host) 235 | } 236 | 237 | return serverTrustIsValid 238 | } 239 | 240 | // MARK: - Private - Trust Validation 241 | 242 | private func trustIsValid(_ trust: SecTrust) -> Bool { 243 | var isValid = false 244 | 245 | var result = SecTrustResultType.invalid 246 | let status = SecTrustEvaluate(trust, &result) 247 | 248 | if status == errSecSuccess { 249 | let unspecified = SecTrustResultType.unspecified 250 | let proceed = SecTrustResultType.proceed 251 | 252 | 253 | isValid = result == unspecified || result == proceed 254 | } 255 | 256 | return isValid 257 | } 258 | 259 | // MARK: - Private - Certificate Data 260 | 261 | private func certificateData(for trust: SecTrust) -> [Data] { 262 | var certificates: [SecCertificate] = [] 263 | 264 | for index in 0.. [Data] { 274 | return certificates.map { SecCertificateCopyData($0) as Data } 275 | } 276 | 277 | // MARK: - Private - Public Key Extraction 278 | 279 | private static func publicKeys(for trust: SecTrust) -> [SecKey] { 280 | var publicKeys: [SecKey] = [] 281 | 282 | for index in 0.. SecKey? { 295 | var publicKey: SecKey? 296 | 297 | let policy = SecPolicyCreateBasicX509() 298 | var trust: SecTrust? 299 | let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) 300 | 301 | if let trust = trust, trustCreationStatus == errSecSuccess { 302 | publicKey = SecTrustCopyPublicKey(trust) 303 | } 304 | 305 | return publicKey 306 | } 307 | } 308 | -------------------------------------------------------------------------------- /Pods/SwiftyJSON/README.md: -------------------------------------------------------------------------------- 1 | # SwiftyJSON 2 | 3 | [![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg) ![Platform](https://img.shields.io/badge/platforms-iOS%208.0+%20%7C%20macOS%2010.10+%20%7C%20tvOS%209.0+%20%7C%20watchOS%202.0+-333333.svg) 4 | 5 | SwiftyJSON makes it easy to deal with JSON data in Swift. 6 | 7 | 1. [Why is the typical JSON handling in Swift NOT good](#why-is-the-typical-json-handling-in-swift-not-good) 8 | 2. [Requirements](#requirements) 9 | 3. [Integration](#integration) 10 | 4. [Usage](#usage) 11 | - [Initialization](#initialization) 12 | - [Subscript](#subscript) 13 | - [Loop](#loop) 14 | - [Error](#error) 15 | - [Optional getter](#optional-getter) 16 | - [Non-optional getter](#non-optional-getter) 17 | - [Setter](#setter) 18 | - [Raw object](#raw-object) 19 | - [Literal convertibles](#literal-convertibles) 20 | - [Merging](#merging) 21 | 5. [Work with Alamofire](#work-with-alamofire) 22 | 6. [Work with Moya](#work-with-moya) 23 | 24 | > For Legacy Swift support, take a look at the [swift2 branch](https://github.com/SwiftyJSON/SwiftyJSON/tree/swift2) 25 | 26 | > [中文介绍](http://tangplin.github.io/swiftyjson/) 27 | 28 | 29 | ## Why is the typical JSON handling in Swift NOT good? 30 | 31 | Swift is very strict about types. But although explicit typing is good for saving us from mistakes, it becomes painful when dealing with JSON and other areas that are, by nature, implicit about types. 32 | 33 | Take the Twitter API for example. Say we want to retrieve a user's "name" value of some tweet in Swift (according to Twitter's API https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline). 34 | 35 | The code would look like this: 36 | 37 | ```swift 38 | if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]], 39 | let user = statusesArray[0]["user"] as? [String: Any], 40 | let username = user["name"] as? String { 41 | // Finally we got the username 42 | } 43 | ``` 44 | 45 | It's not good. 46 | 47 | Even if we use optional chaining, it would be messy: 48 | 49 | ```swift 50 | if let JSONObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]], 51 | let username = (JSONObject[0]["user"] as? [String: Any])?["name"] as? String { 52 | // There's our username 53 | } 54 | ``` 55 | 56 | An unreadable mess--for something that should really be simple! 57 | 58 | With SwiftyJSON all you have to do is: 59 | 60 | ```swift 61 | let json = JSON(data: dataFromNetworking) 62 | if let userName = json[0]["user"]["name"].string { 63 | //Now you got your value 64 | } 65 | ``` 66 | 67 | And don't worry about the Optional Wrapping thing. It's done for you automatically. 68 | 69 | ```swift 70 | let json = JSON(data: dataFromNetworking) 71 | if let userName = json[999999]["wrong_key"]["wrong_name"].string { 72 | //Calm down, take it easy, the ".string" property still produces the correct Optional String type with safety 73 | } else { 74 | //Print the error 75 | print(json[999999]["wrong_key"]["wrong_name"]) 76 | } 77 | ``` 78 | 79 | ## Requirements 80 | 81 | - iOS 8.0+ | macOS 10.10+ | tvOS 9.0+ | watchOS 2.0+ 82 | - Xcode 8 83 | 84 | ## Integration 85 | 86 | #### CocoaPods (iOS 8+, OS X 10.9+) 87 | 88 | You can use [CocoaPods](http://cocoapods.org/) to install `SwiftyJSON` by adding it to your `Podfile`: 89 | 90 | ```ruby 91 | platform :ios, '8.0' 92 | use_frameworks! 93 | 94 | target 'MyApp' do 95 | pod 'SwiftyJSON' 96 | end 97 | ``` 98 | 99 | Note that this requires CocoaPods version 36, and your iOS deployment target to be at least 8.0: 100 | 101 | 102 | #### Carthage (iOS 8+, OS X 10.9+) 103 | 104 | You can use [Carthage](https://github.com/Carthage/Carthage) to install `SwiftyJSON` by adding it to your `Cartfile`: 105 | 106 | ``` 107 | github "SwiftyJSON/SwiftyJSON" 108 | ``` 109 | 110 | #### Swift Package Manager 111 | 112 | You can use [The Swift Package Manager](https://swift.org/package-manager) to install `SwiftyJSON` by adding the proper description to your `Package.swift` file: 113 | 114 | ```swift 115 | import PackageDescription 116 | 117 | let package = Package( 118 | name: "YOUR_PROJECT_NAME", 119 | targets: [], 120 | dependencies: [ 121 | .Package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", versions: Version(1, 0, 0).. = json["list"].arrayValue 329 | ``` 330 | 331 | ```swift 332 | // If not a Dictionary or nil, return [:] 333 | let user: Dictionary = json["user"].dictionaryValue 334 | ``` 335 | 336 | #### Setter 337 | 338 | ```swift 339 | json["name"] = JSON("new-name") 340 | json[0] = JSON(1) 341 | ``` 342 | 343 | ```swift 344 | json["id"].int = 1234567890 345 | json["coordinate"].double = 8766.766 346 | json["name"].string = "Jack" 347 | json.arrayObject = [1,2,3,4] 348 | json.dictionaryObject = ["name":"Jack", "age":25] 349 | ``` 350 | 351 | #### Raw object 352 | 353 | ```swift 354 | let rawObject: Any = json.object 355 | ``` 356 | 357 | ```swift 358 | let rawValue: Any = json.rawValue 359 | ``` 360 | 361 | ```swift 362 | //convert the JSON to raw NSData 363 | do { 364 | let rawData = try json.rawData() 365 | //Do something you want 366 | } catch { 367 | print("Error \(error)") 368 | } 369 | ``` 370 | 371 | ```swift 372 | //convert the JSON to a raw String 373 | if let rawString = json.rawString() { 374 | //Do something you want 375 | } else { 376 | print("json.rawString is nil") 377 | } 378 | ``` 379 | 380 | #### Existence 381 | 382 | ```swift 383 | // shows you whether value specified in JSON or not 384 | if json["name"].exists() 385 | ``` 386 | 387 | #### Literal convertibles 388 | 389 | For more info about literal convertibles: [Swift Literal Convertibles](http://nshipster.com/swift-literal-convertible/) 390 | 391 | ```swift 392 | // StringLiteralConvertible 393 | let json: JSON = "I'm a json" 394 | ``` 395 | 396 | ```swift 397 | / /IntegerLiteralConvertible 398 | let json: JSON = 12345 399 | ``` 400 | 401 | ```swift 402 | // BooleanLiteralConvertible 403 | let json: JSON = true 404 | ``` 405 | 406 | ```swift 407 | // FloatLiteralConvertible 408 | let json: JSON = 2.8765 409 | ``` 410 | 411 | ```swift 412 | // DictionaryLiteralConvertible 413 | let json: JSON = ["I":"am", "a":"json"] 414 | ``` 415 | 416 | ```swift 417 | // ArrayLiteralConvertible 418 | let json: JSON = ["I", "am", "a", "json"] 419 | ``` 420 | 421 | ```swift 422 | // With subscript in array 423 | var json: JSON = [1,2,3] 424 | json[0] = 100 425 | json[1] = 200 426 | json[2] = 300 427 | json[999] = 300 // Don't worry, nothing will happen 428 | ``` 429 | 430 | ```swift 431 | // With subscript in dictionary 432 | var json: JSON = ["name": "Jack", "age": 25] 433 | json["name"] = "Mike" 434 | json["age"] = "25" // It's OK to set String 435 | json["address"] = "L.A." // Add the "address": "L.A." in json 436 | ``` 437 | 438 | ```swift 439 | // Array & Dictionary 440 | var json: JSON = ["name": "Jack", "age": 25, "list": ["a", "b", "c", ["what": "this"]]] 441 | json["list"][3]["what"] = "that" 442 | json["list",3,"what"] = "that" 443 | let path: [JSONSubscriptType] = ["list",3,"what"] 444 | json[path] = "that" 445 | ``` 446 | 447 | ```swift 448 | // With other JSON objects 449 | let user: JSON = ["username" : "Steve", "password": "supersecurepassword"] 450 | let auth: JSON = [ 451 | "user": user.object, // use user.object instead of just user 452 | "apikey": "supersecretapitoken" 453 | ] 454 | ``` 455 | 456 | #### Merging 457 | 458 | It is possible to merge one JSON into another JSON. Merging a JSON into another JSON adds all non existing values to the original JSON which are only present in the `other` JSON. 459 | 460 | If both JSONs contain a value for the same key, _mostly_ this value gets overwritten in the original JSON, but there are two cases where it provides some special treatment: 461 | 462 | - In case of both values being a `JSON.Type.array` the values form the array found in the `other` JSON getting appended to the original JSON's array value. 463 | - In case of both values being a `JSON.Type.dictionary` both JSON-values are getting merged the same way the encapsulating JSON is merged. 464 | 465 | In case, where two fields in a JSON have a different types, the value will get always overwritten. 466 | 467 | There are two different fashions for merging: `merge` modifies the original JSON, whereas `merged` works non-destructively on a copy. 468 | 469 | ```swift 470 | let original: JSON = [ 471 | "first_name": "John", 472 | "age": 20, 473 | "skills": ["Coding", "Reading"], 474 | "address": [ 475 | "street": "Front St", 476 | "zip": "12345", 477 | ] 478 | ] 479 | 480 | let update: JSON = [ 481 | "last_name": "Doe", 482 | "age": 21, 483 | "skills": ["Writing"], 484 | "address": [ 485 | "zip": "12342", 486 | "city": "New York City" 487 | ] 488 | ] 489 | 490 | let updated = original.merge(with: update) 491 | // [ 492 | // "first_name": "John", 493 | // "last_name": "Doe", 494 | // "age": 21, 495 | // "skills": ["Coding", "Reading", "Writing"], 496 | // "address": [ 497 | // "street": "Front St", 498 | // "zip": "12342", 499 | // "city": "New York City" 500 | // ] 501 | // ] 502 | ``` 503 | 504 | ## String representation 505 | There are two options available: 506 | - use the default Swift one 507 | - use a custom one that will handle optionals well and represent `nil` as `"null"`: 508 | ```swift 509 | let dict = ["1":2, "2":"two", "3": nil] as [String: Any?] 510 | let json = JSON(dict) 511 | let representation = json.rawString(options: [.castNilToNSNull: true]) 512 | // representation is "{\"1\":2,\"2\":\"two\",\"3\":null}", which represents {"1":2,"2":"two","3":null} 513 | ``` 514 | 515 | ## Work with [Alamofire](https://github.com/Alamofire/Alamofire) 516 | 517 | SwiftyJSON nicely wraps the result of the Alamofire JSON response handler: 518 | 519 | ```swift 520 | Alamofire.request(url, method: .get).validate().responseJSON { response in 521 | switch response.result { 522 | case .success(let value): 523 | let json = JSON(value) 524 | print("JSON: \(json)") 525 | case .failure(let error): 526 | print(error) 527 | } 528 | } 529 | ``` 530 | 531 | We also provide an extension of Alamofire for serializing NSData to SwiftyJSON's JSON. 532 | 533 | See: [Alamofire-SwiftyJSON](https://github.com/SwiftyJSON/Alamofire-SwiftyJSON) 534 | 535 | 536 | ## Work with [Moya](https://github.com/Moya/Moya) 537 | 538 | SwiftyJSON parse data to JSON: 539 | 540 | ```swift 541 | let provider = MoyaProvider() 542 | provider.request(.showProducts) { result in 543 | switch result { 544 | case let .success(moyaResponse): 545 | let data = moyaResponse.data 546 | let json = JSON(data: data) // convert network data to json 547 | print(json) 548 | case let .failure(error): 549 | print("error: \(error)") 550 | } 551 | } 552 | 553 | ``` 554 | -------------------------------------------------------------------------------- /Pods/Alamofire/Source/TaskDelegate.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TaskDelegate.swift 3 | // 4 | // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) 5 | // 6 | // Permission is hereby granted, free of charge, to any person obtaining a copy 7 | // of this software and associated documentation files (the "Software"), to deal 8 | // in the Software without restriction, including without limitation the rights 9 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | // copies of the Software, and to permit persons to whom the Software is 11 | // furnished to do so, subject to the following conditions: 12 | // 13 | // The above copyright notice and this permission notice shall be included in 14 | // all copies or substantial portions of the Software. 15 | // 16 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | // THE SOFTWARE. 23 | // 24 | 25 | import Foundation 26 | 27 | /// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as 28 | /// executing all operations attached to the serial operation queue upon task completion. 29 | open class TaskDelegate: NSObject { 30 | 31 | // MARK: Properties 32 | 33 | /// The serial operation queue used to execute all operations after the task completes. 34 | open let queue: OperationQueue 35 | 36 | /// The data returned by the server. 37 | public var data: Data? { return nil } 38 | 39 | /// The error generated throughout the lifecyle of the task. 40 | public var error: Error? 41 | 42 | var task: URLSessionTask? { 43 | set { 44 | taskLock.lock(); defer { taskLock.unlock() } 45 | _task = newValue 46 | } 47 | get { 48 | taskLock.lock(); defer { taskLock.unlock() } 49 | return _task 50 | } 51 | } 52 | 53 | var initialResponseTime: CFAbsoluteTime? 54 | var credential: URLCredential? 55 | var metrics: AnyObject? // URLSessionTaskMetrics 56 | 57 | private var _task: URLSessionTask? { 58 | didSet { reset() } 59 | } 60 | 61 | private let taskLock = NSLock() 62 | 63 | // MARK: Lifecycle 64 | 65 | init(task: URLSessionTask?) { 66 | _task = task 67 | 68 | self.queue = { 69 | let operationQueue = OperationQueue() 70 | 71 | operationQueue.maxConcurrentOperationCount = 1 72 | operationQueue.isSuspended = true 73 | operationQueue.qualityOfService = .utility 74 | 75 | return operationQueue 76 | }() 77 | } 78 | 79 | func reset() { 80 | error = nil 81 | initialResponseTime = nil 82 | } 83 | 84 | // MARK: URLSessionTaskDelegate 85 | 86 | var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? 87 | var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? 88 | var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? 89 | var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)? 90 | 91 | @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:) 92 | func urlSession( 93 | _ session: URLSession, 94 | task: URLSessionTask, 95 | willPerformHTTPRedirection response: HTTPURLResponse, 96 | newRequest request: URLRequest, 97 | completionHandler: @escaping (URLRequest?) -> Void) 98 | { 99 | var redirectRequest: URLRequest? = request 100 | 101 | if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { 102 | redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) 103 | } 104 | 105 | completionHandler(redirectRequest) 106 | } 107 | 108 | @objc(URLSession:task:didReceiveChallenge:completionHandler:) 109 | func urlSession( 110 | _ session: URLSession, 111 | task: URLSessionTask, 112 | didReceive challenge: URLAuthenticationChallenge, 113 | completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) 114 | { 115 | var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling 116 | var credential: URLCredential? 117 | 118 | if let taskDidReceiveChallenge = taskDidReceiveChallenge { 119 | (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) 120 | } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { 121 | let host = challenge.protectionSpace.host 122 | 123 | if 124 | let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), 125 | let serverTrust = challenge.protectionSpace.serverTrust 126 | { 127 | if serverTrustPolicy.evaluate(serverTrust, forHost: host) { 128 | disposition = .useCredential 129 | credential = URLCredential(trust: serverTrust) 130 | } else { 131 | disposition = .cancelAuthenticationChallenge 132 | } 133 | } 134 | } else { 135 | if challenge.previousFailureCount > 0 { 136 | disposition = .rejectProtectionSpace 137 | } else { 138 | credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) 139 | 140 | if credential != nil { 141 | disposition = .useCredential 142 | } 143 | } 144 | } 145 | 146 | completionHandler(disposition, credential) 147 | } 148 | 149 | @objc(URLSession:task:needNewBodyStream:) 150 | func urlSession( 151 | _ session: URLSession, 152 | task: URLSessionTask, 153 | needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) 154 | { 155 | var bodyStream: InputStream? 156 | 157 | if let taskNeedNewBodyStream = taskNeedNewBodyStream { 158 | bodyStream = taskNeedNewBodyStream(session, task) 159 | } 160 | 161 | completionHandler(bodyStream) 162 | } 163 | 164 | @objc(URLSession:task:didCompleteWithError:) 165 | func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { 166 | if let taskDidCompleteWithError = taskDidCompleteWithError { 167 | taskDidCompleteWithError(session, task, error) 168 | } else { 169 | if let error = error { 170 | if self.error == nil { self.error = error } 171 | 172 | if 173 | let downloadDelegate = self as? DownloadTaskDelegate, 174 | let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data 175 | { 176 | downloadDelegate.resumeData = resumeData 177 | } 178 | } 179 | 180 | queue.isSuspended = false 181 | } 182 | } 183 | } 184 | 185 | // MARK: - 186 | 187 | class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate { 188 | 189 | // MARK: Properties 190 | 191 | var dataTask: URLSessionDataTask { return task as! URLSessionDataTask } 192 | 193 | override var data: Data? { 194 | if dataStream != nil { 195 | return nil 196 | } else { 197 | return mutableData 198 | } 199 | } 200 | 201 | var progress: Progress 202 | var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? 203 | 204 | var dataStream: ((_ data: Data) -> Void)? 205 | 206 | private var totalBytesReceived: Int64 = 0 207 | private var mutableData: Data 208 | 209 | private var expectedContentLength: Int64? 210 | 211 | // MARK: Lifecycle 212 | 213 | override init(task: URLSessionTask?) { 214 | mutableData = Data() 215 | progress = Progress(totalUnitCount: 0) 216 | 217 | super.init(task: task) 218 | } 219 | 220 | override func reset() { 221 | super.reset() 222 | 223 | progress = Progress(totalUnitCount: 0) 224 | totalBytesReceived = 0 225 | mutableData = Data() 226 | expectedContentLength = nil 227 | } 228 | 229 | // MARK: URLSessionDataDelegate 230 | 231 | var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? 232 | var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? 233 | var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? 234 | var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? 235 | 236 | func urlSession( 237 | _ session: URLSession, 238 | dataTask: URLSessionDataTask, 239 | didReceive response: URLResponse, 240 | completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) 241 | { 242 | var disposition: URLSession.ResponseDisposition = .allow 243 | 244 | expectedContentLength = response.expectedContentLength 245 | 246 | if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { 247 | disposition = dataTaskDidReceiveResponse(session, dataTask, response) 248 | } 249 | 250 | completionHandler(disposition) 251 | } 252 | 253 | func urlSession( 254 | _ session: URLSession, 255 | dataTask: URLSessionDataTask, 256 | didBecome downloadTask: URLSessionDownloadTask) 257 | { 258 | dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) 259 | } 260 | 261 | func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { 262 | if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } 263 | 264 | if let dataTaskDidReceiveData = dataTaskDidReceiveData { 265 | dataTaskDidReceiveData(session, dataTask, data) 266 | } else { 267 | if let dataStream = dataStream { 268 | dataStream(data) 269 | } else { 270 | mutableData.append(data) 271 | } 272 | 273 | let bytesReceived = Int64(data.count) 274 | totalBytesReceived += bytesReceived 275 | let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown 276 | 277 | progress.totalUnitCount = totalBytesExpected 278 | progress.completedUnitCount = totalBytesReceived 279 | 280 | if let progressHandler = progressHandler { 281 | progressHandler.queue.async { progressHandler.closure(self.progress) } 282 | } 283 | } 284 | } 285 | 286 | func urlSession( 287 | _ session: URLSession, 288 | dataTask: URLSessionDataTask, 289 | willCacheResponse proposedResponse: CachedURLResponse, 290 | completionHandler: @escaping (CachedURLResponse?) -> Void) 291 | { 292 | var cachedResponse: CachedURLResponse? = proposedResponse 293 | 294 | if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { 295 | cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) 296 | } 297 | 298 | completionHandler(cachedResponse) 299 | } 300 | } 301 | 302 | // MARK: - 303 | 304 | class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate { 305 | 306 | // MARK: Properties 307 | 308 | var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask } 309 | 310 | var progress: Progress 311 | var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? 312 | 313 | var resumeData: Data? 314 | override var data: Data? { return resumeData } 315 | 316 | var destination: DownloadRequest.DownloadFileDestination? 317 | 318 | var temporaryURL: URL? 319 | var destinationURL: URL? 320 | 321 | var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL } 322 | 323 | // MARK: Lifecycle 324 | 325 | override init(task: URLSessionTask?) { 326 | progress = Progress(totalUnitCount: 0) 327 | super.init(task: task) 328 | } 329 | 330 | override func reset() { 331 | super.reset() 332 | 333 | progress = Progress(totalUnitCount: 0) 334 | resumeData = nil 335 | } 336 | 337 | // MARK: URLSessionDownloadDelegate 338 | 339 | var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)? 340 | var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? 341 | var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? 342 | 343 | func urlSession( 344 | _ session: URLSession, 345 | downloadTask: URLSessionDownloadTask, 346 | didFinishDownloadingTo location: URL) 347 | { 348 | temporaryURL = location 349 | 350 | guard 351 | let destination = destination, 352 | let response = downloadTask.response as? HTTPURLResponse 353 | else { return } 354 | 355 | let result = destination(location, response) 356 | let destinationURL = result.destinationURL 357 | let options = result.options 358 | 359 | self.destinationURL = destinationURL 360 | 361 | do { 362 | if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) { 363 | try FileManager.default.removeItem(at: destinationURL) 364 | } 365 | 366 | if options.contains(.createIntermediateDirectories) { 367 | let directory = destinationURL.deletingLastPathComponent() 368 | try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) 369 | } 370 | 371 | try FileManager.default.moveItem(at: location, to: destinationURL) 372 | } catch { 373 | self.error = error 374 | } 375 | } 376 | 377 | func urlSession( 378 | _ session: URLSession, 379 | downloadTask: URLSessionDownloadTask, 380 | didWriteData bytesWritten: Int64, 381 | totalBytesWritten: Int64, 382 | totalBytesExpectedToWrite: Int64) 383 | { 384 | if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } 385 | 386 | if let downloadTaskDidWriteData = downloadTaskDidWriteData { 387 | downloadTaskDidWriteData( 388 | session, 389 | downloadTask, 390 | bytesWritten, 391 | totalBytesWritten, 392 | totalBytesExpectedToWrite 393 | ) 394 | } else { 395 | progress.totalUnitCount = totalBytesExpectedToWrite 396 | progress.completedUnitCount = totalBytesWritten 397 | 398 | if let progressHandler = progressHandler { 399 | progressHandler.queue.async { progressHandler.closure(self.progress) } 400 | } 401 | } 402 | } 403 | 404 | func urlSession( 405 | _ session: URLSession, 406 | downloadTask: URLSessionDownloadTask, 407 | didResumeAtOffset fileOffset: Int64, 408 | expectedTotalBytes: Int64) 409 | { 410 | if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { 411 | downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) 412 | } else { 413 | progress.totalUnitCount = expectedTotalBytes 414 | progress.completedUnitCount = fileOffset 415 | } 416 | } 417 | } 418 | 419 | // MARK: - 420 | 421 | class UploadTaskDelegate: DataTaskDelegate { 422 | 423 | // MARK: Properties 424 | 425 | var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask } 426 | 427 | var uploadProgress: Progress 428 | var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? 429 | 430 | // MARK: Lifecycle 431 | 432 | override init(task: URLSessionTask?) { 433 | uploadProgress = Progress(totalUnitCount: 0) 434 | super.init(task: task) 435 | } 436 | 437 | override func reset() { 438 | super.reset() 439 | uploadProgress = Progress(totalUnitCount: 0) 440 | } 441 | 442 | // MARK: URLSessionTaskDelegate 443 | 444 | var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? 445 | 446 | func URLSession( 447 | _ session: URLSession, 448 | task: URLSessionTask, 449 | didSendBodyData bytesSent: Int64, 450 | totalBytesSent: Int64, 451 | totalBytesExpectedToSend: Int64) 452 | { 453 | if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } 454 | 455 | if let taskDidSendBodyData = taskDidSendBodyData { 456 | taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) 457 | } else { 458 | uploadProgress.totalUnitCount = totalBytesExpectedToSend 459 | uploadProgress.completedUnitCount = totalBytesSent 460 | 461 | if let uploadProgressHandler = uploadProgressHandler { 462 | uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) } 463 | } 464 | } 465 | } 466 | } 467 | --------------------------------------------------------------------------------